IV-CAN commited on
Commit
f38b9b5
·
verified ·
1 Parent(s): ad6d581

Add dataset metadata, schemas, and attack-generation code

Browse files

Adds CC BY 4.0 dataset-card metadata, normative frame/label schemas, a public validator, and a curated safe-default attack-generation snapshot.

LICENSE.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Creative Commons Attribution 4.0 International
2
+
3
+ IV-CAN-v1, including its documentation and the original supplementary code
4
+ published in this repository, is licensed under the Creative Commons
5
+ Attribution 4.0 International License (CC BY 4.0).
6
+
7
+ License summary and legal code:
8
+ <https://creativecommons.org/licenses/by/4.0/>
9
+
10
+ You are free to share and adapt the material for any purpose, provided that
11
+ appropriate credit is given, a link to the license is supplied, and changes
12
+ are indicated. No additional restrictions may be applied.
13
+
14
+ Third-party names, hardware drivers, libraries, and binary runtimes are not
15
+ relicensed by this notice. In particular, PEAK-System PCAN drivers and
16
+ `PCANBasic.dll` are not distributed in this repository.
README.md CHANGED
@@ -1,58 +1,85 @@
1
- # IV-CAN-v1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- **IV-CAN-v1** is an in-vehicle CAN security dataset organized for attack analysis, cross-domain forwarding inspection, entropy analysis, and message-timing studies.
4
 
5
- The dataset is derived from labeled CSV DataGroups and repackaged into a public case-oriented layout. Each trial is assigned a stable open case id, such as `fuzzing_0001`, `replay_0001`, or `dos_0001`.
6
 
7
  ![Dataset Distribution](statistics/dataset_distribution_pies.svg)
8
 
9
  ## Highlights
10
 
11
- - **Dataset name:** IV-CAN-v1
12
  - **Trials:** 134
13
- - **CSV payload size:** 27.45 GB
14
  - **CAN frames:** 225,850,423
15
- - **Protocol frames:** 56,015,108 classical CAN; 169,835,315 CAN FD
16
- - **Trials with non-driver control:** 67 (37 benign; 30 attack)
17
- - **Total capture duration:** 12h14min
18
- - **Non-benign trial duration:** 3h9min
19
- - **Trials with attack cross-domain forwarding:** 23
20
 
21
- ## Dataset Layout
22
 
23
  ```text
24
  IV-CAN-v1/
25
  ├── data/
26
- │ ├── Benign/<case_id>/
27
- │ └── Attack/<attack_type>/<case_id>/
28
- ├── analysis/
29
- ├── Benign/<case_id>/
30
- │ └── Attack/<attack_type>/<case_id>/
31
- ├── statistics/
 
32
  ├── dataset_manifest.csv
33
- ├── original_csv_mapping.csv
34
- ├── fail.csv
35
  └── README.md
36
  ```
37
 
38
- Each `data/.../<case_id>/` folder contains:
39
 
40
- - `data.csv`: frame-level CAN messages and labels.
41
- - `label.yaml`: trial-level metadata, collection duration, and attack information.
42
 
43
- Each `analysis/.../<case_id>/` folder contains:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- - `entropy_domain_bus/`: domain-specific bus-level payload entropy plots (`domain{n}.svg`).
46
- - `message_timing_domain_bus/`: domain-specific bus-level message-timing plots (`domain{n}.svg`).
47
- - `cross_domain_relationship_map.yaml`: cross-domain relationship data.
48
- - `cross_domain_relationship.html`: cross-domain visualization.
49
- - `tracing.html`: tracing visualization entry point.
50
- - Optional per-CAN-ID folders for attacked and traced attack entropy/message-timing plots.
51
 
52
- ## Trial Categories
53
 
54
  | Category | Trials |
55
- | --- | --- |
56
  | Benign | 60 |
57
  | DoS | 22 |
58
  | fuzzing | 28 |
@@ -61,73 +88,41 @@ Each `analysis/.../<case_id>/` folder contains:
61
  | suspension | 2 |
62
  | masquerade | 2 |
63
 
64
- ![Trial Count By Attack Type](statistics/group_count_pie.svg)
65
 
66
- ## Collection And Attack Statistics
 
 
 
 
 
 
67
 
68
  | Metric | Value |
69
- | --- | --- |
70
  | Total trials | 134 |
71
  | Total CAN frames | 225,850,423 |
72
- | Classical CAN frames | 56,015,108 (24.80%) |
73
- | CAN FD frames | 169,835,315 (75.20%) |
74
  | Trials with non-driver control | 67 (37 benign; 30 attack) |
75
- | Dataset size | 27.45 GB |
76
- | Total capture duration | 12h14min |
77
  | Non-benign trial duration | 3h9min |
78
  | Attack duration | 23min |
79
- | is_attack frames | 231,477 |
80
- | is_traced_attack frames | 42,478 |
81
  | Trials with attack cross-domain forwarding | 23 |
82
 
83
- ### Protocol Distribution By Domain
84
-
85
- | Domain | Configured name | Configured protocol | Classical CAN | CAN FD | Total |
86
- | --- | --- | --- | --- | --- | --- |
87
- | Domain 1 | 驱动CAN | can fd | 0 | 57,786,350 | 57,786,350 |
88
- | Domain 2 | 底盘CAN | can fd | 0 | 64,904,112 | 64,904,112 |
89
- | Domain 3 | 灯控CAN | classical can | 48,815,343 | 0 | 48,815,343 |
90
- | Domain 4 | 辅助行驶CAN | can fd | 0 | 47,144,853 | 47,144,853 |
91
- | Domain 5 | 方向盘CAN | classical can | 7,199,765 | 0 | 7,199,765 |
92
-
93
- ### Figures
94
-
95
- ![Capture Duration By Road Type](statistics/capture_duration_pie.svg)
96
-
97
- ![Attack Duration By Attack Type](statistics/attack_duration_pie.svg)
98
-
99
- ![Attack Frame Distribution](statistics/attack_frame_pie.svg)
100
-
101
- ## Attack Effect Summary
102
-
103
- The attack effect table is available at [`statistics/attack_effect_counter.md`](statistics/attack_effect_counter.md).
104
-
105
- ## Example Cases
106
-
107
- | Case ID | Attack Type | Data | Analysis |
108
- | --- | --- | --- | --- |
109
- | benign_0001 | Benign | data/Benign/benign_0001 | analysis/Benign/benign_0001 |
110
- | dos_0001 | DoS | data/Attack/DoS/dos_0001 | analysis/Attack/DoS/dos_0001 |
111
- | fuzzing_0001 | fuzzing | data/Attack/fuzzing/fuzzing_0001 | analysis/Attack/fuzzing/fuzzing_0001 |
112
- | replay_0001 | replay | data/Attack/replay/replay_0001 | analysis/Attack/replay/replay_0001 |
113
- | spoofing_0001 | spoofing | data/Attack/spoofing/spoofing_0001 | analysis/Attack/spoofing/spoofing_0001 |
114
- | suspension_0001 | suspension | data/Attack/suspension/suspension_0001 | analysis/Attack/suspension/suspension_0001 |
115
- | masquerade_0001 | masquerade | data/Attack/masquerade/masquerade_0001 | analysis/Attack/masquerade/masquerade_0001 |
116
-
117
- ## File Index
118
 
119
- - [`dataset_manifest.csv`](dataset_manifest.csv): all public cases and their data/analysis paths.
120
- - [`original_csv_mapping.csv`](original_csv_mapping.csv): mapping from original CSV DataGroups to open case ids.
121
- - [`fail.csv`](fail.csv): skipped or failed inputs, if any.
122
- - [`statistics/count_csv_result.yaml`](statistics/count_csv_result.yaml): machine-readable dataset statistics.
123
 
124
- ## Naming Convention
125
 
126
- Public attack-type names are normalized as `DoS`, `fuzzing`, `replay`, `spoofing`, `suspension`, and `masquerade`.
127
- Case ids use lowercase prefixes, for example `dos_0001`, `fuzzing_0001`, and `replay_0001`.
128
 
129
- ## Notes
130
 
131
- - `is_attack` marks injected attack frames.
132
- - `is_traced_attack` marks forwarded attack-related frames only when `is_traced_attack=true` and `is_attack=false`.
133
- - Statistics are cherry-picked from the analyzer output using an explicit public-file allowlist.
 
1
+ ---
2
+ pretty_name: IV-CAN-v1
3
+ license: cc-by-4.0
4
+ task_categories:
5
+ - tabular-classification
6
+ tags:
7
+ - automotive
8
+ - can-bus
9
+ - cybersecurity
10
+ - intrusion-detection
11
+ - time-series
12
+ size_categories:
13
+ - 100M<n<1B
14
+ viewer: false
15
+ ---
16
 
17
+ # IV-CAN-v1
18
 
19
+ **IV-CAN-v1** is an in-vehicle CAN security dataset produced entirely by the IV-CAN team. It contains 134 case-oriented captures for intrusion detection, attack analysis, cross-domain forwarding inspection, entropy analysis, and message-timing studies.
20
 
21
  ![Dataset Distribution](statistics/dataset_distribution_pies.svg)
22
 
23
  ## Highlights
24
 
25
+ - **License:** [Creative Commons Attribution 4.0 International](LICENSE.md)
26
  - **Trials:** 134
 
27
  - **CAN frames:** 225,850,423
28
+ - **CSV payload size:** 27.45 GB
29
+ - **Protocols:** 56,015,108 classical CAN frames and 169,835,315 CAN FD frames
30
+ - **Capture duration:** 12h14min
31
+ - **Attack families:** DoS, fuzzing, replay, spoofing, suspension, and masquerade
 
32
 
33
+ ## Repository layout
34
 
35
  ```text
36
  IV-CAN-v1/
37
  ├── data/
38
+ │ ├── Benign/<case_id>/{data.csv,label.yaml}
39
+ │ └── Attack/<attack_type>/<case_id>/{data.csv,label.yaml}
40
+ ├── analysis/ # case-level plots and tracing artifacts
41
+ ├── code/attack_generation/ # self-contained reproducibility snapshot
42
+ ── schema/ # machine-readable schemas
43
+ ├── statistics/ # aggregate statistics and figures
44
+ ├── tools/validate_dataset.py # lightweight public validator
45
  ├── dataset_manifest.csv
46
+ ├── LICENSE.md
47
+ ├── SCHEMA.md
48
  └── README.md
49
  ```
50
 
51
+ Each case has a stable public id such as `fuzzing_0001`. The manifest provides all public data and analysis paths. Large CSV files are intentionally not rendered by the Hub viewer; stream them or download selected cases instead.
52
 
53
+ ## Data schema
 
54
 
55
+ Every `data.csv` uses this ordered header:
56
+
57
+ ```text
58
+ timestamp,can_id,is_extended_id,dlc,data,RX_or_TX,type,is_fd,domain,is_attack,traced_from,uuid,is_traced_attack
59
+ ```
60
+
61
+ The normative definitions, units, enums, identifier scope, and tracing constraints are in [SCHEMA.md](SCHEMA.md). Machine-readable definitions are provided in [schema/frame.schema.yaml](schema/frame.schema.yaml) and [schema/label.schema.json](schema/label.schema.json).
62
+
63
+ Important interpretation rules:
64
+
65
+ - `timestamp` is Unix epoch time in seconds, expressed on the UTC time scale. The original recorder wall-clock was interpreted in the project acquisition timezone (`Asia/Shanghai`) during conversion.
66
+ - `RX` and `TX` are relative to the recording channel: received from or transmitted by that channel.
67
+ - PEAK frame types are `DT` (data frame without the combined flags represented below), `FB` (CAN FD with BRS), and `BI` (CAN FD with BRS and ESI). Use `is_fd`, not `DT` alone, to distinguish classical CAN from CAN FD.
68
+ - `uuid` is unique only within one case. `traced_from` contains zero or more parent UUIDs from that same case; UUIDs must never be joined across cases.
69
+ - `is_attack=true` identifies injected attack frames. A forwarded-only attack-related frame is selected by `is_traced_attack=true AND is_attack=false`; the flags are not declared mutually exclusive.
70
+
71
+ Run a bounded structural check from the repository root:
72
+
73
+ ```bash
74
+ python tools/validate_dataset.py --max-rows 1000
75
+ ```
76
 
77
+ Use `--all` to scan every row (this is expensive for the full dataset).
 
 
 
 
 
78
 
79
+ ## Labels and trial categories
80
 
81
  | Category | Trials |
82
+ | --- | ---: |
83
  | Benign | 60 |
84
  | DoS | 22 |
85
  | fuzzing | 28 |
 
88
  | suspension | 2 |
89
  | masquerade | 2 |
90
 
91
+ Public attack-type names are case-sensitive and normalized exactly as shown. Case ids use lowercase prefixes, for example `dos_0001` and `replay_0001`.
92
 
93
+ ## Attack-generation code
94
+
95
+ [code/attack_generation](code/attack_generation/) is a curated, self-contained snapshot of the core attack construction logic used for the dataset. It excludes private builder infrastructure and third-party hardware binaries. DoS, fuzzing, replay, and spoofing include frame-generation/execution paths; suspension and masquerade are published as validated experiment plans because their execution requires a two-interface MitM bridge.
96
+
97
+ The command-line tool defaults to a no-transmit preview. Hardware execution requires two explicit safety flags and an authorized, isolated CAN test bench. See the [code README](code/attack_generation/README.md) for installation, limitations, and tests.
98
+
99
+ ## Collection and attack statistics
100
 
101
  | Metric | Value |
102
+ | --- | ---: |
103
  | Total trials | 134 |
104
  | Total CAN frames | 225,850,423 |
 
 
105
  | Trials with non-driver control | 67 (37 benign; 30 attack) |
 
 
106
  | Non-benign trial duration | 3h9min |
107
  | Attack duration | 23min |
108
+ | `is_attack` frames | 231,477 |
109
+ | `is_traced_attack` frames | 42,478 |
110
  | Trials with attack cross-domain forwarding | 23 |
111
 
112
+ | Domain | Configured name | Protocol | Frames |
113
+ | --- | --- | --- | ---: |
114
+ | 1 | 驱动CAN | CAN FD | 57,786,350 |
115
+ | 2 | 底盘CAN | CAN FD | 64,904,112 |
116
+ | 3 | 灯控CAN | Classical CAN | 48,815,343 |
117
+ | 4 | 辅助行驶CAN | CAN FD | 47,144,853 |
118
+ | 5 | 方向盘CAN | Classical CAN | 7,199,765 |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
+ The attack-effect summary is available in [statistics/attack_effect_counter.md](statistics/attack_effect_counter.md), with additional machine-readable statistics in [statistics/count_csv_result.yaml](statistics/count_csv_result.yaml).
 
 
 
121
 
122
+ ## Responsible use
123
 
124
+ This dataset and supplementary code are intended for authorized security research, reproducibility, defensive evaluation, and education. Do not use attack-generation functionality on public roads, operational vehicles, or networks you do not own or have explicit permission to test.
 
125
 
126
+ ## License and attribution
127
 
128
+ IV-CAN-v1 data, original documentation, schemas, figures, and the original supplementary attack-generation code are released under [CC BY 4.0](LICENSE.md). Attribution is required. Third-party drivers and runtimes are not redistributed and remain subject to their vendors' licenses.
 
 
SCHEMA.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IV-CAN-v1 data contract
2
+
3
+ This document is the normative public schema for IV-CAN-v1. `schema/frame.schema.yaml` and `schema/label.schema.json` provide machine-readable companions.
4
+
5
+ ## Frame table (`data.csv`)
6
+
7
+ | Field | Type | Definition and constraint |
8
+ | --- | --- | --- |
9
+ | `timestamp` | finite number | Unix epoch seconds on the UTC time scale. Sub-second precision is retained. Source recorder wall-clock values were interpreted as `Asia/Shanghai` during conversion. |
10
+ | `can_id` | string | Uppercase hexadecimal with `0x` prefix: four digits for standard frames or eight for extended frames. Width must agree with `is_extended_id`. |
11
+ | `is_extended_id` | boolean | `true` for a 29-bit CAN identifier; `false` for an 11-bit identifier. CSV spelling is `True`/`False`. |
12
+ | `dlc` | integer | Actual payload byte count, not the encoded CAN DLC nibble. It must equal the number of space-separated bytes in `data`. Classical CAN permits 0–8; CAN FD permits 0–8, 12, 16, 20, 24, 32, 48, or 64. |
13
+ | `data` | string | Zero or more uppercase hexadecimal bytes separated by one ASCII space, for example `00 F0 7F`. Empty iff `dlc=0`. |
14
+ | `RX_or_TX` | enum | `RX`: received by the recording channel. `TX`: transmitted by the recording channel. Direction is channel-relative, not a vehicle-wide source/destination role. |
15
+ | `type` | enum | PEAK TRC record type: `DT` = data frame without the combined flags represented below; `FB` = CAN FD data frame with bit-rate switching (BRS); `BI` = CAN FD frame with BRS and error-state indicator (ESI). A `DT` record can be classical CAN or CAN FD, so do not infer the protocol from this field alone. |
16
+ | `is_fd` | boolean | Normative protocol discriminator: true for CAN FD and false for classical CAN. `FB` and `BI` require true; `DT` permits either value. |
17
+ | `domain` | integer | Recording domain number, one of 1–5. Domain names and configured protocols are listed in the dataset card. |
18
+ | `is_attack` | boolean | True when the row is an injected attack frame. |
19
+ | `traced_from` | list of integers | Python-list serialization of zero or more direct parent UUIDs, e.g. `[]` or `[12, 19]`. Every parent must exist in the same case; cross-case references and self-references are invalid. Multiple parents are allowed. |
20
+ | `uuid` | positive integer | Row identifier unique within one case (`data.csv`). UUID scope resets between cases and is not globally unique. |
21
+ | `is_traced_attack` | boolean | True when tracing associates the row with attack propagation. Because an injected frame can also carry this flag, forwarded-only rows are `is_traced_attack=true AND is_attack=false`. |
22
+
23
+ ### Relationship constraints
24
+
25
+ - The graph induced by `uuid -> traced_from` is case-local and must be acyclic.
26
+ - Every reference must resolve to a row in the same `data.csv`.
27
+ - A row must not reference itself; duplicates in one `traced_from` list are invalid.
28
+ - Consumers must qualify UUIDs with `group_name` or case path before combining cases.
29
+ - Trace edges are intended to represent causal forwarding. Consumers should retain timestamps and domains rather than assuming UUID order alone encodes causality.
30
+
31
+ ## Trial label (`label.yaml`)
32
+
33
+ `group_name` equals the containing case directory. Benign trials use `data_attack_info: null`; attack trials provide an attack family, attacked domain, observed effect, and family-specific configuration when applicable.
34
+
35
+ Enums:
36
+
37
+ - `data_collection_info.road_type`: `UrbanOrdinaryRoad`, `RuralRoad`, `InternalRoad`, `UORWithLKN`, `HighwayWithLKN`, `Highway`, `UrbanExpressway`.
38
+ - `data_attack_info.attack_type.kind`: `DoS`, `fuzzing`, `replay`, `spoofing`, `suspension`, `masquerade`.
39
+ - `attack_effect.level`: `no effect`, `system warning`, `non-motion control compromised`, `motion control compromised`.
40
+ - DoS config: `id_option` is `aliveId|zeroId`; `dlc_option` is `dlcChange|dlcKeep`; `ext_option` is `extendedId|standardId`; `data_option` is `FFData|randomData`.
41
+ - fuzzing config: `id_option` is `aliveId|randomId`; `dlc_option` is `dlcChange|dlcKeep`.
42
+ - replay config: `timing` is `delay|immediate`.
43
+ - suspension config: positive `suspension_duration_sec` and one or more canonical `suspension_CAN_id_list` values.
44
+
45
+ Attack start/end timestamps can be null when the original metadata did not record explicit bounds; `attacking_duration_sec` remains the duration field. The complete conditional structure is in `schema/label.schema.json`.
46
+
47
+ ## Versioning
48
+
49
+ These files describe IV-CAN-v1. Schema-compatible clarifications may be added without renaming the dataset; any incompatible field or semantic change requires a new dataset version.
code/attack_generation/README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IV-CAN-v1 attack-generation snapshot
2
+
3
+ This directory is the self-contained reproducibility snapshot of the attack
4
+ construction code used by IV-CAN-v1. It preserves the dataset taxonomy and
5
+ frame-generation logic while excluding private builder infrastructure and the
6
+ third-party `PCANBasic.dll` binary.
7
+
8
+ ## Implemented scope
9
+
10
+ | Attack family | Dry-run plan | Hardware execution |
11
+ | --- | --- | --- |
12
+ | DoS | Yes | Side-channel injection |
13
+ | fuzzing | Yes | Side-channel injection |
14
+ | replay | Yes | Side-channel injection |
15
+ | spoofing | Yes | Side-channel injection |
16
+ | suspension | Yes | Not implemented; requires a two-interface MitM bridge |
17
+ | masquerade | Yes | Not implemented; requires a two-interface MitM bridge |
18
+
19
+ The values accepted by each family match `label.yaml` and are documented in
20
+ [`../../SCHEMA.md`](../../SCHEMA.md).
21
+
22
+ ## Install
23
+
24
+ Dry-run mode uses only the Python standard library:
25
+
26
+ ```bash
27
+ python -m pip install -e .
28
+ ```
29
+
30
+ Hardware use requires the optional PCAN adapter dependency plus the official
31
+ PEAK-System driver/runtime installed under its own license:
32
+
33
+ ```bash
34
+ python -m pip install -e '.[pcan]'
35
+ ```
36
+
37
+ No PEAK-System DLL is redistributed in this repository.
38
+
39
+ ## Safe default: preview only
40
+
41
+ The CLI does not transmit unless explicitly requested:
42
+
43
+ ```bash
44
+ ivcan-attack --type DoS \
45
+ --id-option zeroId \
46
+ --dlc-option dlcChange \
47
+ --frame-format standardId \
48
+ --data-option FFData \
49
+ --duration 10
50
+ ```
51
+
52
+ Replay can consume an IV-CAN-v1 CSV or the synthetic example:
53
+
54
+ ```bash
55
+ ivcan-attack --type replay \
56
+ --timing immediate \
57
+ --replay-file examples/synthetic_replay.csv
58
+ ```
59
+
60
+ Hardware transmission requires both `--execute` and
61
+ `--acknowledge-bench-only`. It must only be used on an authorized, isolated
62
+ test bench. Never connect this tool to a vehicle operating on a public road.
63
+
64
+ ## Reproducibility notes
65
+
66
+ - `timestamp` differences are used to reproduce replay timing.
67
+ - `is_extended_id` and `is_fd` are consumed when present in replay CSV files.
68
+ - The `seed` option makes generated DoS/fuzzing previews deterministic.
69
+ - Suspension and masquerade are published as validated experiment plans, not
70
+ as claims of an implemented MitM bridge.
71
+
72
+ ## Tests
73
+
74
+ ```bash
75
+ python -m unittest discover -s tests -v
76
+ ```
77
+
78
+ This snapshot is distributed under CC BY 4.0 with the rest of IV-CAN-v1.
79
+ Third-party hardware drivers and runtimes remain under their vendors' terms.
80
+
original_csv_mapping.csv → code/attack_generation/examples/synthetic_replay.csv RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:375a7a305c1ba344a63a3887f903b50b71e21b10edef38fdf6862fb149221025
3
- size 11060
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5f553c4841fbfe2f35f3d2ba4decb08886b13e8d5b6c370b2582b297172284c
3
+ size 164
code/attack_generation/pyproject.toml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ivcan-attack-generation"
7
+ version = "1.0.1"
8
+ description = "Reproducibility snapshot of the IV-CAN-v1 attack generator"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "CC-BY-4.0"}
12
+ dependencies = []
13
+
14
+ [project.optional-dependencies]
15
+ pcan = ["python-can>=4.4,<5"]
16
+
17
+ [project.scripts]
18
+ ivcan-attack = "ivcan_attacker.cli:main"
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
22
+
code/attack_generation/src/ivcan_attacker/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Reproducibility snapshot of the IV-CAN-v1 attack generator."""
2
+
3
+ from .attack_runtime import AttackRequest, AttackRunner
4
+ from .attack_types import AttackBaseType, AttackType
5
+
6
+ __all__ = ["AttackBaseType", "AttackRequest", "AttackRunner", "AttackType"]
7
+
code/attack_generation/src/ivcan_attacker/__main__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
code/attack_generation/src/ivcan_attacker/attack_runtime.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Readable attack strategies built on the vendor-neutral ``can_base`` API.
2
+
3
+ The module separates three concerns:
4
+
5
+ 1. :class:`AttackType` describes the paper-level attack configuration.
6
+ 2. :class:`AttackRequest` contains runtime values supplied by the CLI.
7
+ 3. Strategy classes turn a request into CAN frames or a MitM execution plan.
8
+
9
+ Side-channel injection attacks can already use the common execution loop.
10
+ Suspension and masquerade deliberately expose explicit extension points because
11
+ they need a two-interface MitM bridge, which ``can_base`` does not yet provide.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import random
18
+ import time
19
+ from abc import ABC, abstractmethod
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Iterator
23
+
24
+ from .can_base import CANFrame, CANInterfaceBase
25
+ from .attack_types import (
26
+ AttackBaseType,
27
+ AttackType,
28
+ DoSConfig,
29
+ DoSOptionDLC,
30
+ DoSOptionData,
31
+ DoSOptionExt,
32
+ DoSOptionId,
33
+ FuzzConfig,
34
+ FuzzOptionDLC,
35
+ FuzzOptionId,
36
+ ReplayConfig,
37
+ ReplayOption,
38
+ SuspensionConfig,
39
+ )
40
+
41
+
42
+ _CLASSIC_DLC_VALUES = tuple(range(0, 9))
43
+ _CAN_FD_DLC_VALUES = (*_CLASSIC_DLC_VALUES, 12, 16, 20, 24, 32, 48, 64)
44
+
45
+
46
+ def parse_can_id(value: str) -> int:
47
+ """Parse a decimal or ``0x``-prefixed CAN identifier."""
48
+
49
+ try:
50
+ parsed = int(value, 0)
51
+ except ValueError as exc:
52
+ raise ValueError(f"invalid CAN ID: {value!r}") from exc
53
+ if parsed < 0:
54
+ raise ValueError("CAN ID cannot be negative")
55
+ return parsed
56
+
57
+
58
+ def parse_payload(value: str) -> bytes:
59
+ """Parse payload text such as ``11 22 FF`` or ``1122FF``."""
60
+
61
+ compact = value.replace("0x", "").replace(" ", "").replace(":", "")
62
+ if not compact:
63
+ return b""
64
+ if len(compact) % 2:
65
+ raise ValueError("payload must contain complete hexadecimal bytes")
66
+ try:
67
+ return bytes.fromhex(compact)
68
+ except ValueError as exc:
69
+ raise ValueError(f"invalid hexadecimal payload: {value!r}") from exc
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class AttackRequest:
74
+ """One fully parsed CLI request.
75
+
76
+ ``duration`` controls generated injection attacks. Replay sends one input
77
+ sequence, while suspension uses the duration stored in its paper-level
78
+ :class:`SuspensionConfig`.
79
+ """
80
+
81
+ attack_type: AttackType
82
+ duration: float = 10.0
83
+ interval: float = 0.01
84
+ can_id: int | None = None
85
+ dlc: int | None = None
86
+ payload: bytes | None = None
87
+ is_extended_id: bool = False
88
+ is_fd: bool = False
89
+ replay_file: Path | None = None
90
+ replay_delay: float = 0.0
91
+ seed: int | None = None
92
+
93
+ def __post_init__(self) -> None:
94
+ if self.duration <= 0:
95
+ raise ValueError("duration must be positive")
96
+ if self.interval < 0:
97
+ raise ValueError("interval cannot be negative")
98
+ if self.replay_delay < 0:
99
+ raise ValueError("replay delay cannot be negative")
100
+ if self.dlc is not None:
101
+ allowed = _CAN_FD_DLC_VALUES if self.is_fd else _CLASSIC_DLC_VALUES
102
+ if self.dlc not in allowed:
103
+ protocol = "CAN FD" if self.is_fd else "classical CAN"
104
+ raise ValueError(f"DLC {self.dlc} is invalid for {protocol}")
105
+ if self.payload is not None:
106
+ maximum = 64 if self.is_fd else 8
107
+ if len(self.payload) > maximum:
108
+ raise ValueError(f"payload exceeds the {maximum}-byte protocol limit")
109
+
110
+ def to_dict(self) -> dict:
111
+ return {
112
+ "attack_type": self.attack_type.to_dict(),
113
+ "runtime": {
114
+ "duration": self.duration,
115
+ "interval": self.interval,
116
+ "can_id": None if self.can_id is None else f"0x{self.can_id:X}",
117
+ "dlc": self.dlc,
118
+ "payload": None if self.payload is None else self.payload.hex(" ").upper(),
119
+ "is_extended_id": self.is_extended_id,
120
+ "is_fd": self.is_fd,
121
+ "replay_file": None if self.replay_file is None else str(self.replay_file),
122
+ "replay_delay": self.replay_delay,
123
+ "seed": self.seed,
124
+ },
125
+ }
126
+
127
+
128
+ class AttackStrategy(ABC):
129
+ """Base class for one attack vector."""
130
+
131
+ @abstractmethod
132
+ def validate(self, request: AttackRequest) -> None:
133
+ """Validate attack-specific runtime values."""
134
+
135
+ @abstractmethod
136
+ def describe(self, request: AttackRequest) -> str:
137
+ """Return a concise human-readable execution plan."""
138
+
139
+ def preview(self, request: AttackRequest, count: int = 3) -> list[CANFrame]:
140
+ """Return representative frames without opening CAN hardware."""
141
+
142
+ return []
143
+
144
+ @abstractmethod
145
+ def execute(self, request: AttackRequest, interface: CANInterfaceBase) -> int:
146
+ """Execute the request and return the number of transmitted frames."""
147
+
148
+
149
+ class GeneratedFrameStrategy(AttackStrategy):
150
+ """Common timed loop for attacks that generate side-channel frames."""
151
+
152
+ @abstractmethod
153
+ def frames(self, request: AttackRequest) -> Iterator[CANFrame]:
154
+ """Yield an unbounded stream of attack frames."""
155
+
156
+ def preview(self, request: AttackRequest, count: int = 3) -> list[CANFrame]:
157
+ self.validate(request)
158
+ stream = self.frames(request)
159
+ return [next(stream) for _ in range(count)]
160
+
161
+ def execute(self, request: AttackRequest, interface: CANInterfaceBase) -> int:
162
+ self.validate(request)
163
+ deadline = time.monotonic() + request.duration
164
+ transmitted = 0
165
+ for frame in self.frames(request):
166
+ if time.monotonic() >= deadline:
167
+ break
168
+ interface.send(frame)
169
+ transmitted += 1
170
+ if request.interval:
171
+ time.sleep(request.interval)
172
+ return transmitted
173
+
174
+
175
+ def _random_dlc(rng: random.Random, request: AttackRequest) -> int:
176
+ values = _CAN_FD_DLC_VALUES if request.is_fd else _CLASSIC_DLC_VALUES
177
+ candidates = tuple(value for value in values if value != request.dlc)
178
+ return rng.choice(candidates or values)
179
+
180
+
181
+ def _validate_explicit_can_id(request: AttackRequest, *, extended: bool) -> int:
182
+ if request.can_id is None:
183
+ raise ValueError("this configuration requires --can-id")
184
+ maximum = 0x1FFFFFFF if extended else 0x7FF
185
+ if request.can_id > maximum:
186
+ width = "29-bit" if extended else "11-bit"
187
+ raise ValueError(f"CAN ID 0x{request.can_id:X} does not fit {width} format")
188
+ return request.can_id
189
+
190
+
191
+ class DoSStrategy(GeneratedFrameStrategy):
192
+ def validate(self, request: AttackRequest) -> None:
193
+ config = request.attack_type.config
194
+ if not isinstance(config, DoSConfig):
195
+ raise ValueError("DoSStrategy requires DoSConfig")
196
+ extended = config.ext_option is DoSOptionExt.EXTENDED_ID
197
+ if config.id_option is DoSOptionId.ALIVE_ID:
198
+ _validate_explicit_can_id(request, extended=extended)
199
+ if config.dlc_option is DoSOptionDLC.DLC_KEEP and request.dlc is None:
200
+ raise ValueError("dlcKeep requires --dlc from the active frame")
201
+
202
+ def describe(self, request: AttackRequest) -> str:
203
+ config = request.attack_type.config
204
+ assert isinstance(config, DoSConfig)
205
+ identifier = (
206
+ "0x000"
207
+ if config.id_option is DoSOptionId.ZERO_ID
208
+ else f"0x{request.can_id:X}"
209
+ )
210
+ return (
211
+ f"DoS injection: id={identifier}, {config.dlc_option.value}, "
212
+ f"{config.ext_option.value}, {config.data_option.value}"
213
+ )
214
+
215
+ def frames(self, request: AttackRequest) -> Iterator[CANFrame]:
216
+ config = request.attack_type.config
217
+ assert isinstance(config, DoSConfig)
218
+ rng = random.Random(request.seed)
219
+ extended = config.ext_option is DoSOptionExt.EXTENDED_ID
220
+ arbitration_id = (
221
+ 0
222
+ if config.id_option is DoSOptionId.ZERO_ID
223
+ else _validate_explicit_can_id(request, extended=extended)
224
+ )
225
+ while True:
226
+ dlc = (
227
+ request.dlc
228
+ if config.dlc_option is DoSOptionDLC.DLC_KEEP
229
+ else _random_dlc(rng, request)
230
+ )
231
+ assert dlc is not None
232
+ payload = (
233
+ bytes([0xFF]) * dlc
234
+ if config.data_option is DoSOptionData.FF_DATA
235
+ else bytes(rng.randrange(256) for _ in range(dlc))
236
+ )
237
+ yield CANFrame(
238
+ arbitration_id=arbitration_id,
239
+ data=payload,
240
+ is_extended_id=extended,
241
+ is_fd=request.is_fd,
242
+ bitrate_switch=request.is_fd,
243
+ )
244
+
245
+
246
+ class FuzzStrategy(GeneratedFrameStrategy):
247
+ def validate(self, request: AttackRequest) -> None:
248
+ config = request.attack_type.config
249
+ if not isinstance(config, FuzzConfig):
250
+ raise ValueError("FuzzStrategy requires FuzzConfig")
251
+ if config.id_option is FuzzOptionId.ALIVE_ID:
252
+ _validate_explicit_can_id(request, extended=request.is_extended_id)
253
+ if config.dlc_option is FuzzOptionDLC.DLC_KEEP and request.dlc is None:
254
+ raise ValueError("dlcKeep requires --dlc from the active frame")
255
+
256
+ def describe(self, request: AttackRequest) -> str:
257
+ config = request.attack_type.config
258
+ assert isinstance(config, FuzzConfig)
259
+ identifier = (
260
+ "random"
261
+ if config.id_option is FuzzOptionId.RANDOM_ID
262
+ else f"0x{request.can_id:X}"
263
+ )
264
+ return f"fuzzing injection: id={identifier}, {config.dlc_option.value}"
265
+
266
+ def frames(self, request: AttackRequest) -> Iterator[CANFrame]:
267
+ config = request.attack_type.config
268
+ assert isinstance(config, FuzzConfig)
269
+ rng = random.Random(request.seed)
270
+ maximum_id = 0x1FFFFFFF if request.is_extended_id else 0x7FF
271
+ while True:
272
+ arbitration_id = (
273
+ rng.randint(0, maximum_id)
274
+ if config.id_option is FuzzOptionId.RANDOM_ID
275
+ else _validate_explicit_can_id(request, extended=request.is_extended_id)
276
+ )
277
+ dlc = (
278
+ request.dlc
279
+ if config.dlc_option is FuzzOptionDLC.DLC_KEEP
280
+ else _random_dlc(rng, request)
281
+ )
282
+ assert dlc is not None
283
+ yield CANFrame(
284
+ arbitration_id=arbitration_id,
285
+ data=bytes(rng.randrange(256) for _ in range(dlc)),
286
+ is_extended_id=request.is_extended_id,
287
+ is_fd=request.is_fd,
288
+ bitrate_switch=request.is_fd,
289
+ )
290
+
291
+
292
+ class SpoofingStrategy(GeneratedFrameStrategy):
293
+ def validate(self, request: AttackRequest) -> None:
294
+ _validate_explicit_can_id(request, extended=request.is_extended_id)
295
+ if request.payload is None:
296
+ raise ValueError("Spoofing requires --data")
297
+
298
+ def describe(self, request: AttackRequest) -> str:
299
+ payload = request.payload.hex(" ").upper()
300
+ return f"spoofing injection: id=0x{request.can_id:X}, payload={payload}"
301
+
302
+ def frames(self, request: AttackRequest) -> Iterator[CANFrame]:
303
+ assert request.can_id is not None and request.payload is not None
304
+ frame = CANFrame(
305
+ arbitration_id=request.can_id,
306
+ data=request.payload,
307
+ is_extended_id=request.is_extended_id,
308
+ is_fd=request.is_fd,
309
+ bitrate_switch=request.is_fd,
310
+ )
311
+ while True:
312
+ yield frame
313
+
314
+
315
+ def _parse_bool(value: str) -> bool:
316
+ normalized = value.strip().lower()
317
+ if normalized in {"1", "true", "yes", "y"}:
318
+ return True
319
+ if normalized in {"0", "false", "no", "n", ""}:
320
+ return False
321
+ raise ValueError(f"invalid boolean value: {value!r}")
322
+
323
+
324
+ def _load_replay_csv(path: Path) -> list[CANFrame]:
325
+ """Load frames from an IV-CAN-style CSV file."""
326
+
327
+ if not path.is_file():
328
+ raise ValueError(f"replay file does not exist: {path}")
329
+ frames: list[CANFrame] = []
330
+ with path.open("r", encoding="utf-8", newline="") as handle:
331
+ for line_number, row in enumerate(csv.DictReader(handle), start=2):
332
+ try:
333
+ frames.append(
334
+ CANFrame(
335
+ arbitration_id=parse_can_id(row["can_id"]),
336
+ data=parse_payload(row.get("data", "")),
337
+ timestamp=float(row["timestamp"]) if row.get("timestamp") else None,
338
+ is_extended_id=_parse_bool(row.get("is_extended_id", "false")),
339
+ is_fd=_parse_bool(row.get("is_fd", "false")),
340
+ )
341
+ )
342
+ except (KeyError, ValueError) as exc:
343
+ raise ValueError(f"invalid replay CSV row {line_number}: {exc}") from exc
344
+ if not frames:
345
+ raise ValueError("replay file contains no frames")
346
+ return frames
347
+
348
+
349
+ class ReplayStrategy(AttackStrategy):
350
+ def validate(self, request: AttackRequest) -> None:
351
+ config = request.attack_type.config
352
+ if not isinstance(config, ReplayConfig):
353
+ raise ValueError("ReplayStrategy requires ReplayConfig")
354
+ if request.replay_file is None:
355
+ raise ValueError("Replay requires --replay-file")
356
+ if config.timing is ReplayOption.DELAY and request.replay_delay <= 0:
357
+ raise ValueError("delayed replay requires a positive --replay-delay")
358
+
359
+ def describe(self, request: AttackRequest) -> str:
360
+ config = request.attack_type.config
361
+ assert isinstance(config, ReplayConfig)
362
+ suffix = f" by {request.replay_delay:g} s" if config.timing is ReplayOption.DELAY else ""
363
+ return f"replay {request.replay_file}: {config.timing.value}{suffix}"
364
+
365
+ def preview(self, request: AttackRequest, count: int = 3) -> list[CANFrame]:
366
+ self.validate(request)
367
+ assert request.replay_file is not None
368
+ return _load_replay_csv(request.replay_file)[:count]
369
+
370
+ def execute(self, request: AttackRequest, interface: CANInterfaceBase) -> int:
371
+ self.validate(request)
372
+ config = request.attack_type.config
373
+ assert isinstance(config, ReplayConfig) and request.replay_file is not None
374
+ frames = _load_replay_csv(request.replay_file)
375
+ if config.timing is ReplayOption.DELAY:
376
+ time.sleep(request.replay_delay)
377
+
378
+ first_timestamp = frames[0].timestamp
379
+ started_at = time.monotonic()
380
+ transmitted = 0
381
+ for frame in frames:
382
+ if first_timestamp is not None and frame.timestamp is not None:
383
+ due = started_at + max(0.0, frame.timestamp - first_timestamp)
384
+ time.sleep(max(0.0, due - time.monotonic()))
385
+ elif transmitted and request.interval:
386
+ time.sleep(request.interval)
387
+ interface.send(frame)
388
+ transmitted += 1
389
+ return transmitted
390
+
391
+
392
+ class SuspensionStrategy(AttackStrategy):
393
+ def validate(self, request: AttackRequest) -> None:
394
+ if not isinstance(request.attack_type.config, SuspensionConfig):
395
+ raise ValueError("SuspensionStrategy requires SuspensionConfig")
396
+
397
+ def describe(self, request: AttackRequest) -> str:
398
+ config = request.attack_type.config
399
+ assert isinstance(config, SuspensionConfig)
400
+ return (
401
+ f"MitM suspension: drop {', '.join(config.suspension_CAN_id_list)} "
402
+ f"for {config.suspension_duration_sec} s"
403
+ )
404
+
405
+ def execute(self, request: AttackRequest, interface: CANInterfaceBase) -> int:
406
+ self.validate(request)
407
+ raise NotImplementedError(
408
+ "Suspension needs a two-interface MitM bridge; the strategy contract is ready, "
409
+ "but can_base currently exposes individual interfaces only."
410
+ )
411
+
412
+
413
+ class MasqueradeStrategy(AttackStrategy):
414
+ def validate(self, request: AttackRequest) -> None:
415
+ _validate_explicit_can_id(request, extended=request.is_extended_id)
416
+ if request.payload is None:
417
+ raise ValueError("Masquerade requires --data for the forged replacement frame")
418
+
419
+ def describe(self, request: AttackRequest) -> str:
420
+ return f"MitM masquerade: replace id=0x{request.can_id:X} with forged payload"
421
+
422
+ def execute(self, request: AttackRequest, interface: CANInterfaceBase) -> int:
423
+ self.validate(request)
424
+ raise NotImplementedError(
425
+ "Masquerade needs a two-interface MitM bridge that suppresses legitimate frames "
426
+ "before forwarding forged replacements."
427
+ )
428
+
429
+
430
+ _STRATEGIES: dict[AttackBaseType, type[AttackStrategy]] = {
431
+ AttackBaseType.DOS: DoSStrategy,
432
+ AttackBaseType.FUZZ: FuzzStrategy,
433
+ AttackBaseType.REPLAY: ReplayStrategy,
434
+ AttackBaseType.SPOOFING: SpoofingStrategy,
435
+ AttackBaseType.SUSPENSION: SuspensionStrategy,
436
+ AttackBaseType.MASQUERADE: MasqueradeStrategy,
437
+ }
438
+
439
+
440
+ class AttackRunner:
441
+ """Resolve and run the strategy associated with an :class:`AttackRequest`."""
442
+
443
+ def strategy_for(self, request: AttackRequest) -> AttackStrategy:
444
+ try:
445
+ strategy_class = _STRATEGIES[request.attack_type.kind]
446
+ except KeyError as exc:
447
+ raise ValueError(f"unsupported attack type: {request.attack_type.kind.value}") from exc
448
+ strategy = strategy_class()
449
+ strategy.validate(request)
450
+ return strategy
451
+
452
+ def describe(self, request: AttackRequest) -> str:
453
+ return self.strategy_for(request).describe(request)
454
+
455
+ def preview(self, request: AttackRequest, count: int = 3) -> list[CANFrame]:
456
+ return self.strategy_for(request).preview(request, count=count)
457
+
458
+ def execute(self, request: AttackRequest, interface: CANInterfaceBase) -> int:
459
+ return self.strategy_for(request).execute(request, interface)
code/attack_generation/src/ivcan_attacker/attack_types.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attack taxonomy used to construct the IV-CAN-v1 attack trials."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+
8
+
9
+ class AttackBaseType(str, Enum):
10
+ DOS = "DoS"
11
+ FUZZ = "fuzzing"
12
+ REPLAY = "replay"
13
+ SPOOFING = "spoofing"
14
+ SUSPENSION = "suspension"
15
+ MASQUERADE = "masquerade"
16
+
17
+
18
+ class DoSOptionId(str, Enum):
19
+ ALIVE_ID = "aliveId"
20
+ ZERO_ID = "zeroId"
21
+
22
+
23
+ class DoSOptionDLC(str, Enum):
24
+ DLC_CHANGE = "dlcChange"
25
+ DLC_KEEP = "dlcKeep"
26
+
27
+
28
+ class DoSOptionExt(str, Enum):
29
+ EXTENDED_ID = "extendedId"
30
+ STANDARD_ID = "standardId"
31
+
32
+
33
+ class DoSOptionData(str, Enum):
34
+ RANDOM_DATA = "randomData"
35
+ FF_DATA = "FFData"
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class DoSConfig:
40
+ id_option: DoSOptionId
41
+ dlc_option: DoSOptionDLC
42
+ ext_option: DoSOptionExt
43
+ data_option: DoSOptionData
44
+
45
+ def to_dict(self) -> dict:
46
+ return {
47
+ "id_option": self.id_option.value,
48
+ "dlc_option": self.dlc_option.value,
49
+ "ext_option": self.ext_option.value,
50
+ "data_option": self.data_option.value,
51
+ }
52
+
53
+
54
+ class FuzzOptionId(str, Enum):
55
+ ALIVE_ID = "aliveId"
56
+ RANDOM_ID = "randomId"
57
+
58
+
59
+ class FuzzOptionDLC(str, Enum):
60
+ DLC_CHANGE = "dlcChange"
61
+ DLC_KEEP = "dlcKeep"
62
+
63
+
64
+ @dataclass(frozen=True, slots=True)
65
+ class FuzzConfig:
66
+ id_option: FuzzOptionId
67
+ dlc_option: FuzzOptionDLC
68
+
69
+ def to_dict(self) -> dict:
70
+ return {
71
+ "id_option": self.id_option.value,
72
+ "dlc_option": self.dlc_option.value,
73
+ }
74
+
75
+
76
+ class ReplayOption(str, Enum):
77
+ DELAY = "delay"
78
+ IMMEDIATE = "immediate"
79
+
80
+
81
+ @dataclass(frozen=True, slots=True)
82
+ class ReplayConfig:
83
+ timing: ReplayOption
84
+
85
+ def to_dict(self) -> dict:
86
+ return {"timing": self.timing.value}
87
+
88
+
89
+ @dataclass(frozen=True, slots=True)
90
+ class SuspensionConfig:
91
+ suspension_duration_sec: int
92
+ suspension_CAN_id_list: list[str]
93
+
94
+ def __post_init__(self) -> None:
95
+ if self.suspension_duration_sec <= 0:
96
+ raise ValueError("suspension_duration_sec must be positive")
97
+ if not self.suspension_CAN_id_list:
98
+ raise ValueError("suspension_CAN_id_list cannot be empty")
99
+
100
+ def to_dict(self) -> dict:
101
+ return {
102
+ "suspension_duration_sec": self.suspension_duration_sec,
103
+ "suspension_CAN_id_list": self.suspension_CAN_id_list,
104
+ }
105
+
106
+
107
+ AttackConfig = DoSConfig | FuzzConfig | ReplayConfig | SuspensionConfig
108
+
109
+
110
+ @dataclass(frozen=True, slots=True)
111
+ class AttackType:
112
+ kind: AttackBaseType
113
+ config: AttackConfig | None = None
114
+
115
+ def __post_init__(self) -> None:
116
+ expected = {
117
+ AttackBaseType.DOS: DoSConfig,
118
+ AttackBaseType.FUZZ: FuzzConfig,
119
+ AttackBaseType.REPLAY: ReplayConfig,
120
+ AttackBaseType.SUSPENSION: SuspensionConfig,
121
+ }.get(self.kind)
122
+ if expected is None:
123
+ if self.config is not None:
124
+ raise ValueError(f"{self.kind.value} does not accept a config object")
125
+ elif not isinstance(self.config, expected):
126
+ raise ValueError(f"{self.kind.value} requires {expected.__name__}")
127
+
128
+ def to_dict(self) -> dict:
129
+ return {
130
+ "kind": self.kind.value,
131
+ "config": None if self.config is None else self.config.to_dict(),
132
+ }
133
+
code/attack_generation/src/ivcan_attacker/can_base/__init__.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable public API for CAN hardware access."""
2
+
3
+ from .can_interface_base import CANInterfaceBase
4
+ from .exceptions import (
5
+ CANBaseError,
6
+ CANConfigurationError,
7
+ CANConnectionError,
8
+ CANDependencyError,
9
+ CANDisconnectionError,
10
+ CANQueueFullError,
11
+ CANReceiveError,
12
+ CANStateError,
13
+ CANTimeoutError,
14
+ CANTransmissionError,
15
+ )
16
+ from .pcan_interface import PCANInterface, PCANInterfaceConfig
17
+ from .types import (
18
+ CANFrame,
19
+ CANInterfaceConfig,
20
+ CANStatistics,
21
+ ConnectionState,
22
+ OverflowPolicy,
23
+ )
24
+
25
+ __all__ = [
26
+ "CANBaseError",
27
+ "CANConfigurationError",
28
+ "CANConnectionError",
29
+ "CANDependencyError",
30
+ "CANDisconnectionError",
31
+ "CANFrame",
32
+ "CANInterfaceBase",
33
+ "CANInterfaceConfig",
34
+ "CANQueueFullError",
35
+ "CANReceiveError",
36
+ "CANStateError",
37
+ "CANStatistics",
38
+ "CANTimeoutError",
39
+ "CANTransmissionError",
40
+ "ConnectionState",
41
+ "OverflowPolicy",
42
+ "PCANInterface",
43
+ "PCANInterfaceConfig",
44
+ ]
code/attack_generation/src/ivcan_attacker/can_base/can_interface_base.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thread-safe lifecycle and queueing foundation for CAN adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import queue
7
+ import threading
8
+ import time
9
+ from abc import ABC, abstractmethod
10
+ from dataclasses import dataclass, field
11
+ from typing import Iterable
12
+
13
+ from .exceptions import (
14
+ CANBaseError,
15
+ CANConnectionError,
16
+ CANDisconnectionError,
17
+ CANQueueFullError,
18
+ CANReceiveError,
19
+ CANStateError,
20
+ CANTimeoutError,
21
+ CANTransmissionError,
22
+ )
23
+ from .types import (
24
+ CANFrame,
25
+ CANInterfaceConfig,
26
+ CANStatistics,
27
+ ConnectionState,
28
+ OverflowPolicy,
29
+ )
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class _TxRequest:
34
+ frame: CANFrame
35
+ completion: threading.Event = field(default_factory=threading.Event)
36
+ error: BaseException | None = None
37
+
38
+
39
+ class CANInterfaceBase(ABC):
40
+ """Base class for a full-duplex CAN hardware interface.
41
+
42
+ Subclasses only implement the four synchronous hardware hooks. This class
43
+ owns connection state, bounded queues, one receive worker, and one ordered
44
+ transmit worker. A worker is created per direction, never per frame.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ config: CANInterfaceConfig,
50
+ *,
51
+ logger: logging.Logger | None = None,
52
+ ) -> None:
53
+ self.config = config
54
+ self._logger = logger or logging.getLogger(
55
+ f"{self.__class__.__module__}.{self.__class__.__qualname__}"
56
+ )
57
+
58
+ self._state = ConnectionState.DISCONNECTED
59
+ self._state_lock = threading.RLock()
60
+ self._lifecycle_lock = threading.Lock()
61
+ self._statistics_lock = threading.Lock()
62
+ self._last_error: BaseException | None = None
63
+
64
+ self._rx_queue: queue.Queue[CANFrame] = queue.Queue(
65
+ maxsize=config.rx_queue_size
66
+ )
67
+ self._tx_queue: queue.Queue[_TxRequest] = queue.Queue(
68
+ maxsize=config.tx_queue_size
69
+ )
70
+ self._stop_event = threading.Event()
71
+ self._drain_tx_on_stop = False
72
+ self._rx_thread: threading.Thread | None = None
73
+ self._tx_thread: threading.Thread | None = None
74
+
75
+ self._rx_received = 0
76
+ self._rx_delivered = 0
77
+ self._rx_dropped = 0
78
+ self._tx_queued = 0
79
+ self._tx_sent = 0
80
+ self._tx_failed = 0
81
+ self._tx_dropped = 0
82
+
83
+ @property
84
+ def state(self) -> ConnectionState:
85
+ """Return the current lifecycle state."""
86
+
87
+ with self._state_lock:
88
+ return self._state
89
+
90
+ @property
91
+ def connected(self) -> bool:
92
+ """Whether the interface currently accepts receive/send operations."""
93
+
94
+ return self.state is ConnectionState.CONNECTED
95
+
96
+ @property
97
+ def last_error(self) -> BaseException | None:
98
+ """Return the fatal worker or connection error, if one occurred."""
99
+
100
+ with self._state_lock:
101
+ return self._last_error
102
+
103
+ @property
104
+ def statistics(self) -> CANStatistics:
105
+ """Return a consistent snapshot of runtime counters."""
106
+
107
+ with self._statistics_lock:
108
+ return CANStatistics(
109
+ rx_received=self._rx_received,
110
+ rx_delivered=self._rx_delivered,
111
+ rx_dropped=self._rx_dropped,
112
+ tx_queued=self._tx_queued,
113
+ tx_sent=self._tx_sent,
114
+ tx_failed=self._tx_failed,
115
+ tx_dropped=self._tx_dropped,
116
+ )
117
+
118
+ def connect(self) -> None:
119
+ """Open the hardware and start the independent RX/TX workers.
120
+
121
+ Calling this method while already connected is harmless. After a
122
+ failed connection or fatal worker error, call :meth:`disconnect` before
123
+ attempting to reconnect.
124
+ """
125
+
126
+ with self._lifecycle_lock:
127
+ current = self.state
128
+ if current is ConnectionState.CONNECTED:
129
+ return
130
+ if current is not ConnectionState.DISCONNECTED:
131
+ raise CANStateError(f"cannot connect while interface is {current.value}")
132
+
133
+ self._set_state(ConnectionState.CONNECTING)
134
+ with self._state_lock:
135
+ self._last_error = None
136
+ self._stop_event.clear()
137
+ self._drain_tx_on_stop = False
138
+ self._rx_queue = queue.Queue(maxsize=self.config.rx_queue_size)
139
+ self._tx_queue = queue.Queue(maxsize=self.config.tx_queue_size)
140
+
141
+ try:
142
+ self._open_hardware()
143
+ self._set_state(ConnectionState.CONNECTED)
144
+ self._rx_thread = threading.Thread(
145
+ target=self._rx_worker,
146
+ name=f"{self.config.thread_name_prefix}-rx",
147
+ daemon=True,
148
+ )
149
+ self._tx_thread = threading.Thread(
150
+ target=self._tx_worker,
151
+ name=f"{self.config.thread_name_prefix}-tx",
152
+ daemon=True,
153
+ )
154
+ self._rx_thread.start()
155
+ self._tx_thread.start()
156
+ except Exception as exc:
157
+ self._stop_event.set()
158
+ try:
159
+ self._close_hardware()
160
+ except Exception as close_exc: # pragma: no cover - defensive path
161
+ self._logger.warning(
162
+ "hardware cleanup after failed connect also failed: %s",
163
+ close_exc,
164
+ )
165
+ error = (
166
+ exc
167
+ if isinstance(exc, CANBaseError)
168
+ else CANConnectionError(f"failed to connect CAN hardware: {exc}")
169
+ )
170
+ with self._state_lock:
171
+ self._last_error = error
172
+ self._set_state(ConnectionState.ERROR)
173
+ raise error from exc
174
+
175
+ def disconnect(
176
+ self,
177
+ *,
178
+ drain_tx: bool = False,
179
+ timeout: float | None = None,
180
+ ) -> None:
181
+ """Stop workers and close the hardware connection.
182
+
183
+ Args:
184
+ drain_tx: Send frames already queued before closing. The default
185
+ fails pending requests immediately, which is safer for HIL use.
186
+ timeout: Overall worker join timeout. Defaults to the configured
187
+ ``worker_join_timeout``.
188
+ """
189
+
190
+ if timeout is not None and timeout < 0:
191
+ raise ValueError("timeout cannot be negative")
192
+
193
+ with self._lifecycle_lock:
194
+ current = self.state
195
+ if current is ConnectionState.DISCONNECTED:
196
+ return
197
+ if current in (ConnectionState.CONNECTING, ConnectionState.DISCONNECTING):
198
+ raise CANStateError(
199
+ f"cannot disconnect while interface is {current.value}"
200
+ )
201
+
202
+ self._set_state(ConnectionState.DISCONNECTING)
203
+ self._drain_tx_on_stop = drain_tx
204
+ self._stop_event.set()
205
+ if not drain_tx:
206
+ self._fail_pending_tx(
207
+ CANStateError("transmission cancelled by disconnect"),
208
+ dropped=True,
209
+ )
210
+
211
+ join_budget = self.config.worker_join_timeout if timeout is None else timeout
212
+ deadline = time.monotonic() + join_budget
213
+ live_threads: list[str] = []
214
+ for worker in (self._rx_thread, self._tx_thread):
215
+ if worker is None or worker is threading.current_thread():
216
+ continue
217
+ worker.join(max(0.0, deadline - time.monotonic()))
218
+ if worker.is_alive():
219
+ live_threads.append(worker.name)
220
+
221
+ close_error: BaseException | None = None
222
+ try:
223
+ self._close_hardware()
224
+ except Exception as exc:
225
+ close_error = exc
226
+ finally:
227
+ self._fail_pending_tx(
228
+ CANStateError("interface disconnected before transmission"),
229
+ dropped=True,
230
+ )
231
+ self._rx_thread = None
232
+ self._tx_thread = None
233
+ self._drain_tx_on_stop = False
234
+ self._set_state(ConnectionState.DISCONNECTED)
235
+
236
+ problems: list[str] = []
237
+ if live_threads:
238
+ problems.append(f"workers did not stop: {', '.join(live_threads)}")
239
+ if close_error is not None:
240
+ problems.append(f"hardware close failed: {close_error}")
241
+ if problems:
242
+ error = CANDisconnectionError("; ".join(problems))
243
+ with self._state_lock:
244
+ self._last_error = error
245
+ raise error from close_error
246
+
247
+ def capture(
248
+ self,
249
+ *,
250
+ max_frames: int = 1,
251
+ timeout: float | None = None,
252
+ ) -> list[CANFrame]:
253
+ """Return up to ``max_frames`` received frames from the RX queue.
254
+
255
+ With a finite timeout the method returns a partial batch when the
256
+ deadline expires. ``timeout=0`` performs a non-blocking queue drain;
257
+ ``timeout=None`` waits until the requested batch is complete.
258
+ """
259
+
260
+ if max_frames <= 0:
261
+ raise ValueError("max_frames must be positive")
262
+ if timeout is not None and timeout < 0:
263
+ raise ValueError("timeout cannot be negative")
264
+ self._require_connected("capture")
265
+
266
+ deadline = None if timeout is None else time.monotonic() + timeout
267
+ frames: list[CANFrame] = []
268
+ while len(frames) < max_frames:
269
+ try:
270
+ if timeout == 0:
271
+ frame = self._rx_queue.get_nowait()
272
+ else:
273
+ frame = self._wait_for_rx_frame(deadline)
274
+ except queue.Empty:
275
+ break
276
+ frames.append(frame)
277
+ self._rx_queue.task_done()
278
+
279
+ if frames:
280
+ self._increment_stat("_rx_delivered", len(frames))
281
+ return frames
282
+
283
+ def send(
284
+ self,
285
+ frames: CANFrame | Iterable[CANFrame],
286
+ *,
287
+ block: bool = False,
288
+ timeout: float | None = None,
289
+ ) -> int:
290
+ """Queue one frame or an iterable of frames for ordered transmission.
291
+
292
+ ``block=True`` waits for the hardware write result of every frame.
293
+ The timeout is an overall deadline covering queue admission and, when
294
+ blocking, transmission completion.
295
+ """
296
+
297
+ if timeout is not None and timeout < 0:
298
+ raise ValueError("timeout cannot be negative")
299
+ self._require_connected("send")
300
+
301
+ if isinstance(frames, CANFrame):
302
+ frame_batch = (frames,)
303
+ else:
304
+ frame_batch = tuple(frames)
305
+ if not all(isinstance(frame, CANFrame) for frame in frame_batch):
306
+ raise TypeError("send expects CANFrame objects")
307
+ if not frame_batch:
308
+ return 0
309
+
310
+ deadline = None if timeout is None else time.monotonic() + timeout
311
+ requests: list[_TxRequest] = []
312
+ for frame in frame_batch:
313
+ request = _TxRequest(frame=frame)
314
+ self._enqueue_tx(request, deadline)
315
+ requests.append(request)
316
+ self._increment_stat("_tx_queued")
317
+
318
+ if block:
319
+ for request in requests:
320
+ self._wait_for_tx_request(request, deadline)
321
+ return len(requests)
322
+
323
+ def __enter__(self) -> "CANInterfaceBase":
324
+ self.connect()
325
+ return self
326
+
327
+ def __exit__(self, exc_type, exc, traceback) -> None:
328
+ self.disconnect()
329
+
330
+ def _wait_for_rx_frame(self, deadline: float | None) -> CANFrame:
331
+ while True:
332
+ current = self.state
333
+ if current is ConnectionState.ERROR:
334
+ error = self.last_error
335
+ raise CANReceiveError(f"receive worker stopped: {error}") from error
336
+ if current is not ConnectionState.CONNECTED:
337
+ raise CANStateError(f"capture requires connected state, got {current.value}")
338
+
339
+ if deadline is None:
340
+ wait_time = min(self.config.receive_timeout, 0.05)
341
+ else:
342
+ remaining = deadline - time.monotonic()
343
+ if remaining <= 0:
344
+ raise queue.Empty
345
+ wait_time = min(remaining, self.config.receive_timeout, 0.05)
346
+ try:
347
+ return self._rx_queue.get(timeout=wait_time)
348
+ except queue.Empty:
349
+ if deadline is not None and time.monotonic() >= deadline:
350
+ raise
351
+
352
+ def _enqueue_tx(self, request: _TxRequest, deadline: float | None) -> None:
353
+ policy = self.config.tx_overflow_policy
354
+ if policy is OverflowPolicy.RAISE:
355
+ try:
356
+ self._tx_queue.put_nowait(request)
357
+ except queue.Full as exc:
358
+ raise CANQueueFullError("transmit queue is full") from exc
359
+ return
360
+
361
+ if policy is OverflowPolicy.DROP_OLDEST:
362
+ while True:
363
+ try:
364
+ self._tx_queue.put_nowait(request)
365
+ return
366
+ except queue.Full:
367
+ try:
368
+ dropped = self._tx_queue.get_nowait()
369
+ except queue.Empty:
370
+ continue
371
+ self._complete_tx(
372
+ dropped,
373
+ CANQueueFullError("transmit request dropped by overflow policy"),
374
+ dropped=True,
375
+ )
376
+ self._tx_queue.task_done()
377
+
378
+ while True:
379
+ self._require_connected("send")
380
+ if deadline is None:
381
+ wait_time = 0.05
382
+ else:
383
+ remaining = deadline - time.monotonic()
384
+ if remaining <= 0:
385
+ raise CANQueueFullError("timed out waiting for transmit queue space")
386
+ wait_time = min(remaining, 0.05)
387
+ try:
388
+ self._tx_queue.put(request, timeout=wait_time)
389
+ return
390
+ except queue.Full:
391
+ if deadline is not None and time.monotonic() >= deadline:
392
+ raise CANQueueFullError(
393
+ "timed out waiting for transmit queue space"
394
+ )
395
+
396
+ def _wait_for_tx_request(
397
+ self, request: _TxRequest, deadline: float | None
398
+ ) -> None:
399
+ while not request.completion.is_set():
400
+ if deadline is None:
401
+ wait_time = 0.05
402
+ else:
403
+ remaining = deadline - time.monotonic()
404
+ if remaining <= 0:
405
+ raise CANTimeoutError("timed out waiting for CAN transmission")
406
+ wait_time = min(remaining, 0.05)
407
+ request.completion.wait(wait_time)
408
+ if request.error is not None:
409
+ if isinstance(request.error, CANBaseError):
410
+ raise request.error
411
+ raise CANTransmissionError(str(request.error)) from request.error
412
+
413
+ def _rx_worker(self) -> None:
414
+ try:
415
+ while not self._stop_event.is_set():
416
+ frames = self._receive_batch_from_hardware(
417
+ timeout=self.config.receive_timeout,
418
+ max_frames=self.config.rx_batch_size,
419
+ )
420
+ for frame in frames:
421
+ if not isinstance(frame, CANFrame):
422
+ raise CANReceiveError(
423
+ "hardware adapter returned a non-CANFrame value"
424
+ )
425
+ self._increment_stat("_rx_received")
426
+ self._enqueue_rx(frame)
427
+ if self._stop_event.is_set():
428
+ break
429
+ except Exception as exc:
430
+ if not self._stop_event.is_set():
431
+ error = (
432
+ exc
433
+ if isinstance(exc, CANReceiveError)
434
+ else CANReceiveError(f"receive worker failed: {exc}")
435
+ )
436
+ self._record_fatal_error(error)
437
+
438
+ def _enqueue_rx(self, frame: CANFrame) -> None:
439
+ policy = self.config.rx_overflow_policy
440
+ if policy is OverflowPolicy.BLOCK:
441
+ while not self._stop_event.is_set():
442
+ try:
443
+ self._rx_queue.put(frame, timeout=0.05)
444
+ return
445
+ except queue.Full:
446
+ continue
447
+ self._increment_stat("_rx_dropped")
448
+ return
449
+
450
+ if policy is OverflowPolicy.RAISE:
451
+ try:
452
+ self._rx_queue.put_nowait(frame)
453
+ except queue.Full as exc:
454
+ self._increment_stat("_rx_dropped")
455
+ raise CANQueueFullError("receive queue is full") from exc
456
+ return
457
+
458
+ while True:
459
+ try:
460
+ self._rx_queue.put_nowait(frame)
461
+ return
462
+ except queue.Full:
463
+ try:
464
+ self._rx_queue.get_nowait()
465
+ except queue.Empty:
466
+ continue
467
+ self._rx_queue.task_done()
468
+ self._increment_stat("_rx_dropped")
469
+
470
+ def _tx_worker(self) -> None:
471
+ fatal_error: BaseException | None = None
472
+ while True:
473
+ if self._stop_event.is_set() and (
474
+ not self._drain_tx_on_stop or self._tx_queue.empty()
475
+ ):
476
+ break
477
+ try:
478
+ first = self._tx_queue.get(timeout=0.05)
479
+ except queue.Empty:
480
+ continue
481
+
482
+ batch = [first]
483
+ for _ in range(self.config.tx_batch_size - 1):
484
+ try:
485
+ batch.append(self._tx_queue.get_nowait())
486
+ except queue.Empty:
487
+ break
488
+
489
+ for request in batch:
490
+ if fatal_error is not None:
491
+ self._complete_tx(request, fatal_error, dropped=True)
492
+ self._tx_queue.task_done()
493
+ continue
494
+ if self._stop_event.is_set() and not self._drain_tx_on_stop:
495
+ self._complete_tx(
496
+ request,
497
+ CANStateError("transmission cancelled by disconnect"),
498
+ dropped=True,
499
+ )
500
+ self._tx_queue.task_done()
501
+ continue
502
+ try:
503
+ self._write_frame_to_hardware(request.frame)
504
+ except CANTransmissionError as exc:
505
+ self._complete_tx(request, exc)
506
+ except Exception as exc:
507
+ fatal_error = CANTransmissionError(
508
+ f"transmit worker failed: {exc}"
509
+ )
510
+ self._complete_tx(request, fatal_error)
511
+ else:
512
+ self._complete_tx(request)
513
+ finally:
514
+ self._tx_queue.task_done()
515
+
516
+ if fatal_error is not None:
517
+ self._record_fatal_error(fatal_error)
518
+ break
519
+
520
+ self._fail_pending_tx(
521
+ fatal_error or CANStateError("transmit worker stopped"),
522
+ dropped=True,
523
+ )
524
+
525
+ def _complete_tx(
526
+ self,
527
+ request: _TxRequest,
528
+ error: BaseException | None = None,
529
+ *,
530
+ dropped: bool = False,
531
+ ) -> None:
532
+ if request.completion.is_set():
533
+ return
534
+ request.error = error
535
+ request.completion.set()
536
+ if error is None:
537
+ self._increment_stat("_tx_sent")
538
+ else:
539
+ self._increment_stat("_tx_failed")
540
+ if dropped:
541
+ self._increment_stat("_tx_dropped")
542
+
543
+ def _fail_pending_tx(self, error: BaseException, *, dropped: bool) -> None:
544
+ while True:
545
+ try:
546
+ request = self._tx_queue.get_nowait()
547
+ except queue.Empty:
548
+ return
549
+ self._complete_tx(request, error, dropped=dropped)
550
+ self._tx_queue.task_done()
551
+
552
+ def _record_fatal_error(self, error: BaseException) -> None:
553
+ with self._state_lock:
554
+ self._last_error = error
555
+ if self._state not in (
556
+ ConnectionState.DISCONNECTING,
557
+ ConnectionState.DISCONNECTED,
558
+ ):
559
+ self._state = ConnectionState.ERROR
560
+ self._stop_event.set()
561
+ self._logger.error("CAN worker stopped: %s", error)
562
+
563
+ def _require_connected(self, operation: str) -> None:
564
+ current = self.state
565
+ if current is not ConnectionState.CONNECTED:
566
+ raise CANStateError(
567
+ f"{operation} requires connected state, got {current.value}"
568
+ )
569
+
570
+ def _set_state(self, state: ConnectionState) -> None:
571
+ with self._state_lock:
572
+ self._state = state
573
+
574
+ def _increment_stat(self, attribute: str, value: int = 1) -> None:
575
+ with self._statistics_lock:
576
+ setattr(self, attribute, getattr(self, attribute) + value)
577
+
578
+ @abstractmethod
579
+ def _open_hardware(self) -> None:
580
+ """Initialize the concrete CAN hardware connection."""
581
+
582
+ @abstractmethod
583
+ def _close_hardware(self) -> None:
584
+ """Release concrete CAN hardware resources; must be idempotent."""
585
+
586
+ @abstractmethod
587
+ def _receive_batch_from_hardware(
588
+ self, *, timeout: float, max_frames: int
589
+ ) -> list[CANFrame]:
590
+ """Block for the first frame, then return up to ``max_frames``."""
591
+
592
+ @abstractmethod
593
+ def _write_frame_to_hardware(self, frame: CANFrame) -> None:
594
+ """Synchronously submit one frame to the hardware driver."""
code/attack_generation/src/ivcan_attacker/can_base/exceptions.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exceptions raised by the CAN base layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class CANBaseError(Exception):
7
+ """Base class for all errors exposed by :mod:`can_base`."""
8
+
9
+
10
+ class CANConfigurationError(CANBaseError, ValueError):
11
+ """The interface configuration is invalid."""
12
+
13
+
14
+ class CANDependencyError(CANBaseError, ImportError):
15
+ """A required driver or Python package is unavailable."""
16
+
17
+
18
+ class CANStateError(CANBaseError, RuntimeError):
19
+ """An operation is not valid in the current connection state."""
20
+
21
+
22
+ class CANConnectionError(CANBaseError, ConnectionError):
23
+ """Opening or maintaining the hardware connection failed."""
24
+
25
+
26
+ class CANDisconnectionError(CANBaseError, ConnectionError):
27
+ """The hardware connection could not be closed cleanly."""
28
+
29
+
30
+ class CANReceiveError(CANBaseError, OSError):
31
+ """Receiving a CAN frame failed."""
32
+
33
+
34
+ class CANTransmissionError(CANBaseError, OSError):
35
+ """Transmitting a CAN frame failed."""
36
+
37
+
38
+ class CANQueueFullError(CANBaseError):
39
+ """A bounded receive or transmit queue has no free capacity."""
40
+
41
+
42
+ class CANTimeoutError(CANBaseError, TimeoutError):
43
+ """An operation did not complete before its deadline."""
code/attack_generation/src/ivcan_attacker/can_base/pcan_interface.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PEAK PCAN adapter implemented through python-can's PCAN backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import os
7
+ import struct
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from types import ModuleType
11
+ from typing import Any
12
+
13
+ from .can_interface_base import CANInterfaceBase
14
+ from .exceptions import (
15
+ CANConfigurationError,
16
+ CANConnectionError,
17
+ CANDependencyError,
18
+ CANDisconnectionError,
19
+ CANReceiveError,
20
+ CANStateError,
21
+ CANTransmissionError,
22
+ )
23
+ from .types import CANFrame, CANInterfaceConfig, ConnectionState
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class PCANInterfaceConfig(CANInterfaceConfig):
28
+ """PCAN-specific connection and CAN FD timing parameters.
29
+
30
+ The default FD timing reproduces the 500 kbit/s nominal and 2 Mbit/s data
31
+ settings found in the legacy repository.
32
+ """
33
+
34
+ device_id: int | None = None
35
+ listen_only: bool = False
36
+ receive_own_messages: bool = False
37
+ auto_reset: bool = False
38
+ dll_path: str | Path | None = None
39
+ use_bundled_dll: bool = False
40
+
41
+ data_bitrate: int = 2_000_000
42
+ fd_clock_mhz: int = 80
43
+ nom_brp: int = 2
44
+ nom_tseg1: int = 63
45
+ nom_tseg2: int = 16
46
+ nom_sjw: int = 16
47
+ data_brp: int = 2
48
+ data_tseg1: int = 15
49
+ data_tseg2: int = 4
50
+ data_sjw: int = 4
51
+
52
+ def __post_init__(self) -> None:
53
+ CANInterfaceConfig.__post_init__(self)
54
+ if self.device_id is not None and self.device_id < 0:
55
+ raise CANConfigurationError("device_id cannot be negative")
56
+ if self.dll_path is not None:
57
+ object.__setattr__(self, "dll_path", Path(self.dll_path).expanduser())
58
+ if self.data_bitrate <= 0:
59
+ raise CANConfigurationError("data_bitrate must be positive")
60
+
61
+ ranges = {
62
+ "fd_clock_mhz": (1, None),
63
+ "nom_brp": (1, 1024),
64
+ "nom_tseg1": (1, 256),
65
+ "nom_tseg2": (1, 128),
66
+ "nom_sjw": (1, 128),
67
+ "data_brp": (1, 1024),
68
+ "data_tseg1": (1, 32),
69
+ "data_tseg2": (1, 16),
70
+ "data_sjw": (1, 16),
71
+ }
72
+ for field_name, (minimum, maximum) in ranges.items():
73
+ value = getattr(self, field_name)
74
+ if value < minimum or (maximum is not None and value > maximum):
75
+ upper = f"..{maximum}" if maximum is not None else " or greater"
76
+ raise CANConfigurationError(
77
+ f"{field_name} must be in range {minimum}{upper}"
78
+ )
79
+ if self.nom_sjw > self.nom_tseg2:
80
+ raise CANConfigurationError("nom_sjw cannot exceed nom_tseg2")
81
+ if self.data_sjw > self.data_tseg2:
82
+ raise CANConfigurationError("data_sjw cannot exceed data_tseg2")
83
+
84
+ if self.fd:
85
+ clock_hz = self.fd_clock_mhz * 1_000_000
86
+ nominal = clock_hz / (
87
+ self.nom_brp * (1 + self.nom_tseg1 + self.nom_tseg2)
88
+ )
89
+ data = clock_hz / (
90
+ self.data_brp * (1 + self.data_tseg1 + self.data_tseg2)
91
+ )
92
+ if nominal != self.bitrate:
93
+ raise CANConfigurationError(
94
+ "FD nominal timing resolves to "
95
+ f"{nominal:g} bit/s, not configured bitrate {self.bitrate}"
96
+ )
97
+ if data != self.data_bitrate:
98
+ raise CANConfigurationError(
99
+ "FD data timing resolves to "
100
+ f"{data:g} bit/s, not configured data_bitrate {self.data_bitrate}"
101
+ )
102
+
103
+
104
+ class PCANInterface(CANInterfaceBase):
105
+ """Full-duplex interface for PEAK PCAN hardware."""
106
+
107
+ config: PCANInterfaceConfig
108
+
109
+ def __init__(self, config: PCANInterfaceConfig, **kwargs: Any) -> None:
110
+ super().__init__(config, **kwargs)
111
+ self._can_module: ModuleType | None = None
112
+ self._bus: Any | None = None
113
+ self._dll_directory_handle: Any | None = None
114
+
115
+ @property
116
+ def bundled_dll_path(self) -> Path:
117
+ """Return the optional DLL path expected by legacy deployments.
118
+
119
+ The public reproducibility package intentionally does not redistribute
120
+ PEAK-System's third-party binary.
121
+ """
122
+
123
+ return Path(__file__).resolve().parent / "native" / "x64" / "PCANBasic.dll"
124
+
125
+ def status(self) -> int:
126
+ """Return the raw PCAN bus status code."""
127
+
128
+ self._require_connected("status")
129
+ status_method = getattr(self._bus, "status", None)
130
+ if status_method is None:
131
+ raise CANStateError("the active backend does not expose PCAN status")
132
+ return int(status_method())
133
+
134
+ def status_string(self) -> str | None:
135
+ """Return the PCAN status description when available."""
136
+
137
+ self._require_connected("status_string")
138
+ method = getattr(self._bus, "status_string", None)
139
+ return None if method is None else method()
140
+
141
+ def flash(self, enabled: bool) -> None:
142
+ """Enable or disable the identification LED on the PCAN adapter."""
143
+
144
+ self._require_connected("flash")
145
+ method = getattr(self._bus, "flash", None)
146
+ if method is None:
147
+ raise CANStateError("the active backend does not support device flashing")
148
+ method(enabled)
149
+
150
+ def _open_hardware(self) -> None:
151
+ self._prepare_windows_dll_search()
152
+ try:
153
+ can_module = importlib.import_module("can")
154
+ except ImportError as exc:
155
+ self._release_dll_directory()
156
+ raise CANDependencyError(
157
+ "python-can is not installed; run `python -m pip install -e .`"
158
+ ) from exc
159
+
160
+ kwargs: dict[str, Any] = {
161
+ "interface": "pcan",
162
+ "channel": self.config.channel,
163
+ "state": (
164
+ can_module.BusState.PASSIVE
165
+ if self.config.listen_only
166
+ else can_module.BusState.ACTIVE
167
+ ),
168
+ "receive_own_messages": self.config.receive_own_messages,
169
+ "auto_reset": self.config.auto_reset,
170
+ }
171
+ if self.config.device_id is not None:
172
+ kwargs["device_id"] = self.config.device_id
173
+
174
+ if self.config.fd:
175
+ kwargs.update(
176
+ fd=True,
177
+ f_clock_mhz=self.config.fd_clock_mhz,
178
+ nom_brp=self.config.nom_brp,
179
+ nom_tseg1=self.config.nom_tseg1,
180
+ nom_tseg2=self.config.nom_tseg2,
181
+ nom_sjw=self.config.nom_sjw,
182
+ data_brp=self.config.data_brp,
183
+ data_tseg1=self.config.data_tseg1,
184
+ data_tseg2=self.config.data_tseg2,
185
+ data_sjw=self.config.data_sjw,
186
+ )
187
+ else:
188
+ kwargs.update(fd=False, bitrate=self.config.bitrate)
189
+
190
+ try:
191
+ bus = can_module.Bus(**kwargs)
192
+ except Exception as exc:
193
+ self._release_dll_directory()
194
+ raise CANConnectionError(f"PCAN initialization failed: {exc}") from exc
195
+ self._can_module = can_module
196
+ self._bus = bus
197
+
198
+ def _close_hardware(self) -> None:
199
+ bus, self._bus = self._bus, None
200
+ self._can_module = None
201
+ try:
202
+ if bus is not None:
203
+ bus.shutdown()
204
+ except Exception as exc:
205
+ raise CANDisconnectionError(f"PCAN shutdown failed: {exc}") from exc
206
+ finally:
207
+ self._release_dll_directory()
208
+
209
+ def _receive_batch_from_hardware(
210
+ self, *, timeout: float, max_frames: int
211
+ ) -> list[CANFrame]:
212
+ bus = self._bus
213
+ if bus is None:
214
+ raise CANReceiveError("PCAN bus is not initialized")
215
+ try:
216
+ first = bus.recv(timeout)
217
+ if first is None:
218
+ return []
219
+ messages = [first]
220
+ for _ in range(max_frames - 1):
221
+ message = bus.recv(0.0)
222
+ if message is None:
223
+ break
224
+ messages.append(message)
225
+ except Exception as exc:
226
+ raise CANReceiveError(f"PCAN receive failed: {exc}") from exc
227
+ return [self._from_python_can(message) for message in messages]
228
+
229
+ def _write_frame_to_hardware(self, frame: CANFrame) -> None:
230
+ bus = self._bus
231
+ can_module = self._can_module
232
+ if bus is None or can_module is None:
233
+ raise CANTransmissionError("PCAN bus is not initialized")
234
+ try:
235
+ message = can_module.Message(
236
+ arbitration_id=frame.arbitration_id,
237
+ data=frame.data,
238
+ is_extended_id=frame.is_extended_id,
239
+ is_fd=frame.is_fd,
240
+ bitrate_switch=frame.bitrate_switch,
241
+ error_state_indicator=frame.error_state_indicator,
242
+ is_remote_frame=frame.is_remote_frame,
243
+ is_error_frame=frame.is_error_frame,
244
+ check=True,
245
+ )
246
+ bus.send(message, timeout=self.config.send_timeout)
247
+ except Exception as exc:
248
+ raise CANTransmissionError(
249
+ f"PCAN send failed for 0x{frame.arbitration_id:X}: {exc}"
250
+ ) from exc
251
+
252
+ @staticmethod
253
+ def _from_python_can(message: Any) -> CANFrame:
254
+ return CANFrame(
255
+ arbitration_id=int(message.arbitration_id),
256
+ data=bytes(message.data),
257
+ timestamp=float(message.timestamp),
258
+ is_extended_id=bool(message.is_extended_id),
259
+ is_fd=bool(message.is_fd),
260
+ bitrate_switch=bool(message.bitrate_switch),
261
+ error_state_indicator=bool(message.error_state_indicator),
262
+ is_remote_frame=bool(message.is_remote_frame),
263
+ is_error_frame=bool(message.is_error_frame),
264
+ )
265
+
266
+ def _prepare_windows_dll_search(self) -> None:
267
+ if os.name != "nt":
268
+ return
269
+ dll_path = self.config.dll_path
270
+ if dll_path is None and self.config.use_bundled_dll:
271
+ dll_path = self.bundled_dll_path
272
+ if dll_path is None:
273
+ return
274
+
275
+ dll_path = Path(dll_path).resolve()
276
+ if not dll_path.is_file():
277
+ raise CANDependencyError(f"PCANBasic.dll not found: {dll_path}")
278
+ if struct.calcsize("P") != 8 and dll_path.parent.name.lower() == "x64":
279
+ raise CANDependencyError(
280
+ "the bundled PCANBasic.dll is x64 but the Python process is 32-bit"
281
+ )
282
+ try:
283
+ self._dll_directory_handle = os.add_dll_directory(str(dll_path.parent))
284
+ except OSError as exc:
285
+ raise CANDependencyError(
286
+ f"could not add PCAN DLL directory {dll_path.parent}: {exc}"
287
+ ) from exc
288
+
289
+ def _release_dll_directory(self) -> None:
290
+ handle, self._dll_directory_handle = self._dll_directory_handle, None
291
+ if handle is not None:
292
+ handle.close()
code/attack_generation/src/ivcan_attacker/can_base/types.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vendor-neutral value objects used by CAN interfaces."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from enum import Enum
8
+
9
+ from .exceptions import CANConfigurationError
10
+
11
+
12
+ class ConnectionState(str, Enum):
13
+ """Lifecycle states shared by all CAN interface implementations."""
14
+
15
+ DISCONNECTED = "disconnected"
16
+ CONNECTING = "connecting"
17
+ CONNECTED = "connected"
18
+ DISCONNECTING = "disconnecting"
19
+ ERROR = "error"
20
+
21
+
22
+ class OverflowPolicy(str, Enum):
23
+ """Behaviour when one of the bounded in-memory queues is full."""
24
+
25
+ BLOCK = "block"
26
+ DROP_OLDEST = "drop_oldest"
27
+ RAISE = "raise"
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class CANFrame:
32
+ """An immutable Classic CAN or CAN FD frame.
33
+
34
+ ``timestamp`` is receive metadata expressed in seconds. It is not used to
35
+ schedule transmission; scheduling belongs in a higher-level component.
36
+ """
37
+
38
+ arbitration_id: int
39
+ data: bytes = b""
40
+ timestamp: float | None = None
41
+ is_extended_id: bool = False
42
+ is_fd: bool = False
43
+ bitrate_switch: bool = False
44
+ error_state_indicator: bool = False
45
+ is_remote_frame: bool = False
46
+ is_error_frame: bool = False
47
+
48
+ def __post_init__(self) -> None:
49
+ if isinstance(self.data, int):
50
+ raise CANConfigurationError("frame data must be bytes or an iterable of bytes")
51
+ try:
52
+ payload = bytes(self.data)
53
+ except (TypeError, ValueError) as exc:
54
+ raise CANConfigurationError("frame data contains an invalid byte") from exc
55
+ object.__setattr__(self, "data", payload)
56
+
57
+ maximum_id = 0x1FFFFFFF if self.is_extended_id else 0x7FF
58
+ if not 0 <= self.arbitration_id <= maximum_id:
59
+ id_kind = "29-bit" if self.is_extended_id else "11-bit"
60
+ raise CANConfigurationError(
61
+ f"arbitration_id must fit in a {id_kind} CAN identifier"
62
+ )
63
+
64
+ maximum_length = 64 if self.is_fd else 8
65
+ if len(payload) > maximum_length:
66
+ frame_kind = "CAN FD" if self.is_fd else "Classic CAN"
67
+ raise CANConfigurationError(
68
+ f"{frame_kind} payload cannot exceed {maximum_length} bytes"
69
+ )
70
+ if self.is_remote_frame and payload:
71
+ raise CANConfigurationError("remote frames cannot carry payload bytes")
72
+ if self.is_fd and self.is_remote_frame:
73
+ raise CANConfigurationError("CAN FD does not support remote frames")
74
+ if not self.is_fd and (self.bitrate_switch or self.error_state_indicator):
75
+ raise CANConfigurationError("BRS and ESI flags require a CAN FD frame")
76
+ if self.timestamp is not None and (
77
+ not math.isfinite(self.timestamp) or self.timestamp < 0
78
+ ):
79
+ raise CANConfigurationError("timestamp must be a finite non-negative value")
80
+
81
+ @property
82
+ def dlc(self) -> int:
83
+ """Return the payload length represented by this value object."""
84
+
85
+ return len(self.data)
86
+
87
+
88
+ @dataclass(frozen=True, slots=True)
89
+ class CANInterfaceConfig:
90
+ """Concurrency and bus settings understood by the base class."""
91
+
92
+ channel: str | int = "PCAN_USBBUS1"
93
+ bitrate: int = 500_000
94
+ fd: bool = False
95
+ rx_queue_size: int = 8192
96
+ tx_queue_size: int = 2048
97
+ rx_batch_size: int = 256
98
+ tx_batch_size: int = 64
99
+ receive_timeout: float = 0.05
100
+ send_timeout: float | None = 0.1
101
+ worker_join_timeout: float = 2.0
102
+ rx_overflow_policy: OverflowPolicy = OverflowPolicy.DROP_OLDEST
103
+ tx_overflow_policy: OverflowPolicy = OverflowPolicy.BLOCK
104
+ thread_name_prefix: str = "can-interface"
105
+
106
+ def __post_init__(self) -> None:
107
+ if isinstance(self.channel, str):
108
+ if not self.channel.strip():
109
+ raise CANConfigurationError("channel cannot be empty")
110
+ elif not isinstance(self.channel, int) or self.channel < 0:
111
+ raise CANConfigurationError("channel must be a non-empty string or integer")
112
+ if self.bitrate <= 0:
113
+ raise CANConfigurationError("bitrate must be positive")
114
+
115
+ for field_name in (
116
+ "rx_queue_size",
117
+ "tx_queue_size",
118
+ "rx_batch_size",
119
+ "tx_batch_size",
120
+ ):
121
+ if getattr(self, field_name) <= 0:
122
+ raise CANConfigurationError(f"{field_name} must be positive")
123
+ if self.receive_timeout <= 0:
124
+ raise CANConfigurationError("receive_timeout must be positive")
125
+ if self.send_timeout is not None and self.send_timeout <= 0:
126
+ raise CANConfigurationError("send_timeout must be positive or None")
127
+ if self.worker_join_timeout <= 0:
128
+ raise CANConfigurationError("worker_join_timeout must be positive")
129
+ if not self.thread_name_prefix.strip():
130
+ raise CANConfigurationError("thread_name_prefix cannot be empty")
131
+
132
+ for field_name in ("rx_overflow_policy", "tx_overflow_policy"):
133
+ value = getattr(self, field_name)
134
+ if not isinstance(value, OverflowPolicy):
135
+ try:
136
+ object.__setattr__(self, field_name, OverflowPolicy(value))
137
+ except ValueError as exc:
138
+ raise CANConfigurationError(
139
+ f"unsupported {field_name}: {value!r}"
140
+ ) from exc
141
+
142
+
143
+ @dataclass(frozen=True, slots=True)
144
+ class CANStatistics:
145
+ """Atomic snapshot of interface counters."""
146
+
147
+ rx_received: int = 0
148
+ rx_delivered: int = 0
149
+ rx_dropped: int = 0
150
+ tx_queued: int = 0
151
+ tx_sent: int = 0
152
+ tx_failed: int = 0
153
+ tx_dropped: int = 0
code/attack_generation/src/ivcan_attacker/cli.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Safety-oriented CLI for reproducing IV-CAN attack configurations.
3
+
4
+ Example:
5
+ ivcan-attack --type DoS --id-option zeroId \
6
+ --dlc-option dlcChange --frame-format standardId \
7
+ --data-option FFData --duration 10
8
+
9
+ The default mode only validates and previews a request. Hardware transmission
10
+ requires both ``--execute`` and ``--acknowledge-bench-only``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import logging
18
+ from pathlib import Path
19
+
20
+ from .attack_runtime import (
21
+ AttackRequest,
22
+ AttackRunner,
23
+ parse_can_id,
24
+ parse_payload,
25
+ )
26
+ from .can_base import PCANInterface, PCANInterfaceConfig
27
+ from .attack_types import (
28
+ AttackBaseType,
29
+ AttackType,
30
+ DoSConfig,
31
+ DoSOptionDLC,
32
+ DoSOptionData,
33
+ DoSOptionExt,
34
+ DoSOptionId,
35
+ FuzzConfig,
36
+ FuzzOptionDLC,
37
+ FuzzOptionId,
38
+ ReplayConfig,
39
+ ReplayOption,
40
+ SuspensionConfig,
41
+ )
42
+
43
+
44
+ def _attack_kind(value: str) -> AttackBaseType:
45
+ aliases = {
46
+ "dos": AttackBaseType.DOS,
47
+ "fuzz": AttackBaseType.FUZZ,
48
+ "fuzzing": AttackBaseType.FUZZ,
49
+ "replay": AttackBaseType.REPLAY,
50
+ "spoofing": AttackBaseType.SPOOFING,
51
+ "suspension": AttackBaseType.SUSPENSION,
52
+ "masquerade": AttackBaseType.MASQUERADE,
53
+ }
54
+ try:
55
+ return aliases[value.strip().lower()]
56
+ except KeyError as exc:
57
+ options = ", ".join(kind.value for kind in AttackBaseType)
58
+ raise argparse.ArgumentTypeError(
59
+ f"unknown attack type {value!r}; choose from {options}"
60
+ ) from exc
61
+
62
+
63
+ def build_parser() -> argparse.ArgumentParser:
64
+ parser = argparse.ArgumentParser(
65
+ description=(
66
+ "Validate and preview IV-CAN attack configurations. Hardware execution "
67
+ "is restricted to explicitly acknowledged isolated test benches."
68
+ ),
69
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
70
+ )
71
+ parser.add_argument("--type", required=True, type=_attack_kind, dest="attack_kind")
72
+
73
+ runtime = parser.add_argument_group("runtime")
74
+ runtime.add_argument(
75
+ "--duration",
76
+ type=float,
77
+ default=10.0,
78
+ help="generated attack duration in seconds",
79
+ )
80
+ runtime.add_argument(
81
+ "--interval",
82
+ type=float,
83
+ default=0.01,
84
+ help="interval between generated frames",
85
+ )
86
+ runtime.add_argument("--seed", type=int, help="deterministic random seed")
87
+ runtime.add_argument(
88
+ "--execute",
89
+ action="store_true",
90
+ help="transmit on CAN hardware instead of the default dry-run preview",
91
+ )
92
+ runtime.add_argument(
93
+ "--acknowledge-bench-only",
94
+ action="store_true",
95
+ help="confirm execution is limited to an authorized isolated test bench",
96
+ )
97
+ runtime.add_argument(
98
+ "--preview-count",
99
+ type=int,
100
+ default=3,
101
+ help="sample frames shown in dry-run mode",
102
+ )
103
+
104
+ hardware = parser.add_argument_group("CAN hardware")
105
+ hardware.add_argument("--channel", default="PCAN_USBBUS1")
106
+ hardware.add_argument("--bitrate", type=int, default=500_000)
107
+ hardware.add_argument("--fd", action="store_true", help="use CAN FD")
108
+ hardware.add_argument("--data-bitrate", type=int, default=2_000_000)
109
+ hardware.add_argument(
110
+ "--extended-id",
111
+ action="store_true",
112
+ help="use a 29-bit ID where the attack type does not define frame format",
113
+ )
114
+
115
+ frame = parser.add_argument_group("frame values")
116
+ frame.add_argument(
117
+ "--can-id",
118
+ type=parse_can_id,
119
+ help="active/target CAN ID, decimal or 0x-prefixed",
120
+ )
121
+ frame.add_argument("--dlc", type=int, help="original or fixed payload length")
122
+ frame.add_argument("--data", type=parse_payload, help="hexadecimal payload, e.g. '11 22 FF'")
123
+
124
+ dos = parser.add_argument_group("DoS options (Table II)")
125
+ id_option_choices = sorted(
126
+ {item.value for item in DoSOptionId} | {item.value for item in FuzzOptionId}
127
+ )
128
+ dos.add_argument("--id-option", choices=id_option_choices)
129
+ dos.add_argument("--dlc-option", choices=[item.value for item in DoSOptionDLC])
130
+ dos.add_argument("--frame-format", choices=[item.value for item in DoSOptionExt])
131
+ dos.add_argument("--data-option", choices=[item.value for item in DoSOptionData])
132
+
133
+ replay = parser.add_argument_group("replay options")
134
+ replay.add_argument("--timing", choices=[item.value for item in ReplayOption])
135
+ replay.add_argument("--replay-file", type=Path, help="IV-CAN-style CSV file")
136
+ replay.add_argument(
137
+ "--replay-delay",
138
+ type=float,
139
+ default=0.0,
140
+ help="start delay for delayed replay",
141
+ )
142
+
143
+ suspension = parser.add_argument_group("suspension options")
144
+ suspension.add_argument(
145
+ "--target-ids",
146
+ nargs="+",
147
+ type=parse_can_id,
148
+ help="active CAN IDs suppressed by the MitM bridge",
149
+ )
150
+ suspension.add_argument(
151
+ "--suspension-duration",
152
+ type=int,
153
+ help="suppression interval in seconds",
154
+ )
155
+ return parser
156
+
157
+
158
+ def _required(parser: argparse.ArgumentParser, value, flag: str, attack: str):
159
+ if value is None:
160
+ parser.error(f"{attack} requires {flag}")
161
+ return value
162
+
163
+
164
+ def _build_attack_type(args: argparse.Namespace, parser: argparse.ArgumentParser) -> AttackType:
165
+ kind = args.attack_kind
166
+ if kind is AttackBaseType.DOS:
167
+ return AttackType(
168
+ kind=kind,
169
+ config=DoSConfig(
170
+ id_option=DoSOptionId(_required(parser, args.id_option, "--id-option", "DoS")),
171
+ dlc_option=DoSOptionDLC(_required(parser, args.dlc_option, "--dlc-option", "DoS")),
172
+ ext_option=DoSOptionExt(
173
+ _required(parser, args.frame_format, "--frame-format", "DoS")
174
+ ),
175
+ data_option=DoSOptionData(
176
+ _required(parser, args.data_option, "--data-option", "DoS")
177
+ ),
178
+ ),
179
+ )
180
+ if kind is AttackBaseType.FUZZ:
181
+ return AttackType(
182
+ kind=kind,
183
+ config=FuzzConfig(
184
+ id_option=FuzzOptionId(
185
+ _required(parser, args.id_option, "--id-option", "fuzzing")
186
+ ),
187
+ dlc_option=FuzzOptionDLC(
188
+ _required(parser, args.dlc_option, "--dlc-option", "fuzzing")
189
+ ),
190
+ ),
191
+ )
192
+ if kind is AttackBaseType.REPLAY:
193
+ return AttackType(
194
+ kind=kind,
195
+ config=ReplayConfig(
196
+ timing=ReplayOption(_required(parser, args.timing, "--timing", "replay")),
197
+ ),
198
+ )
199
+ if kind is AttackBaseType.SUSPENSION:
200
+ target_ids = _required(parser, args.target_ids, "--target-ids", "suspension")
201
+ duration = _required(
202
+ parser,
203
+ args.suspension_duration,
204
+ "--suspension-duration",
205
+ "suspension",
206
+ )
207
+ return AttackType(
208
+ kind=kind,
209
+ config=SuspensionConfig(
210
+ suspension_duration_sec=duration,
211
+ suspension_CAN_id_list=[f"0x{value:X}" for value in target_ids],
212
+ ),
213
+ )
214
+ return AttackType(kind=kind)
215
+
216
+
217
+ def _build_request(args: argparse.Namespace, parser: argparse.ArgumentParser) -> AttackRequest:
218
+ try:
219
+ attack_type = _build_attack_type(args, parser)
220
+ return AttackRequest(
221
+ attack_type=attack_type,
222
+ duration=args.duration,
223
+ interval=args.interval,
224
+ can_id=args.can_id,
225
+ dlc=args.dlc,
226
+ payload=args.data,
227
+ is_extended_id=args.extended_id,
228
+ is_fd=args.fd,
229
+ replay_file=args.replay_file,
230
+ replay_delay=args.replay_delay,
231
+ seed=args.seed,
232
+ )
233
+ except ValueError as exc:
234
+ parser.error(str(exc))
235
+
236
+
237
+ def _frame_dict(frame) -> dict:
238
+ return {
239
+ "can_id": f"0x{frame.arbitration_id:X}",
240
+ "dlc": frame.dlc,
241
+ "data": frame.data.hex(" ").upper(),
242
+ "is_extended_id": frame.is_extended_id,
243
+ "is_fd": frame.is_fd,
244
+ }
245
+
246
+
247
+ def main(argv: list[str] | None = None) -> int:
248
+ parser = build_parser()
249
+ args = parser.parse_args(argv)
250
+ request = _build_request(args, parser)
251
+ runner = AttackRunner()
252
+
253
+ try:
254
+ plan = runner.describe(request)
255
+ if not args.execute:
256
+ preview = runner.preview(request, count=args.preview_count)
257
+ output = {
258
+ "request": request.to_dict(),
259
+ "plan": plan,
260
+ "preview": [_frame_dict(frame) for frame in preview],
261
+ }
262
+ print(json.dumps(output, indent=2))
263
+ return 0
264
+
265
+ if not args.acknowledge_bench_only:
266
+ parser.error("--execute requires --acknowledge-bench-only")
267
+
268
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
269
+ logging.info("attack plan: %s", plan)
270
+ config = PCANInterfaceConfig(
271
+ channel=args.channel,
272
+ bitrate=args.bitrate,
273
+ fd=args.fd,
274
+ data_bitrate=args.data_bitrate,
275
+ )
276
+ with PCANInterface(config) as interface:
277
+ transmitted = runner.execute(request, interface)
278
+ logging.info("attack completed: transmitted=%d", transmitted)
279
+ return 0
280
+ except (ValueError, NotImplementedError) as exc:
281
+ parser.error(str(exc))
282
+
283
+
284
+ if __name__ == "__main__":
285
+ raise SystemExit(main())
code/attack_generation/tests/test_cli.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import io
5
+ import json
6
+ import sys
7
+ import unittest
8
+ from pathlib import Path
9
+
10
+ sys.path.insert(0, str(Path(__file__).parents[1] / "src"))
11
+
12
+ from ivcan_attacker.cli import main
13
+
14
+
15
+ class CLITests(unittest.TestCase):
16
+ def test_dos_defaults_to_preview(self) -> None:
17
+ output = io.StringIO()
18
+ with contextlib.redirect_stdout(output):
19
+ result = main(
20
+ [
21
+ "--type",
22
+ "DoS",
23
+ "--id-option",
24
+ "zeroId",
25
+ "--dlc-option",
26
+ "dlcChange",
27
+ "--frame-format",
28
+ "standardId",
29
+ "--data-option",
30
+ "FFData",
31
+ "--seed",
32
+ "7",
33
+ ]
34
+ )
35
+ self.assertEqual(result, 0)
36
+ payload = json.loads(output.getvalue())
37
+ self.assertEqual(payload["request"]["attack_type"]["kind"], "DoS")
38
+ self.assertEqual(len(payload["preview"]), 3)
39
+
40
+ def test_synthetic_replay_preview(self) -> None:
41
+ replay = Path(__file__).parents[1] / "examples" / "synthetic_replay.csv"
42
+ output = io.StringIO()
43
+ with contextlib.redirect_stdout(output):
44
+ result = main(
45
+ [
46
+ "--type",
47
+ "replay",
48
+ "--timing",
49
+ "immediate",
50
+ "--replay-file",
51
+ str(replay),
52
+ ]
53
+ )
54
+ self.assertEqual(result, 0)
55
+ self.assertEqual(len(json.loads(output.getvalue())["preview"]), 3)
56
+
57
+
58
+ if __name__ == "__main__":
59
+ unittest.main()
schema/frame.schema.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ $schema: "https://json-schema.org/draft/2020-12/schema"
2
+ $id: "https://huggingface.co/datasets/IV-CAN/IV-CAN-v1/raw/main/schema/frame.schema.yaml"
3
+ title: IV-CAN-v1 frame row
4
+ description: Logical row schema after parsing the CSV representation.
5
+ type: object
6
+ additionalProperties: false
7
+ required: [timestamp, can_id, is_extended_id, dlc, data, RX_or_TX, type, is_fd, domain, is_attack, traced_from, uuid, is_traced_attack]
8
+ properties:
9
+ timestamp:
10
+ type: number
11
+ minimum: 0
12
+ description: Unix epoch seconds on the UTC time scale; source timezone Asia/Shanghai.
13
+ can_id:
14
+ type: string
15
+ pattern: '^0x(?:[0-9A-F]{4}|[0-9A-F]{8})$'
16
+ is_extended_id: {type: boolean}
17
+ dlc:
18
+ type: integer
19
+ enum: [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64]
20
+ description: Actual payload byte count, not an encoded DLC nibble.
21
+ data:
22
+ type: string
23
+ pattern: '^(?:[0-9A-F]{2}(?: [0-9A-F]{2})*)?$'
24
+ RX_or_TX:
25
+ enum: [RX, TX]
26
+ description: Direction relative to the recording channel.
27
+ type:
28
+ enum: [DT, FB, BI]
29
+ description: PEAK TRC frame type (data; FD+BRS; FD+BRS+ESI). DT may be classic or FD; use is_fd.
30
+ is_fd: {type: boolean}
31
+ domain: {type: integer, minimum: 1, maximum: 5}
32
+ is_attack: {type: boolean}
33
+ traced_from:
34
+ type: array
35
+ uniqueItems: true
36
+ items: {type: integer, minimum: 1}
37
+ description: Direct parent UUIDs in the same case only.
38
+ uuid: {type: integer, minimum: 1}
39
+ is_traced_attack: {type: boolean}
40
+ x-cross-field-constraints:
41
+ - can_id width agrees with is_extended_id
42
+ - dlc equals the number of bytes in data
43
+ - FB or BI implies is_fd=true; DT permits either protocol
44
+ - classic CAN payload length is at most 8
45
+ - uuid is unique within the containing data.csv only
46
+ - traced_from references existing, non-self UUIDs in the same data.csv and forms an acyclic graph
schema/label.schema.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://huggingface.co/datasets/IV-CAN/IV-CAN-v1/raw/main/schema/label.schema.json",
4
+ "title": "IV-CAN-v1 trial label",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": ["group_name", "collection_duration_sec", "attacking_duration_sec", "attack_start_timestamp", "attack_end_timestamp", "data_collection_info", "data_attack_info"],
8
+ "properties": {
9
+ "group_name": {"type": "string", "pattern": "^(?:benign|dos|fuzzing|replay|spoofing|suspension|masquerade)_[0-9]{4}$"},
10
+ "collection_duration_sec": {"type": "number", "minimum": 0},
11
+ "attacking_duration_sec": {"type": "number", "minimum": 0},
12
+ "attack_start_timestamp": {"type": ["number", "null"], "minimum": 0},
13
+ "attack_end_timestamp": {"type": ["number", "null"], "minimum": 0},
14
+ "data_collection_info": {"$ref": "#/$defs/collection"},
15
+ "data_attack_info": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/attack"}]}
16
+ },
17
+ "$defs": {
18
+ "collection": {
19
+ "type": "object",
20
+ "additionalProperties": false,
21
+ "required": ["avg_speed", "description", "end_place", "intelligent_driving", "road_type", "start_place"],
22
+ "properties": {
23
+ "avg_speed": {"type": "number", "minimum": 0},
24
+ "description": {"type": "string"},
25
+ "end_place": {"type": "string"},
26
+ "intelligent_driving": {"type": "boolean"},
27
+ "road_type": {"enum": ["UrbanOrdinaryRoad", "RuralRoad", "InternalRoad", "UORWithLKN", "HighwayWithLKN", "Highway", "UrbanExpressway"]},
28
+ "start_place": {"type": "string"}
29
+ }
30
+ },
31
+ "attack": {
32
+ "type": "object",
33
+ "additionalProperties": false,
34
+ "required": ["attack_effect", "attack_type", "attacked_domain"],
35
+ "properties": {
36
+ "attacked_domain": {"type": "integer", "minimum": 1, "maximum": 5},
37
+ "attack_effect": {
38
+ "type": "object", "additionalProperties": false, "required": ["description", "level"],
39
+ "properties": {"description": {"type": "string"}, "level": {"enum": ["no effect", "system warning", "non-motion control compromised", "motion control compromised"]}}
40
+ },
41
+ "attack_type": {"$ref": "#/$defs/attack_type"}
42
+ }
43
+ },
44
+ "attack_type": {
45
+ "oneOf": [
46
+ {"type": "object", "additionalProperties": false, "required": ["kind", "config"], "properties": {"kind": {"const": "DoS"}, "config": {"$ref": "#/$defs/dos_config"}}},
47
+ {"type": "object", "additionalProperties": false, "required": ["kind", "config"], "properties": {"kind": {"const": "fuzzing"}, "config": {"$ref": "#/$defs/fuzz_config"}}},
48
+ {"type": "object", "additionalProperties": false, "required": ["kind", "config"], "properties": {"kind": {"const": "replay"}, "config": {"$ref": "#/$defs/replay_config"}}},
49
+ {"type": "object", "additionalProperties": false, "required": ["kind", "config"], "properties": {"kind": {"const": "suspension"}, "config": {"$ref": "#/$defs/suspension_config"}}},
50
+ {"type": "object", "additionalProperties": false, "required": ["kind", "config"], "properties": {"kind": {"enum": ["spoofing", "masquerade"]}, "config": {"type": "null"}}}
51
+ ]
52
+ },
53
+ "dos_config": {
54
+ "type": "object", "additionalProperties": false, "required": ["id_option", "dlc_option", "ext_option", "data_option"],
55
+ "properties": {"id_option": {"enum": ["aliveId", "zeroId"]}, "dlc_option": {"enum": ["dlcChange", "dlcKeep"]}, "ext_option": {"enum": ["extendedId", "standardId"]}, "data_option": {"enum": ["FFData", "randomData"]}}
56
+ },
57
+ "fuzz_config": {
58
+ "type": "object", "additionalProperties": false, "required": ["id_option", "dlc_option"],
59
+ "properties": {"id_option": {"enum": ["aliveId", "randomId"]}, "dlc_option": {"enum": ["dlcChange", "dlcKeep"]}}
60
+ },
61
+ "replay_config": {
62
+ "type": "object", "additionalProperties": false, "required": ["timing"],
63
+ "properties": {"timing": {"enum": ["delay", "immediate"]}}
64
+ },
65
+ "suspension_config": {
66
+ "type": "object", "additionalProperties": false, "required": ["suspension_CAN_id_list", "suspension_duration_sec"],
67
+ "properties": {"suspension_duration_sec": {"type": "number", "exclusiveMinimum": 0}, "suspension_CAN_id_list": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "string", "pattern": "^0x(?:[0-9A-F]{4}|[0-9A-F]{8})$"}}}
68
+ }
69
+ }
70
+ }
tools/validate_dataset.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validate IV-CAN-v1 labels and frame CSVs without loading tables into memory."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import ast
8
+ import csv
9
+ import json
10
+ import math
11
+ import re
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import Any, Iterable
15
+
16
+ try:
17
+ import yaml
18
+ except ImportError as exc: # pragma: no cover
19
+ raise SystemExit("PyYAML is required: python -m pip install PyYAML") from exc
20
+
21
+
22
+ COLUMNS = [
23
+ "timestamp", "can_id", "is_extended_id", "dlc", "data", "RX_or_TX",
24
+ "type", "is_fd", "domain", "is_attack", "traced_from", "uuid",
25
+ "is_traced_attack",
26
+ ]
27
+ BOOL = {"True": True, "False": False}
28
+ CAN_ID = re.compile(r"^0x(?:[0-9A-F]{4}|[0-9A-F]{8})$")
29
+ BYTE_STRING = re.compile(r"^(?:[0-9A-F]{2}(?: [0-9A-F]{2})*)?$")
30
+ CLASSIC_LENGTHS = set(range(9))
31
+ FD_LENGTHS = CLASSIC_LENGTHS | {12, 16, 20, 24, 32, 48, 64}
32
+ ROAD_TYPES = {
33
+ "UrbanOrdinaryRoad", "RuralRoad", "InternalRoad", "UORWithLKN",
34
+ "HighwayWithLKN", "Highway", "UrbanExpressway",
35
+ }
36
+ ATTACK_TYPES = {"DoS", "fuzzing", "replay", "spoofing", "suspension", "masquerade"}
37
+ EFFECT_LEVELS = {
38
+ "no effect", "system warning", "non-motion control compromised",
39
+ "motion control compromised",
40
+ }
41
+
42
+
43
+ class Problems:
44
+ def __init__(self) -> None:
45
+ self.items: list[str] = []
46
+
47
+ def add(self, path: Path, message: str, row: int | None = None) -> None:
48
+ where = f"{path}:{row}" if row is not None else str(path)
49
+ self.items.append(f"{where}: {message}")
50
+
51
+
52
+ def require_keys(value: Any, keys: set[str], path: Path, problems: Problems, context: str) -> bool:
53
+ if not isinstance(value, dict):
54
+ problems.add(path, f"{context} must be a mapping")
55
+ return False
56
+ missing = keys - value.keys()
57
+ extra = value.keys() - keys
58
+ if missing:
59
+ problems.add(path, f"{context} missing keys: {sorted(missing)}")
60
+ if extra:
61
+ problems.add(path, f"{context} has unknown keys: {sorted(extra)}")
62
+ return not missing
63
+
64
+
65
+ def validate_label(path: Path, problems: Problems) -> None:
66
+ try:
67
+ value = yaml.safe_load(path.read_text(encoding="utf-8"))
68
+ except Exception as exc:
69
+ problems.add(path, f"cannot parse YAML: {exc}")
70
+ return
71
+
72
+ top = {
73
+ "attack_end_timestamp", "attack_start_timestamp", "attacking_duration_sec",
74
+ "collection_duration_sec", "data_attack_info", "data_collection_info", "group_name",
75
+ }
76
+ if not require_keys(value, top, path, problems, "label"):
77
+ return
78
+ if value["group_name"] != path.parent.name:
79
+ problems.add(path, "group_name must equal the containing case directory")
80
+ for key in ("collection_duration_sec", "attacking_duration_sec"):
81
+ number = value[key]
82
+ if not isinstance(number, (int, float)) or isinstance(number, bool) or number < 0:
83
+ problems.add(path, f"{key} must be a non-negative number")
84
+ for key in ("attack_start_timestamp", "attack_end_timestamp"):
85
+ number = value[key]
86
+ if number is not None and (not isinstance(number, (int, float)) or isinstance(number, bool) or number < 0):
87
+ problems.add(path, f"{key} must be null or a non-negative number")
88
+
89
+ collection = value["data_collection_info"]
90
+ collection_keys = {"avg_speed", "description", "end_place", "intelligent_driving", "road_type", "start_place"}
91
+ if require_keys(collection, collection_keys, path, problems, "data_collection_info"):
92
+ if collection["road_type"] not in ROAD_TYPES:
93
+ problems.add(path, f"unknown road_type: {collection['road_type']!r}")
94
+ if not isinstance(collection["intelligent_driving"], bool):
95
+ problems.add(path, "intelligent_driving must be boolean")
96
+
97
+ attack = value["data_attack_info"]
98
+ if attack is None:
99
+ if not str(value["group_name"]).startswith("benign_"):
100
+ problems.add(path, "only benign cases may have data_attack_info: null")
101
+ return
102
+ if not require_keys(attack, {"attack_effect", "attack_type", "attacked_domain"}, path, problems, "data_attack_info"):
103
+ return
104
+ domain = attack["attacked_domain"]
105
+ if not isinstance(domain, int) or isinstance(domain, bool) or not 1 <= domain <= 5:
106
+ problems.add(path, "attacked_domain must be an integer from 1 through 5")
107
+ effect = attack["attack_effect"]
108
+ if require_keys(effect, {"description", "level"}, path, problems, "attack_effect") and effect["level"] not in EFFECT_LEVELS:
109
+ problems.add(path, f"unknown attack effect level: {effect['level']!r}")
110
+ attack_type = attack["attack_type"]
111
+ if not require_keys(attack_type, {"kind", "config"}, path, problems, "attack_type"):
112
+ return
113
+ kind, config = attack_type["kind"], attack_type["config"]
114
+ if kind not in ATTACK_TYPES:
115
+ problems.add(path, f"unknown attack kind: {kind!r}")
116
+ return
117
+ expected_prefix = "dos" if kind == "DoS" else kind
118
+ if not str(value["group_name"]).startswith(expected_prefix + "_"):
119
+ problems.add(path, "attack kind does not agree with group_name")
120
+ validate_attack_config(kind, config, path, problems)
121
+
122
+
123
+ def validate_attack_config(kind: str, config: Any, path: Path, problems: Problems) -> None:
124
+ if kind in {"spoofing", "masquerade"}:
125
+ if config is not None:
126
+ problems.add(path, f"{kind} config must be null")
127
+ return
128
+ if not isinstance(config, dict):
129
+ problems.add(path, f"{kind} config must be a mapping")
130
+ return
131
+ enums: dict[str, dict[str, set[str]]] = {
132
+ "DoS": {"id_option": {"aliveId", "zeroId"}, "dlc_option": {"dlcChange", "dlcKeep"}, "ext_option": {"extendedId", "standardId"}, "data_option": {"FFData", "randomData"}},
133
+ "fuzzing": {"id_option": {"aliveId", "randomId"}, "dlc_option": {"dlcChange", "dlcKeep"}},
134
+ "replay": {"timing": {"delay", "immediate"}},
135
+ }
136
+ if kind in enums:
137
+ if not require_keys(config, set(enums[kind]), path, problems, f"{kind} config"):
138
+ return
139
+ for key, allowed in enums[kind].items():
140
+ if config[key] not in allowed:
141
+ problems.add(path, f"invalid {kind} {key}: {config[key]!r}")
142
+ return
143
+ if kind == "suspension":
144
+ if not require_keys(config, {"suspension_CAN_id_list", "suspension_duration_sec"}, path, problems, "suspension config"):
145
+ return
146
+ ids = config["suspension_CAN_id_list"]
147
+ if not isinstance(ids, list) or not ids or any(not isinstance(item, str) or not CAN_ID.fullmatch(item) for item in ids):
148
+ problems.add(path, "suspension_CAN_id_list must contain canonical CAN IDs")
149
+ duration = config["suspension_duration_sec"]
150
+ if not isinstance(duration, (int, float)) or isinstance(duration, bool) or duration <= 0:
151
+ problems.add(path, "suspension_duration_sec must be positive")
152
+
153
+
154
+ def parse_bool(raw: str) -> bool:
155
+ if raw not in BOOL:
156
+ raise ValueError("expected True or False")
157
+ return BOOL[raw]
158
+
159
+
160
+ def grow_bitset(bitset: bytearray, index: int) -> None:
161
+ if index >= len(bitset):
162
+ bitset.extend(b"\0" * (index + 1 - len(bitset)))
163
+
164
+
165
+ def validate_frame(row: dict[str, str], path: Path, line: int, seen: bytearray, graph: dict[int, list[int]], problems: Problems) -> None:
166
+ try:
167
+ timestamp = float(row["timestamp"])
168
+ if not math.isfinite(timestamp) or timestamp < 0:
169
+ raise ValueError("timestamp must be finite and non-negative")
170
+ can_id = row["can_id"]
171
+ if not CAN_ID.fullmatch(can_id):
172
+ raise ValueError("can_id is not canonical uppercase hexadecimal")
173
+ extended = parse_bool(row["is_extended_id"])
174
+ if (len(can_id) == 10) != extended:
175
+ raise ValueError("can_id width disagrees with is_extended_id")
176
+ dlc = int(row["dlc"])
177
+ payload = row["data"]
178
+ if not BYTE_STRING.fullmatch(payload):
179
+ raise ValueError("data is not canonical space-separated uppercase hex")
180
+ if len(payload.split()) != dlc:
181
+ raise ValueError("dlc does not equal payload byte count")
182
+ if row["RX_or_TX"] not in {"RX", "TX"}:
183
+ raise ValueError("RX_or_TX must be RX or TX")
184
+ frame_type = row["type"]
185
+ if frame_type not in {"DT", "FB", "BI"}:
186
+ raise ValueError("type must be DT, FB, or BI")
187
+ is_fd = parse_bool(row["is_fd"])
188
+ if frame_type in {"FB", "BI"} and not is_fd:
189
+ raise ValueError("FB or BI requires is_fd=True")
190
+ if dlc not in (FD_LENGTHS if is_fd else CLASSIC_LENGTHS):
191
+ raise ValueError("dlc is invalid for the frame protocol")
192
+ domain = int(row["domain"])
193
+ if not 1 <= domain <= 5:
194
+ raise ValueError("domain must be 1 through 5")
195
+ parse_bool(row["is_attack"])
196
+ parse_bool(row["is_traced_attack"])
197
+ uuid = int(row["uuid"])
198
+ if uuid <= 0:
199
+ raise ValueError("uuid must be positive")
200
+ grow_bitset(seen, uuid)
201
+ if seen[uuid]:
202
+ raise ValueError("duplicate case-local uuid")
203
+ seen[uuid] = 1
204
+ parents = ast.literal_eval(row["traced_from"])
205
+ if not isinstance(parents, list) or any(type(parent) is not int or parent <= 0 for parent in parents):
206
+ raise ValueError("traced_from must be a list of positive integers")
207
+ if len(parents) != len(set(parents)):
208
+ raise ValueError("traced_from contains duplicates")
209
+ if uuid in parents:
210
+ raise ValueError("traced_from contains a self-reference")
211
+ if parents:
212
+ graph[uuid] = parents
213
+ except (ValueError, SyntaxError, KeyError) as exc:
214
+ problems.add(path, str(exc), line)
215
+
216
+
217
+ def validate_graph(path: Path, graph: dict[int, list[int]], seen: bytearray, problems: Problems) -> None:
218
+ for child, parents in graph.items():
219
+ for parent in parents:
220
+ if parent >= len(seen) or not seen[parent]:
221
+ problems.add(path, f"uuid {child} traces from missing case-local uuid {parent}")
222
+ state: dict[int, int] = {}
223
+
224
+ def visit(node: int) -> bool:
225
+ if state.get(node) == 1:
226
+ return False
227
+ if state.get(node) == 2:
228
+ return True
229
+ state[node] = 1
230
+ for parent in graph.get(node, []):
231
+ if parent in graph and not visit(parent):
232
+ return False
233
+ state[node] = 2
234
+ return True
235
+
236
+ for node in graph:
237
+ if not visit(node):
238
+ problems.add(path, "traced_from graph contains a cycle")
239
+ break
240
+
241
+
242
+ def validate_csv(path: Path, max_rows: int | None, problems: Problems) -> int:
243
+ seen = bytearray(1)
244
+ graph: dict[int, list[int]] = {}
245
+ rows = 0
246
+ with path.open("r", encoding="utf-8", newline="") as handle:
247
+ reader = csv.DictReader(handle)
248
+ if reader.fieldnames != COLUMNS:
249
+ problems.add(path, f"unexpected header: {reader.fieldnames!r}", 1)
250
+ return 0
251
+ for line, row in enumerate(reader, 2):
252
+ if max_rows is not None and rows >= max_rows:
253
+ break
254
+ validate_frame(row, path, line, seen, graph, problems)
255
+ rows += 1
256
+ if max_rows is None:
257
+ validate_graph(path, graph, seen, problems)
258
+ return rows
259
+
260
+
261
+ def iter_cases(root: Path) -> Iterable[tuple[Path, Path]]:
262
+ for label in sorted((root / "data").glob("**/label.yaml")):
263
+ yield label, label.with_name("data.csv")
264
+
265
+
266
+ def main(argv: list[str] | None = None) -> int:
267
+ parser = argparse.ArgumentParser(description=__doc__)
268
+ parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
269
+ group = parser.add_mutually_exclusive_group()
270
+ group.add_argument("--max-rows", type=int, default=1000, help="rows checked per case (default: 1000)")
271
+ group.add_argument("--all", action="store_true", help="scan every row and validate trace references/cycles")
272
+ args = parser.parse_args(argv)
273
+ root = args.root.resolve()
274
+ max_rows = None if args.all else args.max_rows
275
+ if max_rows is not None and max_rows <= 0:
276
+ parser.error("--max-rows must be positive")
277
+
278
+ problems = Problems()
279
+ cases = rows = 0
280
+ for label, data in iter_cases(root):
281
+ cases += 1
282
+ validate_label(label, problems)
283
+ if not data.is_file():
284
+ problems.add(data, "missing data.csv")
285
+ else:
286
+ rows += validate_csv(data, max_rows, problems)
287
+ if not cases:
288
+ problems.add(root / "data", "no cases found")
289
+ if problems.items:
290
+ for item in problems.items[:100]:
291
+ print(f"ERROR: {item}", file=sys.stderr)
292
+ if len(problems.items) > 100:
293
+ print(f"ERROR: {len(problems.items) - 100} additional errors omitted", file=sys.stderr)
294
+ return 1
295
+ mode = "all rows" if max_rows is None else f"up to {max_rows} rows/case"
296
+ print(f"OK: validated {cases} cases and {rows:,} frame rows ({mode})")
297
+ return 0
298
+
299
+
300
+ if __name__ == "__main__":
301
+ raise SystemExit(main())