Skip to content

eBPF-based security platform

2.5 KB
Raw Blame
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c) 2026 Authors of shirudo
"""Generate the sensitive-path watch rules as a C header."""

from __future__ import annotations

import argparse
from pathlib import Path

MAX_RULES = 64
NAME_MAX = 31


def c_string(value: str) -> str:
	return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'


def read_rules(path: Path) -> list[tuple[str, str, int]]:
	rules: list[tuple[str, str, int]] = []
	seen: set[tuple[str, str]] = set()
	for line_number, raw in enumerate(path.read_text().splitlines(), 1):
		text = raw.split("#", 1)[0].strip()
		if not text:
			continue
		fields = text.split()
		pattern = fields[0]
		flags = 0
		for option in fields[1:]:
			if option == "w":
				flags |= 1
			else:
				raise ValueError(f"{path}:{line_number}: unknown option {option!r}")
		parent, _, name = pattern.rpartition("/")
		if "/" in parent or not name:
			raise ValueError(f"{path}:{line_number}: pattern must be name or parent/name")
		if name == "*":
			if not parent:
				raise ValueError(f"{path}:{line_number}: '*' needs a parent")
			name = ""
			flags |= 2
		for part in (parent, name):
			if len(part.encode()) > NAME_MAX:
				raise ValueError(f"{path}:{line_number}: component longer than {NAME_MAX} bytes")
		if (parent, name) in seen:
			continue
		seen.add((parent, name))
		rules.append((name, parent, flags))
	if len(rules) > MAX_RULES:
		raise ValueError(f"{path}: more than {MAX_RULES} rules")
	return rules


def main() -> int:
	parser = argparse.ArgumentParser(description=__doc__)
	parser.add_argument("list", type=Path)
	parser.add_argument("output", type=Path)
	args = parser.parse_args()

	rules = read_rules(args.list)
	lines = [
		"/* SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause */",
		"/* Generated by gen_file_watch.py; do not edit manually. */",
		f"/* Source: {args.list.name}; rules: {len(rules)}. */",
		"#ifndef OBS_FILE_WATCH_GENERATED_H",
		"#define OBS_FILE_WATCH_GENERATED_H",
		f"#define OBS_FILE_WATCH_RULES {max(len(rules), 1)}u",
		"#define OBS_FILE_WATCH_INIT { \\",
	]
	if not rules:
		lines.append('\t{ .name = "", .parent = "", .flags = 4 }, \\')
	for name, parent, flags in rules:
		lines.append(f"\t{{ .name = {c_string(name)}, .parent = {c_string(parent)}, "
			     f".flags = {flags} }}, \\")
	lines.append("}")
	lines.append("#endif /* OBS_FILE_WATCH_GENERATED_H */")
	lines.append("")
	args.output.write_text("\n".join(lines))
	return 0


if __name__ == "__main__":
	raise SystemExit(main())