| |
| """Validate IV-CAN-v1 labels and frame CSVs without loading tables into memory.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import ast |
| import csv |
| import json |
| import math |
| import re |
| import sys |
| from pathlib import Path |
| from typing import Any, Iterable |
|
|
| try: |
| import yaml |
| except ImportError as exc: |
| raise SystemExit("PyYAML is required: python -m pip install PyYAML") from exc |
|
|
|
|
| COLUMNS = [ |
| "timestamp", "can_id", "is_extended_id", "dlc", "data", "RX_or_TX", |
| "type", "is_fd", "domain", "is_attack", "traced_from", "uuid", |
| "is_traced_attack", |
| ] |
| BOOL = {"True": True, "False": False} |
| CAN_ID = re.compile(r"^0x(?:[0-9A-F]{4}|[0-9A-F]{8})$") |
| BYTE_STRING = re.compile(r"^(?:[0-9A-F]{2}(?: [0-9A-F]{2})*)?$") |
| CLASSIC_LENGTHS = set(range(9)) |
| FD_LENGTHS = CLASSIC_LENGTHS | {12, 16, 20, 24, 32, 48, 64} |
| ROAD_TYPES = { |
| "UrbanOrdinaryRoad", "RuralRoad", "InternalRoad", "UORWithLKN", |
| "HighwayWithLKN", "Highway", "UrbanExpressway", |
| } |
| ATTACK_TYPES = {"DoS", "fuzzing", "replay", "spoofing", "suspension", "masquerade"} |
| EFFECT_LEVELS = { |
| "no effect", "system warning", "non-motion control compromised", |
| "motion control compromised", |
| } |
|
|
|
|
| class Problems: |
| def __init__(self) -> None: |
| self.items: list[str] = [] |
|
|
| def add(self, path: Path, message: str, row: int | None = None) -> None: |
| where = f"{path}:{row}" if row is not None else str(path) |
| self.items.append(f"{where}: {message}") |
|
|
|
|
| def require_keys(value: Any, keys: set[str], path: Path, problems: Problems, context: str) -> bool: |
| if not isinstance(value, dict): |
| problems.add(path, f"{context} must be a mapping") |
| return False |
| missing = keys - value.keys() |
| extra = value.keys() - keys |
| if missing: |
| problems.add(path, f"{context} missing keys: {sorted(missing)}") |
| if extra: |
| problems.add(path, f"{context} has unknown keys: {sorted(extra)}") |
| return not missing |
|
|
|
|
| def validate_label(path: Path, problems: Problems) -> None: |
| try: |
| value = yaml.safe_load(path.read_text(encoding="utf-8")) |
| except Exception as exc: |
| problems.add(path, f"cannot parse YAML: {exc}") |
| return |
|
|
| top = { |
| "attack_end_timestamp", "attack_start_timestamp", "attacking_duration_sec", |
| "collection_duration_sec", "data_attack_info", "data_collection_info", "group_name", |
| } |
| if not require_keys(value, top, path, problems, "label"): |
| return |
| if value["group_name"] != path.parent.name: |
| problems.add(path, "group_name must equal the containing case directory") |
| for key in ("collection_duration_sec", "attacking_duration_sec"): |
| number = value[key] |
| if not isinstance(number, (int, float)) or isinstance(number, bool) or number < 0: |
| problems.add(path, f"{key} must be a non-negative number") |
| for key in ("attack_start_timestamp", "attack_end_timestamp"): |
| number = value[key] |
| if number is not None and (not isinstance(number, (int, float)) or isinstance(number, bool) or number < 0): |
| problems.add(path, f"{key} must be null or a non-negative number") |
|
|
| collection = value["data_collection_info"] |
| collection_keys = {"avg_speed", "description", "end_place", "intelligent_driving", "road_type", "start_place"} |
| if require_keys(collection, collection_keys, path, problems, "data_collection_info"): |
| if collection["road_type"] not in ROAD_TYPES: |
| problems.add(path, f"unknown road_type: {collection['road_type']!r}") |
| if not isinstance(collection["intelligent_driving"], bool): |
| problems.add(path, "intelligent_driving must be boolean") |
|
|
| attack = value["data_attack_info"] |
| if attack is None: |
| if not str(value["group_name"]).startswith("benign_"): |
| problems.add(path, "only benign cases may have data_attack_info: null") |
| return |
| if not require_keys(attack, {"attack_effect", "attack_type", "attacked_domain"}, path, problems, "data_attack_info"): |
| return |
| domain = attack["attacked_domain"] |
| if not isinstance(domain, int) or isinstance(domain, bool) or not 1 <= domain <= 5: |
| problems.add(path, "attacked_domain must be an integer from 1 through 5") |
| effect = attack["attack_effect"] |
| if require_keys(effect, {"description", "level"}, path, problems, "attack_effect") and effect["level"] not in EFFECT_LEVELS: |
| problems.add(path, f"unknown attack effect level: {effect['level']!r}") |
| attack_type = attack["attack_type"] |
| if not require_keys(attack_type, {"kind", "config"}, path, problems, "attack_type"): |
| return |
| kind, config = attack_type["kind"], attack_type["config"] |
| if kind not in ATTACK_TYPES: |
| problems.add(path, f"unknown attack kind: {kind!r}") |
| return |
| expected_prefix = "dos" if kind == "DoS" else kind |
| if not str(value["group_name"]).startswith(expected_prefix + "_"): |
| problems.add(path, "attack kind does not agree with group_name") |
| validate_attack_config(kind, config, path, problems) |
|
|
|
|
| def validate_attack_config(kind: str, config: Any, path: Path, problems: Problems) -> None: |
| if kind in {"spoofing", "masquerade"}: |
| if config is not None: |
| problems.add(path, f"{kind} config must be null") |
| return |
| if not isinstance(config, dict): |
| problems.add(path, f"{kind} config must be a mapping") |
| return |
| enums: dict[str, dict[str, set[str]]] = { |
| "DoS": {"id_option": {"aliveId", "zeroId"}, "dlc_option": {"dlcChange", "dlcKeep"}, "ext_option": {"extendedId", "standardId"}, "data_option": {"FFData", "randomData"}}, |
| "fuzzing": {"id_option": {"aliveId", "randomId"}, "dlc_option": {"dlcChange", "dlcKeep"}}, |
| "replay": {"timing": {"delay", "immediate"}}, |
| } |
| if kind in enums: |
| if not require_keys(config, set(enums[kind]), path, problems, f"{kind} config"): |
| return |
| for key, allowed in enums[kind].items(): |
| if config[key] not in allowed: |
| problems.add(path, f"invalid {kind} {key}: {config[key]!r}") |
| return |
| if kind == "suspension": |
| if not require_keys(config, {"suspension_CAN_id_list", "suspension_duration_sec"}, path, problems, "suspension config"): |
| return |
| ids = config["suspension_CAN_id_list"] |
| if not isinstance(ids, list) or not ids or any(not isinstance(item, str) or not CAN_ID.fullmatch(item) for item in ids): |
| problems.add(path, "suspension_CAN_id_list must contain canonical CAN IDs") |
| duration = config["suspension_duration_sec"] |
| if not isinstance(duration, (int, float)) or isinstance(duration, bool) or duration <= 0: |
| problems.add(path, "suspension_duration_sec must be positive") |
|
|
|
|
| def parse_bool(raw: str) -> bool: |
| if raw not in BOOL: |
| raise ValueError("expected True or False") |
| return BOOL[raw] |
|
|
|
|
| def grow_bitset(bitset: bytearray, index: int) -> None: |
| if index >= len(bitset): |
| bitset.extend(b"\0" * (index + 1 - len(bitset))) |
|
|
|
|
| def validate_frame(row: dict[str, str], path: Path, line: int, seen: bytearray, graph: dict[int, list[int]], problems: Problems) -> None: |
| try: |
| timestamp = float(row["timestamp"]) |
| if not math.isfinite(timestamp) or timestamp < 0: |
| raise ValueError("timestamp must be finite and non-negative") |
| can_id = row["can_id"] |
| if not CAN_ID.fullmatch(can_id): |
| raise ValueError("can_id is not canonical uppercase hexadecimal") |
| extended = parse_bool(row["is_extended_id"]) |
| if (len(can_id) == 10) != extended: |
| raise ValueError("can_id width disagrees with is_extended_id") |
| dlc = int(row["dlc"]) |
| payload = row["data"] |
| if not BYTE_STRING.fullmatch(payload): |
| raise ValueError("data is not canonical space-separated uppercase hex") |
| if len(payload.split()) != dlc: |
| raise ValueError("dlc does not equal payload byte count") |
| if row["RX_or_TX"] not in {"RX", "TX"}: |
| raise ValueError("RX_or_TX must be RX or TX") |
| frame_type = row["type"] |
| if frame_type not in {"DT", "FB", "BI"}: |
| raise ValueError("type must be DT, FB, or BI") |
| is_fd = parse_bool(row["is_fd"]) |
| if frame_type in {"FB", "BI"} and not is_fd: |
| raise ValueError("FB or BI requires is_fd=True") |
| if dlc not in (FD_LENGTHS if is_fd else CLASSIC_LENGTHS): |
| raise ValueError("dlc is invalid for the frame protocol") |
| domain = int(row["domain"]) |
| if not 1 <= domain <= 5: |
| raise ValueError("domain must be 1 through 5") |
| parse_bool(row["is_attack"]) |
| parse_bool(row["is_traced_attack"]) |
| uuid = int(row["uuid"]) |
| if uuid <= 0: |
| raise ValueError("uuid must be positive") |
| grow_bitset(seen, uuid) |
| if seen[uuid]: |
| raise ValueError("duplicate case-local uuid") |
| seen[uuid] = 1 |
| parents = ast.literal_eval(row["traced_from"]) |
| if not isinstance(parents, list) or any(type(parent) is not int or parent <= 0 for parent in parents): |
| raise ValueError("traced_from must be a list of positive integers") |
| if len(parents) != len(set(parents)): |
| raise ValueError("traced_from contains duplicates") |
| if uuid in parents: |
| raise ValueError("traced_from contains a self-reference") |
| if parents: |
| graph[uuid] = parents |
| except (ValueError, SyntaxError, KeyError) as exc: |
| problems.add(path, str(exc), line) |
|
|
|
|
| def validate_graph(path: Path, graph: dict[int, list[int]], seen: bytearray, problems: Problems) -> None: |
| for child, parents in graph.items(): |
| for parent in parents: |
| if parent >= len(seen) or not seen[parent]: |
| problems.add(path, f"uuid {child} traces from missing case-local uuid {parent}") |
| state: dict[int, int] = {} |
|
|
| def visit(node: int) -> bool: |
| if state.get(node) == 1: |
| return False |
| if state.get(node) == 2: |
| return True |
| state[node] = 1 |
| for parent in graph.get(node, []): |
| if parent in graph and not visit(parent): |
| return False |
| state[node] = 2 |
| return True |
|
|
| for node in graph: |
| if not visit(node): |
| problems.add(path, "traced_from graph contains a cycle") |
| break |
|
|
|
|
| def validate_csv(path: Path, max_rows: int | None, problems: Problems) -> int: |
| seen = bytearray(1) |
| graph: dict[int, list[int]] = {} |
| rows = 0 |
| with path.open("r", encoding="utf-8", newline="") as handle: |
| reader = csv.DictReader(handle) |
| if reader.fieldnames != COLUMNS: |
| problems.add(path, f"unexpected header: {reader.fieldnames!r}", 1) |
| return 0 |
| for line, row in enumerate(reader, 2): |
| if max_rows is not None and rows >= max_rows: |
| break |
| validate_frame(row, path, line, seen, graph, problems) |
| rows += 1 |
| if max_rows is None: |
| validate_graph(path, graph, seen, problems) |
| return rows |
|
|
|
|
| def iter_cases(root: Path) -> Iterable[tuple[Path, Path]]: |
| for label in sorted((root / "data").glob("**/label.yaml")): |
| yield label, label.with_name("data.csv") |
|
|
|
|
| def main(argv: list[str] | None = None) -> int: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) |
| group = parser.add_mutually_exclusive_group() |
| group.add_argument("--max-rows", type=int, default=1000, help="rows checked per case (default: 1000)") |
| group.add_argument("--all", action="store_true", help="scan every row and validate trace references/cycles") |
| args = parser.parse_args(argv) |
| root = args.root.resolve() |
| max_rows = None if args.all else args.max_rows |
| if max_rows is not None and max_rows <= 0: |
| parser.error("--max-rows must be positive") |
|
|
| problems = Problems() |
| cases = rows = 0 |
| for label, data in iter_cases(root): |
| cases += 1 |
| validate_label(label, problems) |
| if not data.is_file(): |
| problems.add(data, "missing data.csv") |
| else: |
| rows += validate_csv(data, max_rows, problems) |
| if not cases: |
| problems.add(root / "data", "no cases found") |
| if problems.items: |
| for item in problems.items[:100]: |
| print(f"ERROR: {item}", file=sys.stderr) |
| if len(problems.items) > 100: |
| print(f"ERROR: {len(problems.items) - 100} additional errors omitted", file=sys.stderr) |
| return 1 |
| mode = "all rows" if max_rows is None else f"up to {max_rows} rows/case" |
| print(f"OK: validated {cases} cases and {rows:,} frame rows ({mode})") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|