File size: 12,907 Bytes
f38b9b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python3
"""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:  # pragma: no cover
    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())