[PATCH v2 03/11] kconfig-audit: Add the configuration checker code
From: Ahmed S. Darwish
Date: Thu Dec 03 2026 - 17:49:45 EST
Introduce the kconfig-audit tool to validate a kernel .config against a
YAML policy and report violations by severity.
For correctness, readability, and long-term maintainability, type-annotate
all the Python code and split the tool's logic into a clean set of classes.
Build a proper data model for policies and .config symbols. Implement all
configuration checking logic in terms of that model, and never on the YAML
files dictionaries.
Clearly document the tool's development rules on top.
Signed-off-by: Ahmed S. Darwish <darwi@xxxxxxxxxxxxx>
---
tools/kconfig-audit/audit.py | 908 +++++++++++++++++++++++++++++++++++
1 file changed, 908 insertions(+)
create mode 100755 tools/kconfig-audit/audit.py
diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
new file mode 100755
index 000000000000..6ff4a56281ad
--- /dev/null
+++ b/tools/kconfig-audit/audit.py
@@ -0,0 +1,908 @@
+#!/usr/bin/env python3
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Kernel .config audit
+#
+# Main usage:
+#
+# $ audit.py list-policies
+# $ audit.py list-api-versions
+#
+# $ audit.py check -c path/to/.config -p preempt_rt
+#
+# Development rules:
+#
+# - Full type-annotations are required. Verify type-safety using:
+#
+# $ mypy --strict --no-warn-return-any audit.py
+#
+# - The minimum required Python version must not be newer than what is
+# required by the kernel build at Documentation/process/changes.rst.
+#
+# - The tool must not depend on being run inside the kernel source tree.
+# This simplifies invocation, testing and possible future packaging.
+#
+# - Keep the parsing code and the internal data model separate:
+#
+# KernelConfig # internal model, typed .config symbols repo
+# KernelConfigFile # parser
+#
+# Policy # internal model, typed policy rules repo
+# PolicyFile # parser
+#
+# Schema # internal model, dictionary-like
+# SchemaFile # parser
+#
+# - The YAML policy files are only treated as a serialization format.
+# After loading and schema validation, such rules are parsed into the
+# internal data model: Severity, Rule, SymbolRule, PatternRule, Policy,
+# and other Python objects.
+#
+# The .config check logic must operate on that typed Python model, and
+# _never_ on the raw YAML dictionaries.
+#
+# - Schema versioning must be handled only during parsing. Keep the
+# internal data model free from any version tags. Keep the .config
+# checker logic free from any schema versioning conditionals.
+#
+# - During parsing, never re-validate what has already been validated by
+# the schema. It is redundant and makes the parser unnecessarily ugly.
+#
+# - Open all policy files with a UTF-8 encoding, so that users can include
+# non-ASCII characters in a policy rule's rationale.
+#
+# - Minimize external dependencies, as this tool is also intended to be run
+# from distributions kernel packaging scripts in the future.
+#
+# - Code simplicity and clarity is favored over random policy features.
+# Before submitting new features, please prove beforehand that they are
+# required by a mainline real-world use case; e.g. a new mainline policy.
+#
+# Script Exit Codes:
+#
+# os.EX_CONFIG passed kernel .config does not match policy
+# os.EX_NOINPUT input file(s) could not be opened
+# os.EX_DATAERR YAML/schema/rule data is malformed
+# os.EX_UNAVAILABLE Python version or dependency is unavailable
+#
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import sys
+import textwrap
+
+from dataclasses import dataclass, field
+from enum import Enum, auto
+from pathlib import Path
+from typing import Any, ClassVar, Final, Mapping, NoReturn, Optional
+
+#
+# Initial sanity checks:
+#
+
+def warn(message: str) -> None:
+ print(message, file=sys.stderr)
+
+def error(message: str, code: int) -> NoReturn:
+ print(f'Error: {message}', file=sys.stderr)
+ sys.exit(code)
+
+if sys.version_info < (3, 9):
+ error('Python 3.9 or later is required', os.EX_UNAVAILABLE)
+
+try:
+ import jsonschema # type: ignore
+ import yaml as yaml_m # type: ignore
+except ModuleNotFoundError as e:
+ error(f'Missing Python module: {e.name}', os.EX_UNAVAILABLE)
+
+#
+# Kernel .config model:
+#
+
+@dataclass(eq=False)
+class Symbol():
+ """Kernel .config symbol"""
+ name: str
+
+@dataclass(eq=False)
+class BooleanSymbol(Symbol):
+ """Kconfig 'tristate' symbol, where value=True implies 'y' or 'm'"""
+ value: bool
+
+@dataclass(eq=False)
+class IntSymbol(Symbol):
+ """Kconfig int symbol"""
+ value: int
+
+@dataclass(eq=False)
+class HexSymbol(Symbol):
+ """Kconfig hex symbol"""
+ value: int
+
+@dataclass(eq=False)
+class StringSymbol(Symbol):
+ """Kconfig string symbol"""
+ value: str
+
+@dataclass
+class KernelConfig:
+ """Internal repository for parsed kconfig symbols"""
+ symbols: dict[str, Symbol] = field(default_factory=dict)
+
+ def add_symbol(self, symbol: Symbol) -> None:
+ if symbol.name in self.symbols:
+ error(f'.config defines {symbol.name} more than once', os.EX_DATAERR)
+
+ self.symbols[symbol.name] = symbol
+
+ def add_bool_symbol(self, name: str, val: bool) -> None:
+ self.add_symbol(BooleanSymbol(name, val))
+
+ def add_str_symbol(self, name: str, val: str) -> None:
+ self.add_symbol(StringSymbol(name, val))
+
+ def add_int_symbol(self, name: str, val: int) -> None:
+ self.add_symbol(IntSymbol(name, val))
+
+ def add_hex_symbol(self, name: str, val: int) -> None:
+ self.add_symbol(HexSymbol(name, val))
+
+ def get_symbol(self, sym_name: str) -> Optional[Symbol]:
+ return self.symbols.get(sym_name)
+
+ def get_matching_symbols(self, pa: re.Pattern[str]) -> list[Symbol]:
+ """Get all symbols whose names match the passed regex"""
+ return [sym for sym in self.symbols.values() if pa.search(sym.name)]
+
+class KernelConfigFile:
+ """Kernel .config file parser (to a KernelConfig model)"""
+
+ def __init__(self, file: Path):
+ try:
+ self.lines = file.read_text(encoding='utf-8').splitlines()
+ except OSError as e:
+ error(f'Could not open {file}: {e.strerror}', os.EX_NOINPUT)
+ except UnicodeError as e:
+ error(f'Invalid UTF-8 in {file}: {e}', os.EX_DATAERR)
+
+ def parse(self) -> KernelConfig:
+ """Parse .config file into a repository of Symbol objects"""
+ config = KernelConfig()
+
+ symbol_unset = re.compile(r'^# (CONFIG_[A-Za-z0-9_]+) is not set$')
+ symbol_assign = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=(.*)$')
+
+ comment = re.compile('^#')
+ empty_line = re.compile('^$')
+
+ for line in self.lines:
+ if m := symbol_unset.match(line):
+ config.add_bool_symbol(m.group(1), False)
+ continue
+
+ if not (m := symbol_assign.match(line)):
+ if not comment.match(line) and not empty_line.match(line):
+ error(f'Invalid .config line: {line}', os.EX_DATAERR)
+ continue
+
+ name, val = m.group(1), m.group(2)
+
+ if val in ('y', 'm'):
+ config.add_bool_symbol(name, True)
+ elif re.fullmatch(r'0[xX][0-9a-fA-F]+', val):
+ config.add_hex_symbol(name, int(val, 16))
+ elif re.fullmatch(r'-?[0-9]+', val):
+ config.add_int_symbol(name, int(val))
+ elif len(val) >= 2 and val[0] == '"' and val[-1] == '"':
+ config.add_str_symbol(name, val[1:-1])
+ else:
+ error(f'Invalid .config assignment: {line}', os.EX_DATAERR)
+
+ return config
+
+#
+# Shared code for YAML files access:
+#
+
+YamlDict = dict[str, Any]
+
+class Helpers:
+
+ @staticmethod
+ def load_yaml(yaml_f: Path) -> YamlDict:
+ """
+ Load a YAML file and return its top-level mapping.
+
+ If the file cannot be opened, contains invalid UTF-8, contains invalid
+ YAML syntax, or does not contain a top-level mapping, report the error
+ and exit the script.
+ """
+ try:
+ with open(yaml_f, 'r', encoding='utf-8') as f:
+ yaml = yaml_m.safe_load(f)
+ except OSError as e:
+ error(f'Could not open {yaml_f}: {e.strerror}', os.EX_NOINPUT)
+ except UnicodeError as e:
+ error(f'Invalid UTF-8 in {yaml_f}: {e}', os.EX_DATAERR)
+ except yaml_m.YAMLError as e:
+ error(f'Invalid YAML syntax at {yaml_f}:\n {e}', os.EX_DATAERR)
+
+ if not isinstance(yaml, dict):
+ error(
+ f'{yaml_f.name} must contain a YAML mapping at the top level',
+ os.EX_DATAERR,
+ )
+
+ return yaml
+
+ @staticmethod
+ def validate_yaml(yaml: YamlDict, schema: Schema, f_name: str) -> None:
+ """Validate a parsed YAML mapping against passed JSON Schema"""
+ try:
+ # For regex validation, manually enforce a format checker
+ jsonschema.validate(
+ yaml,
+ schema,
+ format_checker=jsonschema.FormatChecker(),
+ )
+ except jsonschema.exceptions.ValidationError as e:
+ error(
+ f'{f_name} does not match its schema\n'
+ f'Reason: {e.message}',
+ os.EX_DATAERR
+ )
+
+ @staticmethod
+ def unreachable(message: str) -> NoReturn:
+ """For type checkers and readers, mark an unreachable code path"""
+ raise AssertionError(f'unreachable: {message}')
+
+class VersionedYamlFile:
+ """YAML file whose api_version field selects its validation schema"""
+
+ # Version tags for the entirety of kconfig-audit YAML files
+ AUDIT_API_V1: Final = 'kconfig-audit.kernel.org/v1'
+
+ # Map kconfig-audit version tags to YAML schema file names. To be
+ # filled by children classes.
+ SCHEMAS: ClassVar[Mapping[str, str]] = {}
+
+ yaml: YamlDict
+
+ def __init__(self, yaml_f: Path, schema_dir: Path):
+ """Open YAML file and load its validated dictionary mappings"""
+ self.yaml_f = yaml_f
+ self.yaml = Helpers.load_yaml(yaml_f)
+ self._validate_yaml(schema_dir)
+
+ def _validate_yaml(self, schema_dir: Path) -> None:
+ """Validate this YAML file against its selected schema"""
+ api_version = self._read_api_version()
+ schema_f = schema_dir / self.SCHEMAS[api_version]
+
+ schema = SchemaFile(schema_f).parse()
+ Helpers.validate_yaml(self.yaml, schema, self.yaml_f.name)
+
+ def _read_api_version(self) -> str:
+ """Read and validate api_version to select the YAML schema"""
+ api_version = self.yaml.get('api_version')
+
+ if not api_version:
+ error(
+ f'{self.yaml_f.name}: missing api_version field',
+ os.EX_DATAERR,
+ )
+ if not isinstance(api_version, str):
+ error(
+ f'{self.yaml_f.name}: api_version must be a string',
+ os.EX_DATAERR,
+ )
+
+ if api_version in self.SCHEMAS:
+ return api_version
+
+ versions = '\n\t'.join(self.SCHEMAS)
+ warn(f'Supported API versions:\n\t{versions}\n')
+ error(
+ f'{self.yaml_f.name}: Unknown API version: {api_version}',
+ os.EX_DATAERR,
+ )
+
+#
+# Schema model:
+#
+
+class Schema(YamlDict):
+ """Modeled policy schema, as a YAML dictionary mapping"""
+
+class SchemaFile:
+ """json-schema.org policy schema parser (to Schema model)"""
+
+ def __init__(self, schema_f: Path):
+ self.schema_f = schema_f
+ self.yaml = Helpers.load_yaml(schema_f)
+
+ def parse(self) -> Schema:
+ """Parse and validate a policy schema file"""
+
+ schema = Schema(self.yaml)
+
+ # Validate the schema against its own draft-07 grammar
+ try:
+ jsonschema.Draft7Validator.check_schema(schema)
+ except jsonschema.exceptions.SchemaError as e:
+ error(
+ f'Invalid schema {self.schema_f}:\nReason: {e.message}',
+ os.EX_DATAERR,
+ )
+
+ return schema
+
+#
+# Policy model:
+#
+
+class ExpectedValue(Enum):
+ """Expected values for a .config symbol"""
+
+ enabled = auto() # Implies both a built-in or a module, as in schema
+ disabled = auto()
+ neutral = auto()
+
+class Severity(Enum):
+ """Rule-check severity"""
+
+ fatal = auto()
+ high = auto()
+ medium = auto()
+ low = auto()
+ info = auto()
+
+@dataclass
+class Rule:
+ """Single rule entry"""
+
+ expected: ExpectedValue
+ severity: Severity
+ rationale: Optional[str]
+ docs_hint: Optional[str]
+
+ def __post_init__(self) -> None:
+ self._normalize_docs_hint()
+
+ def _normalize_docs_hint(self) -> None:
+ """Transform the hint to a URI fragment identifier"""
+ if self.docs_hint:
+ self.docs_hint = '#' + self.docs_hint
+
+@dataclass
+class SymbolRule(Rule):
+ """Rule entry for one .config symbol"""
+
+ symbol: str
+
+ def _normalize_docs_hint(self) -> None:
+ """Transform the hint to a docs.kernel.org URI fragment identifier"""
+ if self.docs_hint == 'config':
+ self.docs_hint = self.symbol.lower().replace('_', '-')
+
+ super()._normalize_docs_hint()
+
+@dataclass
+class PatternRule(Rule):
+ """Rule entry for a regex pattern of .config symbols"""
+
+ regex: re.Pattern[str]
+ pattern_prio: int = 0
+
+@dataclass
+class Policy:
+ """The .config checker policy rules repository / data model"""
+
+ rules: list[Rule] = field(default_factory=list)
+ docs_url: Optional[str] = None
+
+ def add_rule(self, rule: Rule) -> None:
+ """Add given rule to the existing rules repository"""
+ if isinstance(rule, SymbolRule):
+ symbol = rule.symbol
+ if self.get_symbol_rule(symbol):
+ error(f'Duplicate rule name: {symbol}', os.EX_DATAERR)
+
+ if isinstance(rule, PatternRule):
+ pattern = rule.regex.pattern
+ if self.get_pattern_rule(pattern):
+ error(f'Duplicate rule pattern: {pattern}', os.EX_DATAERR)
+
+ self.rules.append(rule)
+
+ def get_docs_url_for(self, rule: Rule) -> Optional[str]:
+ """Return full documentation URL for a rule, if available"""
+ if not self.docs_url or not rule.docs_hint:
+ return None
+
+ return f'{self.docs_url}{rule.docs_hint}'
+
+ def get_symbol_rule(self, kconfig_symbol: str) -> Optional[SymbolRule]:
+ """Return symbol rule matching passed .config symbol, if any"""
+ for rule in self.rules:
+ if isinstance(rule, SymbolRule):
+ if rule.symbol == kconfig_symbol:
+ return rule
+ return None
+
+ def get_pattern_rule(self, pattern: str) -> Optional[PatternRule]:
+ """Return pattern rule matching passed name pattern, if any"""
+ for rule in self.rules:
+ if isinstance(rule, PatternRule):
+ if rule.regex.pattern == pattern:
+ return rule
+ return None
+
+ def get_symbol_rule_matching(self, pattern: re.Pattern[str]) -> list[SymbolRule]:
+ """Get all symbol rules matching passed regex"""
+ rules = []
+ for rule in self.rules:
+ if isinstance(rule, SymbolRule):
+ if pattern.search(rule.symbol):
+ rules.append(rule)
+ return rules
+
+ def get_pattern_rules_for(self, kconfig_symbol: str) -> list[PatternRule]:
+ """Get all pattern rules with a regex matching passed .config symbol"""
+ rules = []
+ for rule in self.rules:
+ if isinstance(rule, PatternRule):
+ if rule.regex.search(kconfig_symbol):
+ rules.append(rule)
+ return rules
+
+class PolicyFile(VersionedYamlFile):
+ """Policy file parser (to a Policy model)"""
+
+ SCHEMAS: ClassVar[Mapping[str, str]] = {
+ VersionedYamlFile.AUDIT_API_V1: 'policy-v1.yml',
+ }
+
+ def parse(self) -> Policy:
+ """Parse the YAML policy file into a python Policy object"""
+ policy = Policy()
+
+ for rule_mapping in self.yaml.get('rules', []):
+ rule = self._parse_rule(rule_mapping)
+ policy.add_rule(rule)
+
+ policy.docs_url = self.yaml.get('docs_url')
+ return policy
+
+ def _parse_rule(self, rule: YamlDict) -> Rule:
+ """Parse one policy YAML rule into a polymorphic Rule object"""
+ expected = ExpectedValue[rule['expected']]
+ severity = Severity[rule['severity']]
+ rationale = rule.get('rationale')
+ docs_hint = rule.get('docs_hint')
+
+ if 'name' in rule:
+ return SymbolRule(
+ expected,
+ severity,
+ rationale,
+ docs_hint,
+ symbol=rule['name'],
+ )
+
+ if 'name_pattern' in rule:
+ return PatternRule(
+ expected,
+ severity,
+ rationale,
+ docs_hint,
+ regex=re.compile(rule['name_pattern']),
+ pattern_prio=rule.get('pattern_prio', 0),
+ )
+
+ # Schema should guard against this
+ Helpers.unreachable('YAML rule entry without `name` or `name_pattern`')
+
+#
+# Error reporting model:
+#
+
+@dataclass
+class Issue:
+ message: str
+ docs_url: Optional[str]
+ severity: Severity
+ rationale: Optional[str]
+
+@dataclass
+class SymbolIssue(Issue):
+ """Checker issue concerning a single .config symbol"""
+ symbol: str
+
+@dataclass
+class PatternIssue(Issue):
+ """Checker issue concerning a regex pattern of .config symbols"""
+ symbols: list[str]
+
+@dataclass
+class RegexIssue(Issue):
+ """Checker issue concerning a regex pattern that has no matches"""
+ regex: re.Pattern[str]
+
+class Issues:
+ """Repository of all issues found by the checker"""
+
+ def __init__(self, all_issues: list[Issue]):
+ # Index all issues by severity
+ self.issues: dict[Severity, list[Issue]] = {
+ severity: [] for severity in Severity
+ }
+ for issue in all_issues:
+ self.issues[issue.severity].append(issue)
+
+ def by_severity(self, severity: Severity) -> list[Issue]:
+ return self.issues[severity]
+
+@dataclass
+class Report:
+ """kconfig checker sanity report. Main script output"""
+
+ issues: Issues
+
+ def _print_header(self, header: str) -> None:
+ print(header)
+ print('=' * len(header))
+ print()
+
+ def _print_symbol(self, issue: SymbolIssue) -> None:
+ print(f'* {issue.symbol} {issue.message}')
+ print()
+
+ def _print_pattern(self, issue: PatternIssue) -> None:
+ print(f'* Below options {issue.message}:\n')
+ for symbol in issue.symbols:
+ print(f' {symbol}')
+ print()
+
+ def _print_regex(self, issue: RegexIssue) -> None:
+ print(f'* Regular expression "{issue.regex.pattern}" {issue.message}')
+ print()
+
+ def _print_issue(self, issue: Issue) -> None:
+ if isinstance(issue, SymbolIssue):
+ self._print_symbol(issue)
+ elif isinstance(issue, PatternIssue):
+ self._print_pattern(issue)
+ elif isinstance(issue, RegexIssue):
+ self._print_regex(issue)
+ else:
+ raise TypeError(f'Unsupported issue type: {type(issue).__name__}')
+
+ def _print_rationale(self, issue: Issue) -> None:
+ if not issue.docs_url and not issue.rationale:
+ return
+
+ print(' Rationale:')
+
+ if issue.docs_url:
+ print(' ', issue.docs_url)
+ if issue.rationale:
+ print()
+
+ if issue.rationale:
+ print(textwrap.fill(
+ issue.rationale,
+ width=75,
+ initial_indent=' ',
+ subsequent_indent=' ',
+ ))
+
+ print()
+
+ def print(self) -> None:
+ """Print the checker's .config report, in order of severity"""
+ print()
+ for severity in Severity:
+ issues = self.issues.by_severity(severity)
+ if not issues:
+ continue
+
+ self._print_header('Configuration Issues with severity = ' +
+ severity.name.upper())
+
+ for issue in issues:
+ self._print_issue(issue)
+ self._print_rationale(issue)
+
+#
+# Configuration checking machinery:
+#
+
+PatternRuleMap = Mapping[Symbol, PatternRule]
+
+@dataclass
+class Checker:
+ """Check a parsed kernel .config against a parsed policy"""
+
+ kconfig: KernelConfig
+ policy: Policy
+
+ def __post_init__(self) -> None:
+ self.pattern_rules_map = self._map_pattern_rules()
+
+ def make_report(self) -> Optional[Report]:
+ """Return a report if the policy produced any issues"""
+ if not (issues := self.find_issues()):
+ return None
+
+ return Report(Issues(issues))
+
+ def find_issues(self) -> list[Issue]:
+ """Check .config against all policy rules and return any issues"""
+ issues: list[Issue] = []
+
+ for rule in self.policy.rules:
+ issues.extend(self._find_rule_issues(rule))
+
+ return issues
+
+ def _map_pattern_rules(self) -> PatternRuleMap:
+ """Map each .config symbol to highest-priority matching pattern rule, if any"""
+ pattern_map: dict[Symbol, PatternRule] = {}
+
+ for symbol in self.kconfig.symbols.values():
+
+ # No matching pattern rules for symbol
+ rules = self.policy.get_pattern_rules_for(symbol.name)
+ if not rules:
+ continue
+
+ highest_prio = max(rule.pattern_prio for rule in rules)
+ highest_prio_rules = [
+ rule for rule in rules if rule.pattern_prio == highest_prio
+ ]
+
+ if len(highest_prio_rules) > 1:
+ patterns = '\n\t'.join(
+ rule.regex.pattern for rule in highest_prio_rules
+ )
+ error(
+ f'{symbol.name} is covered by multiple pattern rules with '
+ f'priority {highest_prio}:\n\t{patterns}',
+ os.EX_DATAERR,
+ )
+
+ pattern_map[symbol] = highest_prio_rules[0]
+
+ return pattern_map
+
+ def _find_rule_issues(self, rule: Rule) -> list[Issue]:
+ """Check .config against single passed rule and return any issues"""
+ if rule.expected is ExpectedValue.neutral:
+ return []
+
+ if isinstance(rule, SymbolRule):
+ return self._find_symbol_rule_issues(rule)
+
+ if isinstance(rule, PatternRule):
+ return self._find_pattern_rule_issues(rule)
+
+ raise TypeError(f'Unsupported rule type: {type(rule).__name__}')
+
+ def _find_symbol_rule_issues(self, rule: SymbolRule) -> list[Issue]:
+ """Check .config against a symbol rule and return any issues"""
+
+ symbol = self.kconfig.get_symbol(rule.symbol)
+
+ if symbol is None:
+ if rule.expected is ExpectedValue.enabled:
+ return [self._make_symbol_issue(rule, 'is not in .config')]
+
+ return []
+
+ if not isinstance(symbol, BooleanSymbol):
+ msg = 'has the wrong type, expected boolean'
+ return [self._make_symbol_issue(rule, msg)]
+
+ if Checker._expected_enabled(rule) != symbol.value:
+ msg = 'is ' + self._wrong_symbol_state_message(rule)
+ return [self._make_symbol_issue(rule, msg)]
+
+ return []
+
+ def _find_pattern_rule_issues(self, rule: PatternRule) -> list[Issue]:
+ """Check .config against a pattern rule and return any issues"""
+ wrong_type_symbols: list[str] = []
+ wrong_value_symbols: list[str] = []
+
+ matched_symbols = False
+
+ for symbol in self.kconfig.get_matching_symbols(rule.regex):
+ # Record the regex symbol match before applying overrides
+ matched_symbols = True
+
+ # An exact rule for symbol overrides all pattern rules
+ if self.policy.get_symbol_rule(symbol.name):
+ continue
+
+ # Higher-priority patterns overrides us
+ if self.pattern_rules_map.get(symbol) is not rule:
+ continue
+
+ if not isinstance(symbol, BooleanSymbol):
+ wrong_type_symbols.append(symbol.name)
+ continue
+
+ if Checker._expected_enabled(rule) != symbol.value:
+ wrong_value_symbols.append(symbol.name)
+ continue
+
+ issues: list[Issue] = []
+
+ if Checker._expected_enabled(rule) and not matched_symbols:
+ if not self.policy.get_symbol_rule_matching(rule.regex):
+ msg = 'does not match any enabled kconfig symbol'
+ issues.append(self._make_regex_issue(rule, msg))
+
+ if wrong_type_symbols:
+ issues.append(self._make_pattern_issue(
+ rule,
+ 'have the wrong types, expected boolean',
+ wrong_type_symbols,
+ ))
+
+ if wrong_value_symbols:
+ issues.append(self._make_pattern_issue(
+ rule,
+ 'are ' + self._wrong_symbol_state_message(rule),
+ wrong_value_symbols,
+ ))
+
+ return issues
+
+ @staticmethod
+ def _expected_enabled(rule: Rule) -> bool:
+ if rule.expected is ExpectedValue.enabled:
+ return True
+
+ if rule.expected is ExpectedValue.disabled:
+ return False
+
+ raise ValueError('Neutral rule has no boolean representation')
+
+ @staticmethod
+ def _wrong_symbol_state_message(rule: Rule) -> str:
+ if Checker._expected_enabled(rule):
+ return 'disabled'
+
+ return 'enabled'
+
+ def _make_symbol_issue(self, rule: SymbolRule, err_message: str) -> SymbolIssue:
+ return SymbolIssue(
+ err_message,
+ self.policy.get_docs_url_for(rule),
+ rule.severity,
+ rule.rationale,
+ rule.symbol,
+ )
+
+ def _make_pattern_issue(self, rule: PatternRule, err_message: str, symbols: list[str]) -> PatternIssue:
+ return PatternIssue(
+ err_message,
+ self.policy.get_docs_url_for(rule),
+ rule.severity,
+ rule.rationale,
+ symbols,
+ )
+
+ def _make_regex_issue(self, rule: PatternRule, message: str) -> RegexIssue:
+ return RegexIssue(
+ message,
+ self.policy.get_docs_url_for(rule),
+ rule.severity,
+ rule.rationale,
+ rule.regex,
+ )
+
+#
+# Argument parsing and main code:
+#
+
+def parse_args(policies: list[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ prog='audit.py',
+ description='Kernel .config options checker',
+ )
+
+ subparsers = parser.add_subparsers(
+ dest='command',
+ required=True,
+ )
+
+ subparsers.add_parser(
+ 'list-policies',
+ help='return available .config rule checking profiles',
+ )
+
+ subparsers.add_parser(
+ 'list-api-versions',
+ help='return supported policy API versions',
+ )
+
+ check_parser = subparsers.add_parser(
+ 'check',
+ help='check a .config file against a rule profile',
+ )
+
+ check_parser.add_argument(
+ '-c',
+ '--config',
+ metavar='KCONFIG_FILE',
+ type=Path,
+ required=True,
+ help='.config file to be checked',
+ )
+
+ policy_group = check_parser.add_mutually_exclusive_group(required=True)
+
+ policy_group.add_argument(
+ '-p',
+ '--policy',
+ metavar='POLICY',
+ choices=policies,
+ help='registered policy name to check against',
+ )
+
+ policy_group.add_argument(
+ '-P',
+ '--policy-file',
+ metavar='POLICY_FILE',
+ type=Path,
+ help='policy file to check against',
+ )
+
+ return parser.parse_args()
+
+def main() -> None:
+ base_dir = Path(__file__).resolve().parent
+ policy_dir = base_dir / 'policy'
+ schema_dir = base_dir / 'schema'
+
+ policies = sorted(path.stem for path in policy_dir.glob('*.yml'))
+ args = parse_args(policies)
+
+ if args.command == 'list-policies':
+ print(*policies, sep='\n')
+ return
+
+ if args.command == 'list-api-versions':
+ versions = sorted(PolicyFile.SCHEMAS)
+ print(*versions, sep='\n')
+ return
+
+ kconfig_f = args.config.resolve()
+ kconfig = KernelConfigFile(kconfig_f).parse()
+
+ if args.policy_file:
+ policy_f = args.policy_file
+ else:
+ policy_f = policy_dir / f'{args.policy}.yml'
+ policy = PolicyFile(policy_f, schema_dir).parse()
+
+ checker = Checker(kconfig, policy)
+ report = checker.make_report()
+
+ if report:
+ report.print()
+ error(f'{kconfig_f} does not match required policy', os.EX_CONFIG)
+
+ print(f'Success: {kconfig_f} matches required policy')
+
+if __name__ == '__main__':
+ main()
--
2.56.0