diff --git a/scapy/contrib/automotive/j1939/__init__.py b/scapy/contrib/automotive/j1939/__init__.py new file mode 100644 index 00000000000..a614f8dbe00 --- /dev/null +++ b/scapy/contrib/automotive/j1939/__init__.py @@ -0,0 +1,132 @@ +# SPDX-License-Identifier: GPL-2.0-only +# This file is part of Scapy +# See https://scapy.net/ for more information +# Copyright (C) National Motor Freight Traffic Association Inc. +# + +# scapy.contrib.description = SAE J1939 Transport Layer Socket & Diagnostics +# scapy.contrib.status = loads + +from scapy.contrib.automotive.j1939.j1939_dm import ( + J1939Dm1, + J1939Dm13, + J1939Dm14, + J1939Dm15, + J1939Dtc, + J1939_PGN_DM1, + J1939_PGN_DM13, + J1939_PGN_DM14, + J1939_PGN_DM15, +) +from scapy.contrib.automotive.j1939.j1939_dm_scanner import ( + J1939PgnScanResult, + J1939_DM_PGNS, + J1939_PGN_VIN, + j1939_scan_dm, + j1939_scan_pgns, +) +from scapy.contrib.automotive.j1939.j1939_name import ( + J1939Name, + J1939_INDUSTRY_GROUPS, + J1939_INDUSTRY_SPECIFIC_FUNCTIONS, + J1939_INDUSTRY_SPECIFIC_VEHICLE_SYSTEMS, + J1939_MANUFACTURERS, + J1939_PRE_ASSIGNED_FUNCTIONS, + j1939_format_name_function, + j1939_format_name_industry_group, + j1939_format_name_manufacturer, + j1939_format_name_vehicle_system, +) +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939ScanResult, + J1939_ACK_CTRL_ACCESS_DENIED, + J1939_ACK_CTRL_ACK, + J1939_ACK_CTRL_CANNOT_RESPOND, + J1939_ACK_CTRL_NACK, + J1939_DEFAULT_BITRATE, + J1939_DEFAULT_BUSLOAD, + J1939_DIAGADAPTERS_ADDRESSES, + J1939_PGN_ECU_ID, + J1939_PGN_XCP, + J1939_SCAN_METHODS, + J1939_UDS_TESTER_PRESENT_REQS, + J1939_UDS_TESTER_PRESENT_RESPS, + J1939_XCP_CONNECT_REQ, + J1939_XCP_POSITIVE_RESPONSE, + J1939_XCP_SRC_ADDRS, + j1939_check_rx_filter_warning, + j1939_emit_sa_filter_warning, + j1939_get_sock, + j1939_inter_probe_delay, + j1939_reconnect_with_retry, + j1939_request_name, + j1939_request_names, + j1939_sa_filter, + j1939_scan, + j1939_scan_addr_claim, + j1939_scan_ecu_id, + j1939_scan_passive, + j1939_scan_rts_probe, + j1939_scan_uds, + j1939_scan_unicast, + j1939_scan_xcp, +) + +__all__ = [ + "J1939Dm1", + "J1939Dm13", + "J1939Dm14", + "J1939Dm15", + "J1939Dtc", + "J1939Name", + "J1939PgnScanResult", + "J1939ScanResult", + "J1939_ACK_CTRL_ACCESS_DENIED", + "J1939_ACK_CTRL_ACK", + "J1939_ACK_CTRL_CANNOT_RESPOND", + "J1939_ACK_CTRL_NACK", + "J1939_DEFAULT_BITRATE", + "J1939_DEFAULT_BUSLOAD", + "J1939_DIAGADAPTERS_ADDRESSES", + "J1939_DM_PGNS", + "J1939_INDUSTRY_GROUPS", + "J1939_INDUSTRY_SPECIFIC_FUNCTIONS", + "J1939_INDUSTRY_SPECIFIC_VEHICLE_SYSTEMS", + "J1939_MANUFACTURERS", + "J1939_PGN_DM1", + "J1939_PGN_DM13", + "J1939_PGN_DM14", + "J1939_PGN_DM15", + "J1939_PGN_ECU_ID", + "J1939_PGN_VIN", + "J1939_PGN_XCP", + "J1939_PRE_ASSIGNED_FUNCTIONS", + "J1939_SCAN_METHODS", + "J1939_UDS_TESTER_PRESENT_REQS", + "J1939_UDS_TESTER_PRESENT_RESPS", + "J1939_XCP_CONNECT_REQ", + "J1939_XCP_POSITIVE_RESPONSE", + "J1939_XCP_SRC_ADDRS", + "j1939_check_rx_filter_warning", + "j1939_emit_sa_filter_warning", + "j1939_format_name_function", + "j1939_format_name_industry_group", + "j1939_format_name_manufacturer", + "j1939_format_name_vehicle_system", + "j1939_get_sock", + "j1939_inter_probe_delay", + "j1939_reconnect_with_retry", + "j1939_request_name", + "j1939_request_names", + "j1939_sa_filter", + "j1939_scan", + "j1939_scan_addr_claim", + "j1939_scan_dm", + "j1939_scan_ecu_id", + "j1939_scan_passive", + "j1939_scan_pgns", + "j1939_scan_rts_probe", + "j1939_scan_uds", + "j1939_scan_unicast", + "j1939_scan_xcp", +] diff --git a/scapy/contrib/automotive/j1939/j1939_dm.py b/scapy/contrib/automotive/j1939/j1939_dm.py new file mode 100644 index 00000000000..5ab665566b4 --- /dev/null +++ b/scapy/contrib/automotive/j1939/j1939_dm.py @@ -0,0 +1,329 @@ +# SPDX-License-Identifier: GPL-2.0-only +# This file is part of Scapy +# See https://scapy.net/ for more information +# Copyright (C) National Motor Freight Traffic Association Inc. +# + +# scapy.contrib.description = SAE J1939 Diagnostic Messages (J1939-73) +# scapy.contrib.status = loads + +""" +J1939 Diagnostic Messages (DMs) for Scapy. + +Implements Scapy packet classes for the most common SAE J1939-73 Diagnostic +Messages: + +- ``J1939Dtc`` -- 4-byte Diagnostic Trouble Code (SPN / FMI / CM / OC) +- ``J1939Dm1`` -- Active DTCs, PGN 0xFECA (65226) +- ``J1939Dm13`` -- Stop/Start Broadcast, PGN 0xDF00 (57088) +- ``J1939Dm14`` -- Memory Access Request, PGN 0xD900 (55552) + +All J1939 payload bytes are in little-endian (LE) byte order. The +``J1939Dtc`` class uses Scapy's little-endian ``BitField`` support +(``tot_size=-4`` / ``end_tot_size=-4``) to parse and build the LE wire format +transparently. + +Usage example:: + + >>> load_contrib('automotive.j1939') + >>> from scapy.contrib.automotive.j1939.j1939_dm import ( + ... J1939Dtc, J1939Dm1, J1939Dm13, J1939Dm14, J1939_PGN_DM1 + ... ) + >>> dtc = J1939Dtc(SPN=100, FMI=2, CM=0, OC=5) + >>> dm1 = J1939Dm1(mil_status=1, dtcs=[dtc]) + >>> len(bytes(dm1)) + 6 +""" + +from typing import Tuple + +from scapy.contrib.j1939 import J1939 +from scapy.fields import ( + BitEnumField, + BitField, + ByteField, + PacketListField, + StrFixedLenField, + XLEIntField, + XShortField, +) +from scapy.packet import Packet, bind_layers + + +# --------------------------------------------------------------------------- +# PGN constants for Diagnostic Messages (J1939-73) +# --------------------------------------------------------------------------- + +#: PGN for DM1 Active Diagnostic Trouble Codes +J1939_PGN_DM1 = 0xFECA # 65226 + +#: PGN for DM13 Stop/Start Broadcast Command +J1939_PGN_DM13 = 0xDF00 # 57088 + +#: PGN for DM14 Memory Access Request +J1939_PGN_DM14 = 0xD900 # 55552 + +#: PGN for DM15 Memory Access Response +J1939_PGN_DM15 = 0xD800 # 55296 + +# Lamp status encoding (2-bit values per lamp) +_J1939_LAMP_STATUS = { + 0b00: "off", + 0b01: "on", + 0b10: "reserved", + 0b11: "not_available", +} + +# DM14 command type encoding +_J1939_DM14_COMMAND = { + 0: "erase", + 1: "read", + 2: "write", + 3: "reserved", +} + +# DM14 pointer type encoding +_J1939_DM14_POINTER_TYPE = { + 0: "direct", + 1: "indirect", + 2: "copy", + 3: "reserved", +} + +# DM15 status encoding +_J1939_DM15_STATUS = { + 0: "proceed", + 1: "busy", + 2: "complete", + 3: "operation_failed", +} + + +class J1939Dtc(Packet): + """J1939-73 Diagnostic Trouble Code (4 bytes, little-endian). + + A DTC is a 32-bit little-endian integer with the following bit layout: + + - bits 18-0: SPN (Suspect Parameter Number, 19 bits) + - bits 23-19: FMI (Failure Mode Indicator, 5 bits) + - bit 24: CM (SPN Conversion Method, 1 bit) + - bits 31-25: OC (Occurrence Count, 7 bits) + + Wire bytes (LSB first):: + + byte 0: SPN[7:0] + byte 1: SPN[15:8] + byte 2: FMI[4:0] | SPN[18:16] (bits 7-3 = FMI, bits 2-0 = SPN MSBs) + byte 3: OC[6:0] | CM (bits 7-1 = OC, bit 0 = CM) + + :param SPN: Suspect Parameter Number (0-524287) + :param FMI: Failure Mode Indicator (0-31) + :param CM: SPN Conversion Method (0-1) + :param OC: Occurrence Count (0-127) + """ + + name = "J1939Dtc" + + fields_desc = [ + BitField("OC", 0, 7, tot_size=-4), # bits 31-25 (MSB side) + BitField("CM", 0, 1), # bit 24 + BitField("FMI", 0, 5), # bits 23-19 + BitField("SPN", 0, 19, end_tot_size=-4), # bits 18-0 (LSB side) + ] + + def extract_padding(self, s): + # type: (bytes) -> Tuple[bytes, bytes] + return b"", s + + +class J1939Dm1(Packet): + """DM1 Active Diagnostic Trouble Codes (PGN 0xFECA = 65226). + + Wire format: + + - Bytes 0-1: Lamp Status (4 lamps × 2 bits on/off + 4 lamps × 2 bits + flash pattern). + - Bytes 2+: Variable list of :class:`J1939Dtc` records (4 bytes each). + + Multi-packet messages (>8 bytes) are sent via the J1939-21 Transport + Protocol, handled automatically by :class:`J1939SoftSocket`. + + :param mil_status: Malfunction Indicator Lamp on/off (0=off, 1=on, 3=N/A) + :param rsl_status: Red Stop Lamp on/off + :param awl_status: Amber Warning Lamp on/off + :param pl_status: Protect Lamp on/off + :param mil_flash: MIL flash pattern + :param rsl_flash: RSL flash pattern + :param awl_flash: AWL flash pattern + :param pl_flash: PL flash pattern + :param dtcs: list of :class:`J1939Dtc` objects + """ + + name = "J1939Dm1" + + #: PGN for DM1 Active DTCs (J1939-73) + PGN = J1939_PGN_DM1 + MIN_LEN = 2 + + fields_desc = [ + # Byte 0: Lamp on/off status (bits 7-6 = MIL, 5-4 = RSL, 3-2 = AWL, 1-0 = PL) + BitEnumField("mil_status", 3, 2, _J1939_LAMP_STATUS), + BitEnumField("rsl_status", 3, 2, _J1939_LAMP_STATUS), + BitEnumField("awl_status", 3, 2, _J1939_LAMP_STATUS), + BitEnumField("pl_status", 3, 2, _J1939_LAMP_STATUS), + # Byte 1: Lamp flash patterns (same 2-bit encoding) + BitEnumField("mil_flash", 3, 2, _J1939_LAMP_STATUS), + BitEnumField("rsl_flash", 3, 2, _J1939_LAMP_STATUS), + BitEnumField("awl_flash", 3, 2, _J1939_LAMP_STATUS), + BitEnumField("pl_flash", 3, 2, _J1939_LAMP_STATUS), + PacketListField( + "dtcs", + [], + J1939Dtc, + next_cls_cb=lambda pkt, lst, cur, remain: ( + J1939Dtc if len(remain) >= 4 else None + ), + max_count=1000, + ), + ] + + +class J1939Dm13(Packet): + """DM13 Stop/Start Broadcast Command (PGN 0xDF00 = 57088). + + Broadcast to all ECUs on the bus to start or stop periodic diagnostic + broadcast. The ``hold_signal`` byte uses the J1939-73 convention: + ``0xFE`` = start broadcasting, ``0xFF`` = stop broadcasting. + + :param hold_signal: broadcast control (0xFE=start, 0xFF=stop) + :param data: remaining 7 bytes (optional override; default all 0xFF) + """ + + name = "J1939Dm13" + + #: PGN for DM13 Stop/Start Broadcast + PGN = J1939_PGN_DM13 + MIN_LEN = 8 + + fields_desc = [ + ByteField("hold_signal", 0xFF), + StrFixedLenField("data", b"\xff" * 7, 7), + ] + + +class J1939Dm14(Packet): + """DM14 Memory Access Request (PGN 0xD900 = 55552). + + Peer-to-peer request to read, write, or erase ECU memory. DM14 must + always be addressed to a specific ECU (not the global broadcast address + ``0xFF``). + + Wire format (8 bytes): + + - Byte 0: bits 7-6 = reserved (1), bits 5-4 = command, bits 3-2 = + pointer type, bits 1-0 = access level + - Bytes 1-4: memory address (32-bit LE) + - Byte 5: data length (number of bytes to read/write) + - Bytes 6-7: reserved (0xFFFF) + + :param command_type: memory operation (0=erase, 1=read, 2=write) + :param pointer_type: addressing mode (0=direct, 1=indirect, 2=copy) + :param access_level: security access level (0-3) + :param address: 32-bit LE memory address + :param length: number of bytes to access + """ + + name = "J1939Dm14" + + #: PGN for DM14 Memory Access Request + PGN = J1939_PGN_DM14 + MIN_LEN = 8 + + fields_desc = [ + # Byte 0: control fields + BitField("reserved", 0b11, 2), + BitEnumField("command_type", 1, 2, _J1939_DM14_COMMAND), + BitEnumField("pointer_type", 0, 2, _J1939_DM14_POINTER_TYPE), + BitField("access_level", 0, 2), + # Bytes 1-4: memory address (little-endian) + XLEIntField("address", 0), + # Byte 5: data length + ByteField("length", 0), + # Bytes 6-7: reserved + XShortField("reserved2", 0xFFFF), + ] + + +class J1939Dm15(Packet): + """DM15 Memory Access Response (PGN 0xD800 = 55296). + + Sent in response to a :class:`J1939Dm14` request. + + Wire format (8 bytes): + + - Byte 0: bits 7-6 = reserved (1), bits 5-4 = status, bits 3-2 = + pointer type, bits 1-0 = access level + - Bytes 1-4: memory address (32-bit LE) + - Byte 5: data length (number of bytes) + - Bytes 6-7: EDC parameter / seed (16-bit) + + :param status: response status (0=proceed, 1=busy, 2=complete, 3=failed) + :param pointer_type: addressing mode (0=direct, 1=indirect, 2=copy) + :param access_level: security access level (0-3) + :param address: 32-bit LE memory address + :param length: number of bytes + :param edc_parameter: EDC or security seed (0xFFFF if unused) + """ + + name = "J1939Dm15" + + #: PGN for DM15 Memory Access Response + PGN = J1939_PGN_DM15 + MIN_LEN = 8 + + fields_desc = [ + # Byte 0: control fields + BitField("reserved", 0b11, 2), + BitEnumField("status", 0, 2, _J1939_DM15_STATUS), + BitEnumField("pointer_type", 0, 2, _J1939_DM14_POINTER_TYPE), + BitField("access_level", 0, 2), + # Bytes 1-4: memory address (little-endian) + XLEIntField("address", 0), + # Byte 5: data length + ByteField("length", 0), + # Bytes 6-7: EDC parameter / seed + XShortField("edc_parameter", 0xFFFF), + ] + + def answers(self, other): + # type: (Packet) -> int + if not isinstance(other, Packet): + return 0 + other_dm14 = other.getlayer(J1939Dm14) + if other_dm14 is not None: + return int( + self.address == other_dm14.address + and self.length == other_dm14.length + ) + other_j = other if isinstance(other, J1939) else other.getlayer(J1939) + if other_j is not None and other_j.pgn == J1939_PGN_DM14: + return 1 + return 0 + + +bind_layers(J1939, J1939Dm1, pgn=J1939_PGN_DM1) +bind_layers(J1939, J1939Dm13, pgn=J1939_PGN_DM13) +bind_layers(J1939, J1939Dm14, pgn=J1939_PGN_DM14) +bind_layers(J1939, J1939Dm15, pgn=J1939_PGN_DM15) + +__all__ = [ + "J1939Dm1", + "J1939Dm13", + "J1939Dm14", + "J1939Dm15", + "J1939Dtc", + "J1939_PGN_DM1", + "J1939_PGN_DM13", + "J1939_PGN_DM14", + "J1939_PGN_DM15", +] diff --git a/scapy/contrib/automotive/j1939/j1939_dm_scanner.py b/scapy/contrib/automotive/j1939/j1939_dm_scanner.py new file mode 100644 index 00000000000..9ba97beceb6 --- /dev/null +++ b/scapy/contrib/automotive/j1939/j1939_dm_scanner.py @@ -0,0 +1,633 @@ +# SPDX-License-Identifier: GPL-2.0-only +# This file is part of Scapy +# See https://scapy.net/ for more information +# Copyright (C) National Motor Freight Traffic Association Inc. +# + +# scapy.contrib.description = SAE J1939 Diagnostic Message (DM) Scanner +# scapy.contrib.status = library + +""" +J1939 Diagnostic Message (DM) Scanner. + +Probes a single J1939 ECU (identified by its Destination Address) to discover +which SAE J1939-73 Diagnostic Messages it supports. For each PGN in +:data:`J1939_DM_PGNS` the scanner sends a unicast Request (PGN 59904) and +classifies the response: + +- **Positive response** — ECU replies with the requested PGN. +- **NACK** — ECU replies with an Acknowledgment (PGN 0xE800), control byte + 0x01 (Negative Acknowledgment). +- **Timeout** — ECU does not reply within *sniff_time* seconds. + +This scanner could functionally be implemented as an ``.sr1()``-based scanner, +but it has been prepared to be runtime-optimized instead. It uses raw CAN +socket filtering, asynchronous sniffing with a +transmission callback, and busload pacing. + +Usage:: + + >>> load_contrib('automotive.j1939') + >>> from scapy.contrib.cansocket import CANSocket + >>> from scapy.contrib.automotive.j1939.j1939_dm_scanner import ( + ... j1939_scan_dm, + ... ) + >>> sock = CANSocket("can0") + >>> results = j1939_scan_dm(sock, target_da=0x00) + >>> for name, res in sorted(results.items()): + ... print("{}: supported={} error={}".format( + ... name, res.supported, res.error)) +""" + +import copy +from dataclasses import dataclass +import time +from typing import ( + Any, + Callable, + Dict, + Iterable, + List, + Optional, + TYPE_CHECKING, + Type, + Union, +) + +if TYPE_CHECKING: + from threading import Event + from scapy.supersocket import SuperSocket + +from scapy.contrib.automotive.ecu import EcuState +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_ACK_CTRL_NACK, + J1939_DEFAULT_BITRATE, + J1939_DEFAULT_BUSLOAD, + j1939_emit_sa_filter_warning, + j1939_inter_probe_delay, + j1939_reconnect_with_retry, +) +from scapy.contrib.automotive.scanner.enumerator import ServiceEnumerator +from scapy.contrib.automotive.scanner.executor import AutomotiveTestCaseExecutor +from scapy.contrib.automotive.scanner.test_case import AutomotiveTestCaseABC +from scapy.contrib.j1939 import ( + J1939, + J1939Ack, + J1939Request, + J1939_GLOBAL_ADDRESS, + J1939_PGN_REQUEST, + J1939_PGN_TP_CM, + J1939_TP_CM_ABORT, + J1939_TP_CM_BAM, + J1939_TP_CM_RTS, + log_j1939, +) +from scapy.layers.can import CAN +from scapy.packet import Packet + +# --- Scanner constants + +#: PGN for Vehicle Identification Number (VIN / VI) (J1939-71) +J1939_PGN_VIN = 0xFEE4 # 65260 + +#: Default priority for request frames sent by the DM scanner +_J1939_DM_SCAN_PRIORITY = 6 + +#: Ordered mapping from DM name (str) to PGN number (int). +#: Most entries are PDU2 (PF byte >= 0xF0) broadcast-capable messages; +#: some higher DMs use PDU1 (peer-to-peer) PGNs. +J1939_DM_PGNS = { + "DM1": 0xFECA, # Active Diagnostic Trouble Codes + "DM2": 0xFECB, # Previously Active Diagnostic Trouble Codes + "DM3": 0xFECC, # Diagnostic Data Clear/Reset for Previously Active DTCs + "DM4": 0xFECD, # Freeze Frame Parameters + "DM5": 0xFECE, # Diagnostic Readiness 1 + "DM6": 0xFECF, # Emission-Related Pending DTCs + "DM7": 0xE300, # Command Noncontinuously Monitored Test + "DM8": 0xFED0, # Test Results for Noncontinuously Monitored Systems + "DM9": 0xFED1, # Oxygen Sensor Test Results + "DM10": 0xFED2, # Non-continuously Monitored Systems Test Identifiers Support + "DM11": 0xFED3, # Diagnostic Data Clear/Reset for Active DTCs + "DM12": 0xFED4, # Emission-Related Active DTCs + "DM13": 0xDF00, # Stop Start Broadcast + "DM14": 0xD900, # Memory Access Request + "DM15": 0xD800, # Memory Access Response + "DM16": 0xD700, # Binary Data Transfer + "DM17": 0xD600, # Boot Load Data + "DM18": 0xD400, # Data Security + "DM19": 0xD300, # Calibration Information + "DM20": 0xC200, # Monitor Performance Ratio + "DM21": 0xC100, # Diagnostic Readiness 2 + "DM22": 0xC300, # Individual Clear/Reset of Active and Previously Active DTC + "DM23": 0xFDB5, # Emission-Related Previously Active DTCs + "DM24": 0xFDB6, # SPN Support + "DM25": 0xFDB7, # Expanded Freeze Frame + "DM26": 0xFDB8, # Diagnostic Readiness 3 + "DM27": 0xFD82, # All Pending DTCs + "DM28": 0xFD80, # Permanent DTCs + "DM29": 0x9E00, # Regulated DTC Counts (Pending, Permanent, MIL-On, PMIL-On) + "DM30": 0xA400, # Scaled Test Results + "DM31": 0xA300, # DTC to Lamp Association + "DM32": 0xA200, # Regulated Exhaust Emission Level Exceedance + "DM33": 0xA100, # Emission Increasing Auxiliary Emission Control Device Active Time + "DM34": 0xA000, # NTE Status + "DM35": 0x9F00, # Immediate Fault Status + "DM36": 0xFD64, # Harmonized Roadworthiness - Vehicle (HRWV) + "DM37": 0xFD63, # Harmonized Roadworthiness - System (HRWS) + "DM38": 0xFD62, # Harmonized Global Regulation Description (HGRD) + "DM39": 0xFD61, # Harmonized Cumulative Continuous Malfunction Indicator - System + "DM40": 0xFD60, # Harmonized B1 Failure Counts (HB1C) + "DM41": 0xFD5F, # DTCs - A, Pending + "DM42": 0xFD5E, # DTCs - A, Confirmed and Active + "DM43": 0xFD5D, # DTCs - A, Previously Active + "DM44": 0xFD5C, # DTCs - B1, Pending + "DM45": 0xFD5B, # DTCs - B1, Confirmed and Active + "DM46": 0xFD5A, # DTCs - B1, Previously Active + "DM47": 0xFD59, # DTCs - B2, Pending + "DM48": 0xFD58, # DTCs - B2, Confirmed and Active + "DM49": 0xFD57, # DTCs - B2, Previously Active + "DM50": 0xFD56, # DTCs - C, Pending + "DM51": 0xFD55, # DTCs - C, Confirmed and Active + "DM52": 0xFD54, # DTCs - C, Previously Active + "DM53": 0xFCD1, # Active Service Only DTCs + "DM54": 0xFCD2, # Previously Active Service Only DTCs + "DM55": 0xFCD3, # Diagnostic Data Clear/Reset for All Service Only DTCs + "DM56": 0xFCC7, # Engine Emissions Certification Information + "DM57": 0xFCC6, # OBD Information +} + + +# --- Result containers + + +@dataclass +class J1939PgnScanResult: + """Result record for a single PGN probe sent by :func:`j1939_scan_pgns`. + + :param pgn: PGN number that was requested + :param supported: ``True`` if the ECU replied with the requested PGN + :param name: human-readable name for the PGN + :param packet: the first CAN response received (``None`` on timeout) + :param error: ``None`` when supported; ``"NACK"`` for negative ack; + ``"Timeout"`` when no reply; ``"Aborted"`` if stopped early + """ + + pgn: int + supported: bool + name: str = "Unknown" + packet: Optional[CAN] = None + error: Optional[str] = None + + +class J1939_PGN_Enumerator(ServiceEnumerator): + """Enumerator for J1939 Parameter Group Numbers (PGNs).""" + + _supported_kwargs = copy.copy(ServiceEnumerator._supported_kwargs) + _supported_kwargs.update({ + "bitrate": (int, None), + "busload": (None, None), + "pgns": (None, None), + "reconnect_handler": (None, None), + "reconnect_retries": (int, None), + "reset_handler": (None, None), + "retry_delay": (None, None), + "sniff_time": (None, None), + "src_addr": (int, None), + "stop_event": (None, None), + "target_da": (int, None), + }) + + def __init__(self): + # type: () -> None + super(J1939_PGN_Enumerator, self).__init__() + self.pgn_results = {} # type: Dict[Any, J1939PgnScanResult] + + @staticmethod + def _get_negative_response_code(resp): + # type: (Packet) -> int + ack = resp.getlayer(J1939Ack) if resp is not None else None + if ack is not None: + return ack.ctrl + return getattr(resp, "negativeResponseCode", 0) + + @staticmethod + def _get_negative_response_desc(nrc): + # type: (int) -> str + if nrc == J1939_ACK_CTRL_NACK: + return "NACK" + return str(nrc) + + @staticmethod + def _get_negative_response_label(response): + # type: (Packet) -> str + return "NACK" + + def _get_initial_requests(self, **kwargs): + # type: (Any) -> Iterable[Packet] + pgns = kwargs.get("pgns", []) + target_da = kwargs.get("target_da", 0x00) + src_addr = kwargs.get("src_addr", 0xF9) + if isinstance(pgns, dict): + items = list(pgns.items()) + else: + items = [(pgn, pgn) for pgn in pgns] + + for _, pgn in items: + yield J1939( + pgn=J1939_PGN_REQUEST, + dst=target_da, + src=src_addr, + priority=_J1939_DM_SCAN_PRIORITY, + ) / J1939Request( + req_pgn=pgn, + ) + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + target_da = kwargs.get("target_da", 0x00) + pgns = kwargs.get("pgns", []) + src_addr = kwargs.get("src_addr", 0xF9) + sniff_time = kwargs.get("sniff_time", 1.0) + stop_event = kwargs.get("stop_event") + bitrate = kwargs.get("bitrate", J1939_DEFAULT_BITRATE) + busload = kwargs.get("busload", J1939_DEFAULT_BUSLOAD) + reset_handler = kwargs.get("reset_handler") + reconnect_handler = kwargs.get("reconnect_handler") + reconnect_retries = kwargs.get("reconnect_retries", 5) + retry_delay = kwargs.get("retry_delay", 1.0) + + if isinstance(pgns, dict): + items = list(pgns.items()) + else: + items = [(pgn, pgn) for pgn in pgns] + + results = {} # type: Dict[Any, J1939PgnScanResult] + active_sock = socket + num_items = len(items) + + send_sock = rx_sock = active_sock + close_rx = False + + requests = list(self._get_initial_requests(**kwargs)) + + try: + for i, ((key, pgn), req_pkt) in enumerate(zip(items, requests)): + name_str = ( + str(key) if isinstance(key, str) else "PGN_0x{:04X}".format(pgn) + ) + if stop_event is not None and stop_event.is_set(): + results[key] = J1939PgnScanResult( + pgn, False, name=name_str, error="Aborted" + ) + break + + res_list = [] # type: List[J1939PgnScanResult] + + def _rx(pkt): + # type: (CAN) -> None + if res_list: + return + if stop_event is not None and stop_event.is_set(): + return + if hasattr(pkt, "flags") and not pkt.flags.extended: + return + sa = ( + pkt.identifier & 0xFF + if hasattr(pkt, "identifier") + else getattr(pkt, "src", None) + ) + if sa != target_da: + j1939_emit_sa_filter_warning([active_sock], target_da) + return + j_pkt = pkt if isinstance(pkt, J1939) else J1939.from_can(pkt) + if j_pkt.pgn == pgn: + log_j1939.debug( + "pgn_scan: positive response SA=0x%02X PGN=0x%04X", + sa, + pgn, + ) + res_list.append( + J1939PgnScanResult( + pgn, True, name=name_str, packet=pkt + ) + ) + return + + tp_cm = ( + j_pkt.getlayer(J1939_TP_CM_BAM) + or j_pkt.getlayer(J1939_TP_CM_RTS) + ) + if tp_cm is not None and ( + ( + isinstance(tp_cm, J1939_TP_CM_BAM) + and j_pkt.dst == J1939_GLOBAL_ADDRESS + ) + or ( + isinstance(tp_cm, J1939_TP_CM_RTS) + and j_pkt.dst == src_addr + ) + ) and tp_cm.pgn == pgn: + log_j1939.debug( + "pgn_scan: TP positive response " + "SA=0x%02X PGN=0x%04X", + sa, + pgn, + ) + if isinstance(tp_cm, J1939_TP_CM_RTS): + try: + abort_pkt = J1939( + priority=7, + pgn=J1939_PGN_TP_CM, + dst=target_da, + src=src_addr, + ) / J1939_TP_CM_ABORT( + reason=0xFF, pgn=pgn + ) + send_sock.send(abort_pkt.to_can()) + except (AttributeError, OSError) as ex: + log_j1939.debug( + "pgn_scan: failed to send TP abort to " + "SA=0x%02X: %s", + src_addr, + ex, + ) + res_list.append( + J1939PgnScanResult( + pgn, True, name=name_str, packet=pkt + ) + ) + return + + ack = j_pkt.getlayer(J1939Ack) + if ( + ack is not None + and ack.ctrl == J1939_ACK_CTRL_NACK + and ack.pgn == pgn + ): + log_j1939.debug( + "pgn_scan: NACK from SA=0x%02X PGN=0x%04X", + sa, + pgn, + ) + res_list.append( + J1939PgnScanResult( + pgn, + False, + name=name_str, + packet=pkt, + error="NACK", + ) + ) + + def _send_probe(): + # type: () -> None + send_sock.send(req_pkt.to_can()) + log_j1939.debug( + "pgn_scan: probing DA=0x%02X PGN=0x%04X (%s)", + target_da, + pgn, + name_str, + ) + + rx_sock.sniff( + prn=_rx, + timeout=sniff_time, + store=False, + started_callback=_send_probe, + stop_filter=lambda _: bool(res_list), + ) + + _extra = j1939_inter_probe_delay( + bitrate, busload, 3, 8, sniff_time + ) + if _extra > 0.0: + time.sleep(_extra) + + if res_list: + results[key] = res_list[0] + elif stop_event is not None and stop_event.is_set(): + results[key] = J1939PgnScanResult( + pgn, False, name=name_str, error="Aborted" + ) + else: + log_j1939.debug( + "pgn_scan: timeout waiting for DA=0x%02X PGN=0x%04X", + target_da, + pgn, + ) + results[key] = J1939PgnScanResult( + pgn, False, name=name_str, error="Timeout" + ) + + if i < num_items - 1: + if reset_handler is not None: + log_j1939.debug( + "pgn_scan: calling reset_handler between probes" + ) + reset_handler() + if reconnect_handler is not None: + log_j1939.debug("pgn_scan: calling reconnect_handler") + if close_rx: + rx_sock.close() + active_sock = j1939_reconnect_with_retry( + reconnect_handler, + reconnect_retries=reconnect_retries, + retry_delay=retry_delay, + stop_event=stop_event, + ) + send_sock = rx_sock = active_sock + close_rx = True + finally: + if close_rx: + rx_sock.close() + + self.pgn_results = results + self._state_completed[state] = True + + +class J1939_DM_Enumerator(J1939_PGN_Enumerator): + """Enumerator for SAE J1939-73 Diagnostic Message PGNs.""" + + def _get_initial_requests(self, **kwargs): + # type: (Any) -> Iterable[Packet] + kwargs_copy = dict(kwargs) + if "pgns" not in kwargs_copy or kwargs_copy["pgns"] is None: + kwargs_copy["pgns"] = J1939_DM_PGNS + return super(J1939_DM_Enumerator, self)._get_initial_requests( + **kwargs_copy + ) + + +class J1939_DM_Scanner(AutomotiveTestCaseExecutor): + """Automotive scanner for J1939 Diagnostic Message enumeration.""" + + @property + def default_test_case_clss(self): + # type: () -> List[Type[AutomotiveTestCaseABC]] + return [J1939_DM_Enumerator] + + +# --- General PGN request scanner + + +def j1939_scan_pgns( + sock, # type: SuperSocket + target_da, # type: int + pgns, # type: Union[List[int], Dict[Any, int]] + src_addr=0xF9, # type: int + sniff_time=1.0, # type: float + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reset_handler=None, # type: Optional[Callable[[], None]] + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] + reconnect_retries=5, # type: int + retry_delay=1.0, # type: float +): + # type: (...) -> Dict[Any, J1939PgnScanResult] + """Probe *target_da* for a sequence of Parameter Group Numbers (PGNs). + + Iterates over the PGNs specified in *pgns* (either a dictionary mapping + names/identifiers to PGN integers, or an iterable of PGN integers), + sending a unicast Request (PGN 59904) for each and classifying the response. + + If *reset_handler* is provided it is called between each pair of probes to + reset the target ECU to a known state. If *reconnect_handler* is also + provided it is called immediately after the reset to obtain a fresh socket; + subsequent probes will use the returned socket. + + :param sock: raw CAN socket + :param target_da: destination address of the ECU to probe (0x00–0xFD) + :param pgns: dict mapping names to PGN numbers or list of PGN numbers + :param src_addr: source address used in outgoing probes (default 0xF9) + :param sniff_time: per-PGN listen time in seconds (default 1.0) + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000 for J1939) + :param busload: maximum fraction of bus capacity the scanner may consume + (default 0.05 = 5 %) + :param reset_handler: optional callable to reset the target ECU between probes + :param reconnect_handler: optional callable returning a new CAN socket + :param reconnect_retries: maximum number of reconnect attempts (default 5) + :param retry_delay: delay in seconds between failed reconnect attempts (default 1.0) + :returns: dict mapping each input key/PGN to its :class:`J1939PgnScanResult` + """ + if busload <= 0.0 or busload > 1.0: + raise ValueError("busload must be in range (0.0, 1.0], got {}".format(busload)) + + if isinstance(pgns, dict): + items = list(pgns.items()) + else: + items = [(pgn, pgn) for pgn in pgns] + + if stop_event is not None and stop_event.is_set(): + return { + key: J1939PgnScanResult( + pgn, + False, + name=str(key) if isinstance(key, str) else "PGN_0x{:04X}".format(pgn), + error="Aborted", + ) + for key, pgn in items + } + + enumerator = J1939_PGN_Enumerator() + tc_kwargs = { + "bitrate": bitrate, + "busload": busload, + "pgns": pgns, + "reconnect_handler": reconnect_handler, + "reconnect_retries": reconnect_retries, + "reset_handler": reset_handler, + "retry_delay": retry_delay, + "sniff_time": sniff_time, + "src_addr": src_addr, + "stop_event": stop_event, + "target_da": target_da, + } + scanner = J1939_DM_Scanner( + sock, + test_cases=[enumerator], + J1939_PGN_Enumerator_kwargs=tc_kwargs, + J1939_DM_Enumerator_kwargs=tc_kwargs, + ) + scanner.scan() + return enumerator.pgn_results + + +# --- Top-level DM scanner (special case of j1939_scan_pgns) + + +def j1939_scan_dm( + sock, # type: SuperSocket + target_da, # type: int + dms=None, # type: Optional[List[str]] + src_addr=0xF9, # type: int + sniff_time=1.0, # type: float + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reset_handler=None, # type: Optional[Callable[[], None]] + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] + reconnect_retries=5, # type: int + retry_delay=1.0, # type: float +): + # type: (...) -> Dict[str, J1939PgnScanResult] + """Probe *target_da* for all (or a selected subset of) Diagnostic Message PGNs. + + Special case of :func:`j1939_scan_pgns` for SAE J1939-73 Diagnostic Messages + (:data:`J1939_DM_PGNS`). + + :param sock: raw CAN socket + :param target_da: destination address of the ECU to probe (0x00–0xFD) + :param dms: list of DM names to scan; must be keys of + :data:`J1939_DM_PGNS`. Default is all entries. + :param src_addr: source address used in outgoing probes (default 0xF9) + :param sniff_time: per-PGN listen time in seconds (default 1.0) + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000 for J1939) + :param busload: maximum fraction of bus capacity the scanner may consume + (default 0.05 = 5 %) + :param reset_handler: optional callable to reset the target ECU between probes + :param reconnect_handler: optional callable returning a new CAN socket + :param reconnect_retries: maximum number of reconnect attempts (default 5) + :param retry_delay: delay in seconds between failed reconnect attempts (default 1.0) + :returns: dict mapping each DM name (str) to its :class:`J1939PgnScanResult` + """ + if dms is None: + dms = list(J1939_DM_PGNS.keys()) + + for name in dms: + if name not in J1939_DM_PGNS: + raise ValueError( + "Unknown DM name {!r}; valid names: {}".format( + name, list(J1939_DM_PGNS.keys()) + ) + ) + + pgn_dict = {dm_name: J1939_DM_PGNS[dm_name] for dm_name in dms} + return j1939_scan_pgns( + sock=sock, + target_da=target_da, + pgns=pgn_dict, + src_addr=src_addr, + sniff_time=sniff_time, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reset_handler=reset_handler, + reconnect_handler=reconnect_handler, + reconnect_retries=reconnect_retries, + retry_delay=retry_delay, + ) + + +__all__ = [ + "J1939PgnScanResult", + "J1939_DM_Enumerator", + "J1939_DM_PGNS", + "J1939_DM_Scanner", + "J1939_PGN_Enumerator", + "J1939_PGN_VIN", + "j1939_scan_dm", + "j1939_scan_pgns", +] diff --git a/scapy/contrib/automotive/j1939/j1939_name.py b/scapy/contrib/automotive/j1939/j1939_name.py new file mode 100644 index 00000000000..61fb2cd34da --- /dev/null +++ b/scapy/contrib/automotive/j1939/j1939_name.py @@ -0,0 +1,356 @@ +# SPDX-License-Identifier: GPL-2.0-only +# This file is part of Scapy +# See https://scapy.net/ for more information +# Copyright (C) National Motor Freight Traffic Association Inc. +# + +# scapy.contrib.description = SAE J1939 64-bit NAME Decoder (J1939-81) +# scapy.contrib.status = loads + +""" +SAE J1939 NAME Protocol & Decoder (J1939-81). + +This module decodes the 64-bit (8-byte) J1939 NAME used in Address Claiming +and Network Management (PGN 60928, 0xEE00). According to SAE J1939-81 §4.2.1, +the 64-bit NAME is transmitted in CAN data bytes 1 through 8, with Byte 1 +being the Least Significant Byte (LSB, Identity Number LSB) and Byte 8 being +the Most Significant Byte (MSB, Arbitrary Address Capable, Industry Group, etc.). +""" + +from typing import ( + Any, + Optional, +) + +from scapy.contrib.j1939 import ( + J1939, + J1939_PGN_ADDRESS_CLAIMED, +) +from scapy.fields import ( + BitEnumField, + BitField, +) +from scapy.packet import Packet, bind_layers + + +# --------------------------------------------------------------------------- + + +# J1939 Standard Registries +# --------------------------------------------------------------------------- + +J1939_INDUSTRY_GROUPS = { + 0: "Global / Common across industries", + 1: "On-Highway Equipment (Trucks, Buses, Coaches)", + 2: "Agricultural and Forestry Equipment", + 3: "Construction Equipment", + 4: "Marine Equipment", + 5: "Industrial, Process Control, Stationary Equipment", + 6: "Fleet Management Systems", + 7: "Reserved for future SAE assignment", +} + +# Standard pre-assigned functions (Lower 128 values: 0 to 127) +# These values are universal and independent of Industry Group and Vehicle System. +J1939_PRE_ASSIGNED_FUNCTIONS = { + 0: "Engine", + 1: "Auxiliary Power Unit (APU)", + 2: "Electric Propulsion Control", + 3: "Transmission", + 4: "Battery Pack Monitor", + 5: "Shift Control/Console", + 6: "Power TakeOff - (Main or Rear)", + 7: "Axle - Steering", + 8: "Axle - Drive", + 9: "Brakes - System Controller", + 10: "Brakes - Steer Axle", + 11: "Brakes - Drive axle", + 12: "Retarder - Engine", + 13: "Retarder - Driveline", + 14: "Cruise Control", + 15: "Fuel System", + 16: "Steering Controller", + 17: "Suspension - Steer Axle", + 18: "Suspension - Drive Axle", + 19: "Instrument Cluster", + 20: "Trip Recorder", + 21: "Cab Climate Control", + 22: "Aerodynamic Control", + 23: "Vehicle Navigation", + 24: "Vehicle Security", + 25: "Network Interconnect ECU", + 26: "Body Controller", + 27: "Power TakeOff (Secondary or Front)", + 28: "Off Vehicle Gateway", + 29: "Virtual Terminal (in cab)", + 30: "Management Computer", + 31: "Propulsion Battery Charger", + 32: "Headway Controller", + 33: "System Monitor", + 34: "Hydraulic Pump Controller", + 35: "Suspension - System Controller", + 36: "Pneumatic - System Controller", + 37: "Cab Controller", + 38: "Tire Pressure Control", + 39: "Ignition Control Module", + 40: "Seat Control", + 41: "Lighting - Operator Controls", + 42: "Water Pump Control", + 43: "Transmission Display", + 44: "Exhaust Emission Control", + 45: "Vehicle Dynamic Stability Control", + 46: "Oil Sensor Unit", + 47: "Information System Controller", + 48: "Ramp Control", + 49: "Clutch/Converter Control", + 50: "Auxiliary Heater", + 51: "Forward-Looking Collision Warning System", + 52: "Chassis Controller", + 53: "Alternator/Charging System", + 54: "Communications Unit, Cellular", + 55: "Communications Unit, Satellite", + 56: "Communications Unit, Radio", + 57: "Steering Column Unit", + 58: "Fan Drive Control", + 59: "Starter", + 60: "Cab Display", + 61: "File Server / Printer", + 62: "On-Board Diagnostic Unit", + 63: "Engine Valve Controller", + 64: "Endurance Braking", + 65: "Gas Flow Measurement", + 66: "I/O Controller", + 67: "Electrical System Controller", + 68: "Aftertreatment system gas measurement", + 69: "Engine Emission Aftertreatment System", + 70: "Auxiliary Regeneration Device", + 71: "Transfer Case Control", + 72: "Coolant Valve Controller", + 73: "Rollover Detection Control", + 74: "Lubrication System", + 75: "Supplemental Fan", + 76: "Temperature Sensor", + 77: "Fuel Properties Sensor", + 78: "Fire Suppression System", + 79: "Power Systems Manager", + 80: "Electric Powertrain", + 81: "Hydraulic Powertrain", + 254: "Error State", + 255: "Not Available", +} + +# Industry group specific function mappings (values 128 to 253) +J1939_INDUSTRY_SPECIFIC_FUNCTIONS = { + 1: { # On-Highway Equipment + 130: "Cab Display / Operator Interface (On-Highway Specific)", + 131: "Tachograph Device", + 132: "Vehicle Gateway Interface", + }, + 2: { # Agricultural and Forestry Equipment (ISOBUS / ISO 11783) + 130: "Task Controller / Mapping Computer (ISO 11783-10)", + 135: "Virtual Terminal (ISO 11783-6)", + 140: "Implement / Working Set Master", + 141: "Auxiliary Valve Control / Implement Bridge", + }, + 3: { # Construction Equipment + 130: "Grade Control System", + 131: "Payload Scale System", + }, + 4: { # Marine Equipment (NMEA 2000) + 130: "Autopilot / Heading Control", + 131: "Radar / Sonar System", + 132: "VHF Radio / Communications", + }, +} + +# Industry group specific vehicle system mappings (values 0 to 127) +J1939_INDUSTRY_SPECIFIC_VEHICLE_SYSTEMS = { + 1: { # On-Highway Equipment + 1: "Tractor", + 2: "Trailer", + 3: "Public Transit Bus", + 4: "Specialized Construction Support Vehicle", + }, + 2: { # Agricultural and Forestry Equipment + 1: "Agricultural Tractor", + 2: "Tillage Implement", + 3: "Planter / Seeder Implement", + 4: "Fertilizer Implement", + 5: "Sprayer Implement", + 6: "Combine Harvester", + 7: "Forage Harvester", + }, + 3: { # Construction Equipment + 1: "Crawler Dozer", + 2: "Wheel Loader", + 3: "Hydraulic Excavator", + 4: "Off-Highway Haul Truck", + }, + 4: { # Marine Equipment + 1: "Vessel System", + 2: "Engine Room Monitor", + 3: "Bridge Navigation Display", + }, +} + +# Industry-assigned or common manufacturer codes (11 bits) +J1939_MANUFACTURERS = { + 8: "Caterpillar Inc.", + 15: "Cummins Inc.", + 35: "Detroit Diesel Corporation", + 49: "Deere & Company (John Deere)", + 88: "Eaton Corporation", + 117: "Allison Transmission", + 140: "Volvo Powertrain Corporation", + 154: "Bendix Commercial Vehicle Systems", + 161: "Volvo Lastvagnar AB", + 174: "Wabco Vehicle Control Systems", + 184: "PACCAR Inc.", + 275: "Detroit Diesel", + 345: "Robert Bosch GmbH", +} + + +class J1939Name(Packet): + """SAE J1939 64-bit NAME (J1939-81 Address Claiming). + + The 64-bit NAME is sent as the 8-byte payload in Address Claimed messages + (PGN 60928, 0xEE00). According to SAE J1939-81 §4.2.1, the 64-bit NAME is + transmitted Least Significant Byte (LSB) first over CAN: + + - Byte 1 (CAN data[0]): Identity Number bits 0-7 (LSB) + - Byte 2 (CAN data[1]): Identity Number bits 8-15 + - Byte 3 (CAN data[2]): Identity Number bits 16-20, Manufacturer Code bits 21-23 + - Byte 4 (CAN data[3]): Manufacturer Code bits 24-31 + - Byte 5 (CAN data[4]): ECU Instance bits 32-34, Function Instance bits 35-39 + - Byte 6 (CAN data[5]): Function bits 40-47 + - Byte 7 (CAN data[6]): Reserved bit 48, Vehicle System bits 49-55 + - Byte 8 (CAN data[7]): Vehicle System Instance bits 56-59, Industry Group + bits 60-62, Arbitrary Address Capable bit 63 (MSB) + """ + + name = "J1939Name" + MIN_LEN = 8 + + fields_desc = [ + BitField("arbitrary_address_capable", 0, 1, tot_size=-8), + BitEnumField("industry_group", 0, 3, J1939_INDUSTRY_GROUPS), + BitField("vehicle_system_instance", 0, 4), + BitField("vehicle_system", 0, 7), + BitField("reserved", 0, 1), + BitEnumField("function", 0, 8, J1939_PRE_ASSIGNED_FUNCTIONS), + BitField("function_instance", 0, 5), + BitField("ecu_instance", 0, 3), + BitEnumField("manufacturer_code", 0, 11, J1939_MANUFACTURERS), + BitField("identity_number", 0, 21, end_tot_size=-8), + ] + + def raw_value(self): + # type: () -> int + """Return the 64-bit integer representation of this NAME.""" + return int.from_bytes(bytes(self), "little") + + def mysummary(self): + # type: () -> str + mfg = J1939_MANUFACTURERS.get( + self.manufacturer_code, str(self.manufacturer_code) + ) + func = j1939_format_name_function(self) + return ( + "J1939Name: mfg='{}' " + "func='{}' " + "identity={} " + "arb_addr={}".format( + mfg, + func, + self.identity_number, + bool(self.arbitrary_address_capable), + ) + ) + + +def j1939_format_name_function(function_or_pkt, industry_group=None): + # type: (Any, Optional[int]) -> str + """Return the human-readable function description.""" + if isinstance(function_or_pkt, Packet): + func = getattr(function_or_pkt, "function", 0) + ig = ( + industry_group + if industry_group is not None + else getattr(function_or_pkt, "industry_group", 0) + ) + else: + func = int(function_or_pkt) + ig = industry_group if industry_group is not None else 0 + + if 128 <= func <= 253: + func_table = J1939_INDUSTRY_SPECIFIC_FUNCTIONS.get(ig, {}) + return func_table.get( + func, + "Industry Group Specific Function {}".format(func), + ) + if func in J1939_PRE_ASSIGNED_FUNCTIONS: + return J1939_PRE_ASSIGNED_FUNCTIONS[func] + if 82 <= func <= 127: + return "Pre-Assigned / Reserved Function ({})".format(func) + return str(func) + + +def j1939_format_name_industry_group(group_or_pkt): + # type: (Any) -> str + """Return the human-readable industry group description.""" + if isinstance(group_or_pkt, Packet): + ig = getattr(group_or_pkt, "industry_group", 0) + else: + ig = int(group_or_pkt) + return J1939_INDUSTRY_GROUPS.get(ig, str(ig)) + + +def j1939_format_name_manufacturer(mfg_or_pkt): + # type: (Any) -> str + """Return the human-readable manufacturer name.""" + if isinstance(mfg_or_pkt, Packet): + mfg = getattr(mfg_or_pkt, "manufacturer_code", 0) + else: + mfg = int(mfg_or_pkt) + return J1939_MANUFACTURERS.get(mfg, str(mfg)) + + +def j1939_format_name_vehicle_system(system_or_pkt, industry_group=None): + # type: (Any, Optional[int]) -> str + """Return the human-readable vehicle system description.""" + if isinstance(system_or_pkt, Packet): + vs = getattr(system_or_pkt, "vehicle_system", 0) + ig = ( + industry_group + if industry_group is not None + else getattr(system_or_pkt, "industry_group", 0) + ) + else: + vs = int(system_or_pkt) + ig = industry_group if industry_group is not None else 0 + + vs_table = J1939_INDUSTRY_SPECIFIC_VEHICLE_SYSTEMS.get(ig, {}) + return vs_table.get( + vs, + "Industry Group Specific Vehicle System {}".format(vs) + if ig != 0 + else "Common Vehicle System {}".format(vs), + ) + + +bind_layers(J1939, J1939Name, pgn=J1939_PGN_ADDRESS_CLAIMED) + + +__all__ = [ + "J1939Name", + "J1939_INDUSTRY_GROUPS", + "J1939_INDUSTRY_SPECIFIC_FUNCTIONS", + "J1939_INDUSTRY_SPECIFIC_VEHICLE_SYSTEMS", + "J1939_MANUFACTURERS", + "J1939_PRE_ASSIGNED_FUNCTIONS", + "j1939_format_name_function", + "j1939_format_name_industry_group", + "j1939_format_name_manufacturer", + "j1939_format_name_vehicle_system", +] diff --git a/scapy/contrib/automotive/j1939/j1939_scanner.py b/scapy/contrib/automotive/j1939/j1939_scanner.py new file mode 100644 index 00000000000..f7327dd595e --- /dev/null +++ b/scapy/contrib/automotive/j1939/j1939_scanner.py @@ -0,0 +1,1872 @@ +# SPDX-License-Identifier: GPL-2.0-only +# This file is part of Scapy +# See https://scapy.net/ for more information +# Copyright (C) National Motor Freight Traffic Association Inc. +# + +# scapy.contrib.description = SAE J1939 Controller Application (CA) Scanner +# scapy.contrib.status = library + +""" +J1939 Controller Application (CA) Scanner. + +Implements five complementary techniques for enumerating active J1939 +Controller Applications (CAs / ECUs) on a CAN bus, modelled after the +Scapy ``isotp_scan`` API. + +Technique 1 — Global Address Claim Request + Broadcasts a single Request (PGN 59904) for the Address Claimed PGN + (60928). Every active CA that implements J1939-81 address claiming must + respond. Best for networks where all nodes are J1939-81 compliant. + +Technique 2 — Global ECU Identification Request + Broadcasts a single Request (PGN 59904) for the ECU Identification Info + PGN (64965). Responding nodes announce their ECU ID via a BAM transfer. + Identifies nodes that publish an ECU Identification string. + +Technique 3 — Unicast Ping Sweep + Iterates through destination addresses 0x00–0xFD, sending a Request for + Address Claimed to each. Nodes that are active reply. Detects nodes + even if they do not respond to the broadcast in Technique 1. + +Technique 4 — TP.CM RTS Probing + Iterates through destination addresses 0x00–0xFD, sending a minimal + TP.CM_RTS frame to each. Active nodes reply with CTS, Conn_Abort, + or a NACK on the Acknowledgment PGN (0xE800), all of which confirm + the node is present. + +Technique 5 — UDS TesterPresent Probe + Iterates through destination addresses 0x00–0xFD, sending padded UDS + TesterPresent requests (SID 0x3E, sub-functions 0x00 and 0x01, + 5 x 0xFF padding) over both J1939 Diagnostic Message A (Physical) and + Diagnostic Message B (Functional), once for every source + address in *src_addrs*. Nodes that implement UDS reply with a positive + response (SID 0x7E) or a negative response (SID 0x7F). + +Technique 6 — XCP Connect Probe + Iterates through destination addresses 0x00–0xFD, sending an XCP CONNECT + command (command code 0xFF, mode 0x00, 6 x 0xFF padding) over J1939 + Diagnostic Message A (Physical), once for every source address in + *src_addrs*. Nodes that implement XCP reply with a positive response + (status byte 0xFF). + +Detection Matrix +---------------- + +The following table shows the probe each technique sends and the CAN +response it expects from an active CA in order to detect it. + ++------------+-----------------------------------+------------------------------------+ +| Technique | Probe (sent by scanner) | Expected response (from ECU) | ++============+===================================+====================================+ +| addr_claim | Broadcast Request (PF=EA, DA=FF) | Address Claimed (PF=EE, DA=FF) | +| | for PGN 60928 (0xEE00) | SA=ECU-SA, 8-byte J1939 NAME | ++------------+-----------------------------------+------------------------------------+ +| ecu_id | Broadcast Request (PF=EA, DA=FF) | TP.CM BAM (PF=EC, DA=FF, | +| | for PGN 64965 (0xFDC5) | ctrl=0x20) announcing PGN 64965 | ++------------+-----------------------------------+------------------------------------+ +| unicast | Unicast Request (PF=EA, DA=ECU) | Any CAN frame (extended) whose | +| | for PGN 60928 to each DA | SA equals probed DA | ++------------+-----------------------------------+------------------------------------+ +| rts_probe | TP.CM_RTS (PF=EC, DA=ECU-SA) | TP.CM_CTS (ctrl=0x11) or | +| | sent to each DA | TP_Conn_Abort (ctrl=0xFF) or | +| | | NACK on ACK PGN (PF=E8) | ++------------+-----------------------------------+------------------------------------+ +| uds | Physical (PF=diag, DA=ECU-SA) and | UDS response (positive 02 7E xx | +| | Functional (PF=diag+1, DA=FF) | or negative 03 7F 3E xx) | +| | payload 02 3E {00,01} padded | from responding DA | +| | once per SA in src_addrs | | ++------------+-----------------------------------+------------------------------------+ +| xcp | Physical (PF=diag, DA=ECU-SA) | XCP positive response (byte 0=FF) | +| | payload FF 00 FF FF FF FF FF FF | from responding DA | +| | once per SA in src_addrs | | ++------------+-----------------------------------+------------------------------------+ + +Usage:: + + >>> load_contrib('automotive.j1939') + >>> from scapy.contrib.cansocket import CANSocket + >>> from scapy.contrib.automotive.j1939.j1939_scanner import j1939_scan + >>> sock = CANSocket("can0") + >>> found = j1939_scan(sock, methods=["addr_claim", "unicast"]) + >>> for sa, info in found.items(): + ... print("SA=0x{:02X} found_by={} pkts={}".format( + ... sa, info["methods"], len(info["packets"]))) +""" + +import contextlib +import copy +from dataclasses import dataclass +import logging +import time +import weakref + +# Typing imports +from typing import ( + Any, + Callable, + Dict, + Iterable, + Iterator, + List, + Optional, + Set, + TYPE_CHECKING, + Type, + Union, + cast, +) + +if TYPE_CHECKING: + from threading import Event + +from scapy.contrib.automotive.ecu import EcuState +from scapy.contrib.automotive.j1939.j1939_name import J1939Name +from scapy.contrib.automotive.scanner.executor import AutomotiveTestCaseExecutor +from scapy.contrib.automotive.scanner.test_case import ( + AutomotiveTestCase, + AutomotiveTestCaseABC, +) +from scapy.contrib.automotive.uds import ( + UDS, + UDS_NR, + UDS_TP, + UDS_TPPR, +) +from scapy.contrib.automotive.xcp.xcp import ( + CTORequest, + Connect, +) +from scapy.contrib.j1939 import ( + J1939, + J1939Ack, + J1939DiagA, + J1939DiagB, + J1939Request, + J1939Socket, + J1939SoftSocket, + J1939_GLOBAL_ADDRESS, + J1939_PGN_ADDRESS_CLAIMED, + J1939_PGN_DIAG_A, + J1939_PGN_REQUEST, + J1939_TP_CM_ABORT, + J1939_TP_CM_BAM, + J1939_TP_CM_CTS, + J1939_TP_CM_RTS, + NativeJ1939Socket, + log_j1939, +) +from scapy.error import Scapy_Exception +from scapy.layers.can import CAN, CAN_EFF_FLAG +from scapy.packet import Packet +from scapy.supersocket import SuperSocket + + +@dataclass +class J1939ScanResult: + """Result of an individual J1939 scan probe. + + :param packet: the received response packet (:class:`~scapy.contrib.j1939.J1939`) + :param scanner_src: the scanner source address that elicited the response, + or None if unknown/unspecified + """ + + packet: J1939 + scanner_src: Optional[int] = None + + +# --- Scanner constants + +#: PGN for ECU Identification Information (J1939-73 §5.7.5) +J1939_PGN_ECU_ID = 0xFDC5 # 64965 + +#: Default priority for request frames sent by the scanner +_J1939_SCAN_PRIORITY = 6 + +#: Scan address range for unicast / RTS sweeps (0x00 – 0xFD inclusive) +_J1939_SCAN_ADDR_RANGE = range(0x00, 0xFE) # 0xFE = null / 0xFF = broadcast + +_J1939ProbeResult = Optional[Union[Packet, List[Packet]]] +_J1939ProbeCallable = Callable[[SuperSocket, int, int], _J1939ProbeResult] + +#: Candidate diagnostic source addresses (SAE J1939 reserved diagnostic range). +#: Used as the default for *src_addrs* in all scan functions. +J1939_DIAGADAPTERS_ADDRESSES = list(range(0xF1, 0xFE)) # [0xF1 .. 0xFD] + + +#: Pre-computed UDS TesterPresent request CAN frame payloads +#: (sub-functions 0x00 and 0x01). +J1939_UDS_TESTER_PRESENT_REQS = [ + (bytes([len(p)]) + bytes(p)).ljust(8, b"\xff") + for p in ( + UDS() / UDS_TP(subFunction=0x00), + UDS() / UDS_TP(subFunction=0x01), + ) +] + +#: Expected UDS responses for TesterPresent (SID=0x3E). +#: Truncated to positive responses (SID=0x7E, sub-functions 0x00 and 0x01) and +#: negative response header (SID=0x7F, original SID=0x3E) so any NRC matches. +J1939_UDS_TESTER_PRESENT_RESPS = [ + bytes(UDS() / UDS_TPPR(zeroSubFunction=0x00)), + bytes(UDS() / UDS_TPPR(zeroSubFunction=0x01)), + bytes(UDS() / UDS_NR(requestServiceId=0x3E))[:2], +] + +#: PGN for XCP Messages (Proprietary A, PDU1 peer-to-peer, PGN 0xEF00) +J1939_PGN_XCP = 0xEF00 + +#: Default source addresses used by the XCP scanner. +J1939_XCP_SRC_ADDRS = ( + [0x3F, 0x5A] + list(range(0x01, 0x10)) + [0xAC] + list(range(0xF1, 0xFE)) +) + +#: Padded XCP CONNECT request payload (8 bytes: 0xFF 0x00 followed by padding). +J1939_XCP_CONNECT_REQ = bytes(CTORequest() / Connect()).ljust(8, b"\xff") + +#: XCP positive response byte (status byte 0xFF = OK in XCP protocol) +J1939_XCP_POSITIVE_RESPONSE = 0xFF + +#: Acknowledgment control-byte values (J1939-21 §5.4.4, data byte 0). +J1939_ACK_CTRL_ACK = 0x00 # Positive Acknowledgment +J1939_ACK_CTRL_NACK = 0x01 # Negative Acknowledgment +J1939_ACK_CTRL_ACCESS_DENIED = 0x02 # Access Denied +J1939_ACK_CTRL_CANNOT_RESPOND = 0x03 # Cannot Respond + +#: All valid CA scan method names +J1939_SCAN_METHODS = ("addr_claim", "ecu_id", "unicast", "rts_probe", "uds", "xcp") + + +# --- Pacing helpers + +#: Default CAN bitrate for J1939 networks (SAE J1939-11, 250 kbit/s) +J1939_DEFAULT_BITRATE = 250000 # bit/s + +#: Default maximum fraction of bus bandwidth the scanner may consume (5 %) +J1939_DEFAULT_BUSLOAD = 0.05 + + +def j1939_inter_probe_delay(bitrate, busload, tx_dlc, rx_dlc, sniff_time): + # type: (int, float, int, int, float) -> float + """Compute the extra sleep needed after a probe-response cycle. + + Each probe cycle occupies *tx_dlc*-frame bits (outgoing probe) plus + *rx_dlc*-frame bits (expected response). The scanner's bandwidth budget + is ``bitrate × busload`` bits per second. If the probe-response exchange + completes in less time than the budget requires, the caller should sleep for + the returned value before transmitting the next probe. + + :param bitrate: CAN bus bitrate in bit/s (e.g. 250000 for 250 kbit/s) + :param busload: fraction of bus capacity the scanner may consume + (0 < busload ≤ 1.0) + :param tx_dlc: DLC of the outgoing probe frame (0–8) + :param rx_dlc: DLC of the expected response frame (0–8) + :param sniff_time: seconds already spent waiting for the response + :returns: non-negative seconds to sleep before the next probe + :raises ValueError: when *busload* is not in (0, 1.0] + """ + if not 0.0 < busload <= 1.0: + raise ValueError("busload must be in (0, 1.0]; got {!r}".format(busload)) + bits = (67 + tx_dlc * 8) + (67 + rx_dlc * 8) + min_cycle = bits / (bitrate * busload) + return max(0.0, min_cycle - sniff_time) + + +# --- Socketcan filter helpers + +def j1939_sa_filter(target_sa): + # type: (int) -> List[Dict[str, int]] + """Return socketcan ``can_filters`` matching extended frames with SA=*target_sa*. + + In a 29-bit J1939 CAN identifier the source address (SA) occupies bits + 7–0. The returned filter passes only extended-format frames whose low + byte equals *target_sa*, dramatically reducing the number of frames + delivered to the socket's kernel receive buffer on a busy bus. + + :param target_sa: source address to match (0x00–0xFF) + :returns: list with one ``can_filters`` dict suitable for + :class:`~scapy.contrib.cansocket_native.NativeCANSocket` + """ + return [{ + "can_id": CAN_EFF_FLAG | (target_sa & 0xFF), + "can_mask": CAN_EFF_FLAG | 0xFF, + }] + + +_J1939_FILTER_WARNED_SOCKETS = weakref.WeakSet() # type: weakref.WeakSet[Any] + + +def j1939_emit_sa_filter_warning(sock_objs, target_sa): + # type: (Iterable[Any], int) -> None + """Emit warning recommending a CAN filter for *target_sa* once.""" + if not any(obj in _J1939_FILTER_WARNED_SOCKETS for obj in sock_objs): + log_j1939.warning( + "You should put a filter for SA=0x%02X on your CAN socket", + target_sa, + ) + for obj in sock_objs: + try: + _J1939_FILTER_WARNED_SOCKETS.add(obj) + except TypeError as ex: + # Sockets without weakref support cannot be tracked in WeakSet + log_j1939.debug( + "failed to track socket object in WeakSet: %s", ex + ) + + +def j1939_check_rx_filter_warning(pkt, target_sa, warning_targets): + # type: (Any, Optional[int], Iterable[Any]) -> None + """Inspect a received packet and emit filter warning if SA != target_sa.""" + if target_sa is None or pkt is None: + return + sa = getattr(pkt, "src", None) + if sa is None and hasattr(pkt, "identifier"): + try: + sa = pkt.identifier & 0xFF + except (AttributeError, TypeError, ValueError) as ex: + log_j1939.debug( + "j1939_check_rx_filter_warning: failed to decode CAN ID: %s", ex + ) + if sa is not None and sa != target_sa: + j1939_emit_sa_filter_warning(warning_targets, target_sa) + + +def j1939_reconnect_with_retry( + reconnect_handler, # type: Callable[[], SuperSocket] + reconnect_retries=5, # type: int + retry_delay=1.0, # type: float + stop_event=None, # type: Optional[Event] +): + # type: (...) -> SuperSocket + """Invoke *reconnect_handler* with retries on failure.""" + for attempt in range(max(1, reconnect_retries)): + try: + return reconnect_handler() + except (AttributeError, OSError, Scapy_Exception) as ex: + if attempt == reconnect_retries - 1: + raise + log_j1939.debug( + "reconnect attempt %d/%d failed: %s, retrying in %s s", + attempt + 1, + reconnect_retries, + ex, + retry_delay, + ) + if stop_event is not None: + stop_event.wait(retry_delay) + else: + time.sleep(retry_delay) + raise OSError("reconnect_handler failed after exhausting retries") + + +@contextlib.contextmanager +def j1939_get_sock( + sock, # type: SuperSocket + src_addr=0xF9, # type: int + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] + target_sa=None, # type: Optional[int] + include_tp_cm=False, # type: bool + promisc=True, # type: bool +): + # type: (...) -> Iterator[SuperSocket] + """Context manager yielding a J1939Socket configured with *src_addr*. + + If *sock* is closed or not working and *reconnect_handler* is provided, + obtains a fresh socket from *reconnect_handler* and closes it on exit. + If *sock* is already a J1939Socket, yields it without closing *sock*. + Otherwise wraps *sock* in a J1939Socket and closes the wrapper on exit + (preserving the underlying CAN socket). + """ + inner_sock = getattr(sock, "_inner", sock) + is_closed = ( + inner_sock is None + or getattr(inner_sock, "closed", False) + or getattr(getattr(inner_sock, "impl", None), "closed", False) + or getattr(getattr(inner_sock, "can_socket", None), "closed", False) + ) + + close_raw = False + if is_closed and reconnect_handler is not None: + raw = reconnect_handler() + close_raw = True + else: + raw = inner_sock + + if isinstance(raw, (J1939SoftSocket, NativeJ1939Socket)): + try: + yield raw + finally: + if close_raw: + try: + raw.close() + except (AttributeError, OSError) as ex: + log_j1939.debug( + "j1939_get_sock: failed to close socket: %s", ex + ) + else: + j_sock = J1939Socket( + raw, + src_addr=src_addr, + include_tp_cm=include_tp_cm, + promisc=promisc, + ) + try: + yield j_sock + finally: + try: + j_sock.close() + except (AttributeError, OSError) as ex: + log_j1939.debug( + "j1939_get_sock: failed to close j_sock: %s", ex + ) + if close_raw: + try: + raw.close() + except (AttributeError, OSError) as ex: + log_j1939.debug( + "j1939_get_sock: failed to close raw socket: %s", ex + ) + + +# --- Passive scan — background noise detection + + +def j1939_scan_passive( + + sock, # type: SuperSocket + listen_time=2.0, # type: float + stop_event=None, # type: Optional[Event] + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Set[int] + """Passively listen to the bus and return the set of observed source addresses. + + Listens for *listen_time* seconds without sending any probe frames and + records every source address (SA) seen in an extended CAN frame. The + returned set can be passed as the ``noise_ids`` argument to the active + scan functions so that already-known CAs are not re-probed or re-reported. + + :param sock: raw CAN socket + :param listen_time: seconds to collect background traffic + :param stop_event: optional :class:`threading.Event` to abort early + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket + :returns: set of observed source addresses (integers) + """ + if reconnect_handler is not None: + active_sock, close_sock = reconnect_handler(), True + else: + active_sock, close_sock = sock, False + try: + seen = set() # type: Set[int] + + def _rx(pkt): + # type: (CAN) -> None + if stop_event is not None and stop_event.is_set(): + return + if not pkt.flags.extended: + return + seen.add(pkt.identifier & 0xFF) + + active_sock.sniff(prn=_rx, timeout=listen_time, store=False) + log_j1939.debug( + "passive: observed %d SA(s): %s", len(seen), [hex(s) for s in sorted(seen)] + ) + return seen + finally: + if close_sock: + active_sock.close() + + +# --- Core Scan Execution Engines + + +def _j1939_scan_broadcast_loop( + sock, # type: SuperSocket + src_addrs, # type: Optional[Iterable[int]] + build_probes, # type: Callable[[int], Iterable[Packet]] + match_response, # type: Callable[[Packet], bool] + log_name, # type: str + listen_time=1.0, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] + include_tp_cm=False, # type: bool + tx_dlc=3, # type: int + rx_dlc=8, # type: int + on_match=None, # type: Optional[Callable[[int, int, Packet], None]] + found=None, # type: Optional[Dict[int, List[J1939ScanResult]]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Execute broadcast discovery loop across *src_addrs*.""" + if src_addrs is None: + src_addrs = J1939_DIAGADAPTERS_ADDRESSES + if found is None: + found = {} + + with ( + j1939_get_sock(sock, include_tp_cm=include_tp_cm) + if reconnect_handler is None + else contextlib.nullcontext(sock) + ) as base_j_sock: + for _sa in src_addrs: + if stop_event is not None and stop_event.is_set(): + break + with j1939_get_sock( + base_j_sock, + src_addr=_sa, + reconnect_handler=reconnect_handler, + include_tp_cm=include_tp_cm, + ) as j_sock: + for req in build_probes(_sa): + if stop_event is not None and stop_event.is_set(): + break + ans, _ = j_sock.sr( + req, multi=True, timeout=listen_time, verbose=False + ) + for _, rcv in ans: + if stop_event is not None and stop_event.is_set(): + break + if match_response(rcv): + sa = rcv.src + if not force and noise_ids is not None and sa in noise_ids: + log_j1939.debug( + "%s: suppressing noise SA=0x%02X", log_name, sa + ) + continue + if on_match is not None: + on_match(sa, _sa, rcv) + if sa not in found: + found[sa] = [] + found[sa].append( + J1939ScanResult(packet=rcv, scanner_src=_sa) + ) + + _extra = j1939_inter_probe_delay(bitrate, busload, tx_dlc, rx_dlc, listen_time) + if _extra > 0.0: + time.sleep(_extra) + + return found + + +def _j1939_scan_sweep_loop( + sock, # type: SuperSocket + scan_range, # type: Iterable[int] + src_addrs, # type: Optional[Iterable[int]] + default_src_addrs, # type: List[int] + probe_step, # type: _J1939ProbeCallable + log_name, # type: str + sniff_time=0.1, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] + tx_dlc=3, # type: int + rx_dlc=8, # type: int + num_tx_probes=1, # type: int + pace_per_sa=False, # type: bool + found=None, # type: Optional[Dict[int, List[J1939ScanResult]]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Execute unicast address sweep across *scan_range* and *src_addrs*.""" + if src_addrs is None: + src_addrs = default_src_addrs + else: + src_addrs = list(src_addrs) + if found is None: + found = {} + + def _calc_extra(): + # type: () -> float + tx_bits = num_tx_probes * (67 + tx_dlc * 8) + return max( + 0.0, + (tx_bits + 67 + rx_dlc * 8) / (bitrate * busload) - sniff_time, + ) + + with ( + j1939_get_sock(sock) + if reconnect_handler is None + else contextlib.nullcontext(sock) + ) as base_j_sock: + for da in scan_range: + if stop_event is not None and stop_event.is_set(): + break + if not force and noise_ids is not None and da in noise_ids: + log_j1939.debug("%s: skipping noise DA=0x%02X", log_name, da) + continue + + _da = da + with j1939_get_sock( + base_j_sock, reconnect_handler=reconnect_handler, target_sa=_da + ) as j_sock: + for _sa in src_addrs: + if stop_event is not None and stop_event.is_set(): + break + resps = probe_step(j_sock, _da, _sa) + if resps: + resp_list = resps if isinstance(resps, list) else [resps] + for pkt in resp_list: + j1939_check_rx_filter_warning( + pkt, _da, [base_j_sock, j_sock] + ) + if _da not in found: + found[_da] = [] + for pkt in resp_list: + found[_da].append( + J1939ScanResult(packet=pkt, scanner_src=_sa) + ) + if pace_per_sa: + _extra = _calc_extra() + if _extra > 0.0: + time.sleep(_extra) + + if not pace_per_sa: + _extra = _calc_extra() + if _extra > 0.0: + time.sleep(_extra) + + return found + + +# --- Technique 1 – Global Address Claim Request + + +def j1939_scan_addr_claim( + sock, # type: SuperSocket + src_addrs=None, # type: Optional[List[int]] + listen_time=1.0, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Enumerate CAs via a global Request for Address Claimed (PGN 60928). + + For each address in *src_addrs*, sends a broadcast Request frame and + listens for Address Claimed replies. Every J1939-81-compliant CA must + respond. + + :param sock: raw CAN socket + :param src_addrs: list of source addresses to use in requests; defaults + to :data:`J1939_DIAGADAPTERS_ADDRESSES` ([0xF1..0xFD]) + :param listen_time: seconds to collect responses after sending each probe + :param noise_ids: set of source addresses already seen on the bus + (from :func:`j1939_scan_passive`). SAs in this set + are suppressed from the results unless *force* is True. + :param force: if True, report all responding SAs even if they appear in + *noise_ids* + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000). + :param busload: maximum scanner bus-load fraction (default 0.05). + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket + :returns: dict mapping responder source address (int) to a list of + :class:`J1939ScanResult` objects + """ + def make_probes(sa): + # type: (int) -> List[Packet] + req = J1939( + pgn=J1939_PGN_REQUEST, dst=J1939_GLOBAL_ADDRESS, src=sa + ) / J1939Request( + req_pgn=J1939_PGN_ADDRESS_CLAIMED + ) + log_j1939.debug( + "addr_claim: broadcast request sent SA=0x%02X (CAN-ID=0x%08X)", + sa, + req.to_can_id(), + ) + return [req] + + return _j1939_scan_broadcast_loop( + sock=sock, + src_addrs=src_addrs, + build_probes=make_probes, + match_response=lambda rcv: rcv.pgn == J1939_PGN_ADDRESS_CLAIMED, + log_name="addr_claim", + listen_time=listen_time, + noise_ids=noise_ids, + force=force, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + tx_dlc=3, + rx_dlc=8, + ) + + +# --- Technique 2 – Global ECU ID Request + + +def j1939_scan_ecu_id( + sock, # type: SuperSocket + src_addrs=None, # type: Optional[List[int]] + listen_time=1.0, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Enumerate CAs via a global Request for ECU Identification (PGN 64965). + + For each address in *src_addrs*, sends a broadcast Request frame and + listens for BAM announce headers whose PGN field matches 64965. + + :param sock: raw CAN socket + :param src_addrs: list of source addresses to use in requests; defaults + to :data:`J1939_DIAGADAPTERS_ADDRESSES` ([0xF1..0xFD]) + :param listen_time: seconds to collect responses after sending each probe + :param noise_ids: set of source addresses to suppress from results + (see :func:`j1939_scan_passive`) + :param force: if True, report all responding SAs even if in *noise_ids* + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000). + :param busload: maximum scanner bus-load fraction (default 0.05). + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket + :returns: dict mapping responder source address (int) to a list of + :class:`J1939ScanResult` objects + """ + def make_probes(sa): + # type: (int) -> List[Packet] + req = J1939( + pgn=J1939_PGN_REQUEST, dst=J1939_GLOBAL_ADDRESS, src=sa + ) / J1939Request( + req_pgn=J1939_PGN_ECU_ID + ) + log_j1939.debug( + "ecu_id: broadcast request sent SA=0x%02X (CAN-ID=0x%08X)", + sa, + req.to_can_id(), + ) + return [req] + + def match_resp(rcv): + # type: (Packet) -> bool + if rcv.pgn == J1939_PGN_ECU_ID: + return True + bam = rcv.getlayer(J1939_TP_CM_BAM) + return bam is not None and bam.pgn == J1939_PGN_ECU_ID + + def on_match(sa, scanner_sa, rcv): + # type: (int, int, Packet) -> None + log_j1939.debug("ecu_id: BAM from SA=0x%02X", sa) + + return _j1939_scan_broadcast_loop( + sock=sock, + src_addrs=src_addrs, + build_probes=make_probes, + match_response=match_resp, + log_name="ecu_id", + listen_time=listen_time, + noise_ids=noise_ids, + force=force, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + include_tp_cm=True, + tx_dlc=3, + rx_dlc=8, + on_match=on_match, + ) + + +# --- Technique 3 – Unicast Ping Sweep + + +def j1939_scan_unicast( + sock, # type: SuperSocket + scan_range=_J1939_SCAN_ADDR_RANGE, # type: Iterable[int] + src_addrs=None, # type: Optional[List[int]] + sniff_time=0.1, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Enumerate CAs by sending unicast Address Claim Requests to each DA. + + For each destination address *da* in *scan_range*, sends a Request for + Address Claimed (PGN 60928) addressed to *da* once for each address in + *src_addrs*. Any CAN frame whose source address equals *da* is counted + as a positive response. + + When *noise_ids* is provided (and *force* is False), destination addresses + that appear in *noise_ids* are skipped entirely — no probe is sent and no + response is recorded for those addresses. This prevents re-reporting CAs + already known from background bus traffic. + + The inter-probe gap is automatically paced so that the scanner contributes + at most *busload* × *bitrate* bits per second to the bus, counting both + the outgoing probe frames and the expected response frame. + + :param sock: raw CAN socket + :param scan_range: iterable of destination addresses to probe + :param src_addrs: list of source addresses to use in requests; defaults + to :data:`J1939_DIAGADAPTERS_ADDRESSES` ([0xF1..0xF9]) + :param sniff_time: seconds to wait for a response after each probe + :param noise_ids: set of source addresses already known from background + traffic (see :func:`j1939_scan_passive`). DAs whose + value appears in this set are not probed. + :param force: if True, probe all DAs in *scan_range* regardless of + *noise_ids* + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000 for J1939) + :param busload: maximum fraction of bus capacity the scanner may consume + (default 0.05 = 5 %) + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket. When provided, a fresh socket is + created for each probed DA and closed after that + iteration. + :returns: dict mapping responder source address (int) to a list of + :class:`J1939ScanResult` objects + """ + def probe(j_sock, da, sa): + # type: (SuperSocket, int, int) -> Optional[Packet] + req = J1939( + pgn=J1939_PGN_REQUEST, dst=da, src=sa + ) / J1939Request( + req_pgn=J1939_PGN_ADDRESS_CLAIMED + ) + log_j1939.debug("unicast: probing DA=0x%02X from SA=0x%02X", da, sa) + rcv = j_sock.sr1(req, timeout=sniff_time, verbose=False) + if rcv is not None: + log_j1939.debug( + "unicast: response from SA=0x%02X to scanner SA=0x%02X", + rcv.src, + rcv.dst, + ) + return rcv + return None + + return _j1939_scan_sweep_loop( + sock=sock, + scan_range=scan_range, + src_addrs=src_addrs, + default_src_addrs=J1939_DIAGADAPTERS_ADDRESSES, + probe_step=probe, + log_name="unicast", + sniff_time=sniff_time, + noise_ids=noise_ids, + force=force, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + tx_dlc=3, + rx_dlc=8, + ) + + +# --- Technique 4 – TP.CM RTS Probing + + +def j1939_scan_rts_probe( + sock, # type: SuperSocket + scan_range=_J1939_SCAN_ADDR_RANGE, # type: Iterable[int] + src_addrs=None, # type: Optional[List[int]] + sniff_time=0.1, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Enumerate CAs by sending minimal TP.CM_RTS frames to each DA. + + For each destination address *da* in *scan_range*, sends a TP.CM_RTS + (Connection Management – Request to Send) frame once per address in + *src_addrs*. An active node replies with either TP.CM_CTS (clear to + send), ``TP_Conn_Abort`` (connection abort), or a NACK on the + Nodes that implement the J1939 Transport Protocol respond with either a + TP.CM_CTS or a TP.Conn_Abort frame. Nodes that do not implement TP may + respond with an Acknowledgment frame (PGN 0xE800 / 59392) carrying a NACK, + Access Denied, or Cannot Respond control byte. Silent nodes simply time + out. + + This technique is faster and simpler than DM14/DM13 for detecting CAs that + ignore Address Claim Requests. + + :param sock: raw CAN socket + :param scan_range: iterable of destination addresses to probe + :param src_addrs: list of source addresses to use in probes; defaults + to :data:`J1939_DIAGADAPTERS_ADDRESSES` ([0xF1..0xF9]) + :param sniff_time: seconds to wait for a response after each probe + :param noise_ids: set of source addresses already known from background + traffic (see :func:`j1939_scan_passive`). DAs whose + value appears in this set are not probed. + :param force: if True, probe all DAs in *scan_range* regardless of + *noise_ids* + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000 for J1939) + :param busload: maximum fraction of bus capacity the scanner may consume + (default 0.05 = 5 %) + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket. When provided, a fresh socket is + created for each probed DA and closed after that + iteration. + :returns: dict mapping responder source address (int) to a list of + :class:`J1939ScanResult` objects + """ + def probe(j_sock, da, sa): + # type: (SuperSocket, int, int) -> Optional[Packet] + req = J1939(pgn=0xEC00, dst=da, src=sa) / J1939_TP_CM_RTS( + total_size=9, + num_packets=2, + max_packets=0xFF, + pgn=0x0000FF, + ) + log_j1939.debug("rts_probe: probing DA=0x%02X from SA=0x%02X", da, sa) + rcv = j_sock.sr1(req, timeout=sniff_time, verbose=False) + if rcv is not None: + tp_cm = rcv.getlayer(J1939_TP_CM_CTS) or rcv.getlayer(J1939_TP_CM_ABORT) + if tp_cm is not None: + log_j1939.debug( + "rts_probe: %s from SA=0x%02X to scanner SA=0x%02X", + tp_cm.name, + rcv.src, + sa, + ) + return rcv + + ack = rcv.getlayer(J1939Ack) + if ack is not None and ack.ctrl in ( + J1939_ACK_CTRL_NACK, + J1939_ACK_CTRL_ACCESS_DENIED, + J1939_ACK_CTRL_CANNOT_RESPOND, + ): + log_j1939.debug( + "rts_probe: ACK (ctrl=0x%02X) from SA=0x%02X to" + " scanner SA=0x%02X", + ack.ctrl, + rcv.src, + sa, + ) + return rcv + return None + + return _j1939_scan_sweep_loop( + sock=sock, + scan_range=scan_range, + src_addrs=src_addrs, + default_src_addrs=J1939_DIAGADAPTERS_ADDRESSES, + probe_step=probe, + log_name="rts_probe", + sniff_time=sniff_time, + noise_ids=noise_ids, + force=force, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + tx_dlc=8, + rx_dlc=8, + ) + + +# --- Technique 5 – UDS TesterPresent Probe + + +def _j1939_is_uds_tester_present_resp(rcv): + # type: (Packet) -> bool + """Check if a received packet contains a UDS TesterPresent response.""" + uds = rcv.getlayer(UDS) + if uds is None: + data = getattr(rcv, "data", None) or bytes(rcv.payload) + if not data: + return False + uds = UDS(data) + if not ( + uds.haslayer(UDS_TPPR) + or (uds.haslayer(UDS_NR) and uds[UDS_NR].requestServiceId == 0x3E) + ) and len(data) > 1: + uds = UDS(data[1:]) + if uds.haslayer(UDS_TPPR): + return True + nr = uds.getlayer(UDS_NR) + if nr is not None and nr.requestServiceId == 0x3E: + return True + return False + + +def j1939_scan_uds( + sock, # type: SuperSocket + scan_range=_J1939_SCAN_ADDR_RANGE, # type: Iterable[int] + src_addrs=None, # type: Optional[List[int]] + sniff_time=0.1, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + skip_functional=False, # type: bool + broadcast_listen_time=1.0, # type: float + diag_pgn=J1939_PGN_DIAG_A, # type: int + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Enumerate CAs by sending a UDS TesterPresent request to each DA. + + First, if *skip_functional* is False, sends broadcast UDS TesterPresent + requests over Diagnostic Message B (DA=0xFF). + Attempts both subfunctions 0x00 and 0x01. Any responding source addresses + are recorded. + + Then, for each destination address *da* in *scan_range* and each source + address in *src_addrs*, sends padded UDS TesterPresent requests over + Diagnostic Message A. Attempts both subfunctions 0x00 + and 0x01. A node that implements UDS replies with a positive response + frame whose first three payload bytes are ``02 7E 00`` or ``02 7E 01``. + Only well-formed positive responses are recorded. + + The inter-probe gap is automatically paced so that the scanner contributes + at most *busload* × *bitrate* bits per second to the bus. + + :param sock: raw CAN socket + :param scan_range: iterable of destination addresses to probe + :param src_addrs: list of source addresses to use in requests; defaults + to :data:`J1939_DIAGADAPTERS_ADDRESSES` ([0xF1..0xF9]) + :param sniff_time: seconds to wait for a response after each probe + :param noise_ids: set of source addresses already known from background + traffic (see :func:`j1939_scan_passive`). DAs whose + value appears in this set are not probed. + :param force: if True, probe all DAs in *scan_range* regardless of + *noise_ids* + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000 for J1939) + :param busload: maximum fraction of bus capacity the scanner may consume + (default 0.05 = 5 %) + :param skip_functional: if True, skip the broadcast functional scan + :param broadcast_listen_time: seconds to wait for responses after the + broadcast functional probe + :param diag_pgn: PGN for UDS diagnostic messages (default :data:`J1939_PGN_DIAG_A`). + Functional addressing uses ``(pf | 0x01) << 8``. + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket. When provided, a fresh socket is + created for each probed DA and closed after that + iteration. + :returns: dict mapping responder source address (int) to a list of + :class:`J1939ScanResult` objects + """ + if src_addrs is None: + src_addrs = J1939_DIAGADAPTERS_ADDRESSES + else: + src_addrs = list(src_addrs) + found = {} # type: Dict[int, List[J1939ScanResult]] + reqs = J1939_UDS_TESTER_PRESENT_REQS + pf = (diag_pgn >> 8) & 0xFF if diag_pgn > 0xFF else diag_pgn + func_pgn = (pf | 0x01) << 8 + phys_pgn = pf << 8 + + if not skip_functional: + def make_bcast_probes(sa): + # type: (int) -> List[Packet] + log_j1939.debug( + "uds: broadcast functional probe sent SA=0x%02X (PF=0x%02X)", + sa, + pf | 0x01, + ) + return [ + J1939( + pgn=func_pgn, + dst=J1939_GLOBAL_ADDRESS, + src=sa, + ) / J1939DiagB(data=req_data) + for req_data in reqs + ] + + def match_bcast(rcv): + # type: (Packet) -> bool + return _j1939_is_uds_tester_present_resp(rcv) + + def on_bcast_match(sa, scanner_sa, rcv): + # type: (int, int, Packet) -> None + log_j1939.debug( + "uds: functional response from SA=0x%02X to scanner SA=0x%02X", + sa, + scanner_sa, + ) + + _j1939_scan_broadcast_loop( + sock=sock, + src_addrs=src_addrs, + build_probes=make_bcast_probes, + match_response=match_bcast, + log_name="uds", + listen_time=broadcast_listen_time, + noise_ids=noise_ids, + force=force, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + on_match=on_bcast_match, + found=found, + ) + + def probe_phys(j_sock, da, sa): + # type: (SuperSocket, int, int) -> Optional[Packet] + for req_data in reqs: + if stop_event is not None and stop_event.is_set(): + break + log_j1939.debug( + "uds: physical probe DA=0x%02X SA=0x%02X on PF=0x%02X", + da, + sa, + pf, + ) + req = J1939( + pgn=phys_pgn, dst=da, src=sa + ) / J1939DiagA(data=req_data) + rcv = j_sock.sr1(req, timeout=sniff_time, verbose=False) + if rcv is not None and _j1939_is_uds_tester_present_resp(rcv): + log_j1939.debug( + "uds: response from SA=0x%02X to scanner SA=0x%02X", + rcv.src, + sa, + ) + return rcv + return None + + return _j1939_scan_sweep_loop( + sock=sock, + scan_range=scan_range, + src_addrs=src_addrs, + default_src_addrs=J1939_DIAGADAPTERS_ADDRESSES, + probe_step=probe_phys, + log_name="uds", + sniff_time=sniff_time, + noise_ids=noise_ids, + force=force, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + tx_dlc=8, + rx_dlc=8, + num_tx_probes=len(reqs), + pace_per_sa=True, + found=found, + ) + + +# --- Technique 6 – XCP Connect Probe + + +def j1939_scan_xcp( + sock, # type: SuperSocket + scan_range=_J1939_SCAN_ADDR_RANGE, # type: Iterable[int] + src_addrs=None, # type: Optional[List[int]] + sniff_time=0.1, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + diag_pgn=J1939_PGN_XCP, # type: int + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, List[J1939ScanResult]] + """Enumerate CAs by sending an XCP CONNECT command to each DA. + + For each destination address *da* in *scan_range* and each source address + in *src_addrs*, sends a padded XCP CONNECT request (command byte 0xFF, + mode 0x00, 6 x 0xFF padding) over Diagnostic Message A. + A node that implements XCP replies with a positive response frame whose + first byte is ``0xFF``. Only well-formed positive responses are recorded. + + The inter-probe gap is automatically paced so that the scanner contributes + at most *busload* × *bitrate* bits per second to the bus. + + :param sock: raw CAN socket + :param scan_range: iterable of destination addresses to probe + :param src_addrs: list of source addresses to use in requests; defaults + to :data:`J1939_XCP_SRC_ADDRS` ([0x3F, 0x5A]) + :param sniff_time: seconds to wait for a response after each probe + :param noise_ids: set of source addresses already known from background + traffic (see :func:`j1939_scan_passive`). DAs whose + value appears in this set are not probed. + :param force: if True, probe all DAs in *scan_range* regardless of + *noise_ids* + :param stop_event: optional :class:`threading.Event` to abort early + :param bitrate: CAN bus bitrate in bit/s (default 250000 for J1939) + :param busload: maximum fraction of bus capacity the scanner may consume + (default 0.05 = 5 %) + :param diag_pgn: PGN for XCP diagnostic messages (default :data:`J1939_PGN_XCP`, + Proprietary A peer-to-peer addressing) + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket. When provided, a fresh socket is + created for each probed DA and closed after that + iteration. + :returns: dict mapping responder source address (int) to a list of + :class:`J1939ScanResult` objects + """ + connect_req = J1939_XCP_CONNECT_REQ + pf = (diag_pgn >> 8) & 0xFF if diag_pgn > 0xFF else diag_pgn + xcp_pgn = pf << 8 + + def probe(j_sock, da, sa): + # type: (SuperSocket, int, int) -> Optional[Packet] + req = J1939(pgn=xcp_pgn, dst=da, src=sa, data=connect_req) + log_j1939.debug("xcp: probing DA=0x%02X from SA=0x%02X", da, sa) + rcv = j_sock.sr1(req, timeout=sniff_time, verbose=False) + if rcv is not None: + data = rcv.data if rcv.data else bytes(rcv.payload) + if data and data[0] == J1939_XCP_POSITIVE_RESPONSE: + log_j1939.debug( + "xcp: response from SA=0x%02X to scanner SA=0x%02X", + rcv.src, + sa, + ) + return rcv + return None + + return _j1939_scan_sweep_loop( + sock=sock, + scan_range=scan_range, + src_addrs=src_addrs, + default_src_addrs=J1939_XCP_SRC_ADDRS, + probe_step=probe, + log_name="xcp", + sniff_time=sniff_time, + noise_ids=noise_ids, + force=force, + stop_event=stop_event, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + tx_dlc=8, + rx_dlc=8, + ) + + +# --- Automotive Scanner Integration + + +class J1939_CA_TestCaseBase(AutomotiveTestCase): + """Base test case for J1939 Controller Application enumeration.""" + + _method_name = "base" + _supported_kwargs = copy.copy(AutomotiveTestCase._supported_kwargs) + _supported_kwargs.update({ + "bitrate": (int, None), + "broadcast_listen_time": (None, None), + "busload": (None, None), + "diag_pgn": (None, None), + "force": (bool, None), + "noise_ids": (None, None), + "reconnect_handler": (None, None), + "scan_range": (None, None), + "skip_functional": (bool, None), + "sniff_time": (None, None), + "src_addrs": (None, None), + "stop_event": (None, None), + }) + + def __init__(self): + # type: () -> None + super(J1939_CA_TestCaseBase, self).__init__() + self.results = {} # type: Dict[int, List[J1939ScanResult]] + + @property + def supported_responses(self): + # type: () -> List[Any] + return [] + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + raise NotImplementedError() + + +class J1939_AddrClaim_TestCase(J1939_CA_TestCaseBase): + """Address Claim (PGN 60928) broadcast discovery test case.""" + + _method_name = "addr_claim" + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + self.results = j1939_scan_addr_claim( + sock=socket, + src_addrs=kwargs.get("src_addrs"), + listen_time=kwargs.get("broadcast_listen_time", 1.0), + noise_ids=kwargs.get("noise_ids"), + force=kwargs.get("force", False), + stop_event=kwargs.get("stop_event"), + bitrate=kwargs.get("bitrate", J1939_DEFAULT_BITRATE), + busload=kwargs.get("busload", J1939_DEFAULT_BUSLOAD), + reconnect_handler=kwargs.get("reconnect_handler"), + ) + self._state_completed[state] = True + + +class J1939_EcuId_TestCase(J1939_CA_TestCaseBase): + """ECU Identification (PGN 64965) broadcast discovery test case.""" + + _method_name = "ecu_id" + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + self.results = j1939_scan_ecu_id( + sock=socket, + src_addrs=kwargs.get("src_addrs"), + listen_time=kwargs.get("broadcast_listen_time", 1.0), + noise_ids=kwargs.get("noise_ids"), + force=kwargs.get("force", False), + stop_event=kwargs.get("stop_event"), + bitrate=kwargs.get("bitrate", J1939_DEFAULT_BITRATE), + busload=kwargs.get("busload", J1939_DEFAULT_BUSLOAD), + reconnect_handler=kwargs.get("reconnect_handler"), + ) + self._state_completed[state] = True + + +class J1939_Unicast_TestCase(J1939_CA_TestCaseBase): + """Unicast Address Claim request address sweep test case.""" + + _method_name = "unicast" + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + self.results = j1939_scan_unicast( + sock=socket, + scan_range=kwargs.get("scan_range", _J1939_SCAN_ADDR_RANGE), + src_addrs=kwargs.get("src_addrs"), + sniff_time=kwargs.get("sniff_time", 0.1), + noise_ids=kwargs.get("noise_ids"), + force=kwargs.get("force", False), + stop_event=kwargs.get("stop_event"), + bitrate=kwargs.get("bitrate", J1939_DEFAULT_BITRATE), + busload=kwargs.get("busload", J1939_DEFAULT_BUSLOAD), + reconnect_handler=kwargs.get("reconnect_handler"), + ) + self._state_completed[state] = True + + +class J1939_RtsProbe_TestCase(J1939_CA_TestCaseBase): + """TP.CM_RTS connection-abort sweep test case.""" + + _method_name = "rts_probe" + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + self.results = j1939_scan_rts_probe( + sock=socket, + scan_range=kwargs.get("scan_range", _J1939_SCAN_ADDR_RANGE), + src_addrs=kwargs.get("src_addrs"), + sniff_time=kwargs.get("sniff_time", 0.1), + noise_ids=kwargs.get("noise_ids"), + force=kwargs.get("force", False), + stop_event=kwargs.get("stop_event"), + bitrate=kwargs.get("bitrate", J1939_DEFAULT_BITRATE), + busload=kwargs.get("busload", J1939_DEFAULT_BUSLOAD), + reconnect_handler=kwargs.get("reconnect_handler"), + ) + self._state_completed[state] = True + + +class J1939_UDS_TestCase(J1939_CA_TestCaseBase): + """UDS TesterPresent probe sweep test case.""" + + _method_name = "uds" + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + uds_kwargs = { + "sock": socket, + "scan_range": kwargs.get("scan_range", _J1939_SCAN_ADDR_RANGE), + "src_addrs": kwargs.get("src_addrs"), + "sniff_time": kwargs.get("sniff_time", 0.1), + "noise_ids": kwargs.get("noise_ids"), + "force": kwargs.get("force", False), + "stop_event": kwargs.get("stop_event"), + "bitrate": kwargs.get("bitrate", J1939_DEFAULT_BITRATE), + "busload": kwargs.get("busload", J1939_DEFAULT_BUSLOAD), + "skip_functional": kwargs.get("skip_functional", False), + "broadcast_listen_time": kwargs.get("broadcast_listen_time", 1.0), + "reconnect_handler": kwargs.get("reconnect_handler"), + } + if kwargs.get("diag_pgn") is not None: + uds_kwargs["diag_pgn"] = kwargs["diag_pgn"] + self.results = j1939_scan_uds(**uds_kwargs) + self._state_completed[state] = True + + +class J1939_XCP_TestCase(J1939_CA_TestCaseBase): + """XCP CONNECT probe sweep test case.""" + + _method_name = "xcp" + + def execute(self, socket, state, **kwargs): + # type: (Any, EcuState, Any) -> None + xcp_kwargs = { + "sock": socket, + "scan_range": kwargs.get("scan_range", _J1939_SCAN_ADDR_RANGE), + "src_addrs": kwargs.get("src_addrs"), + "sniff_time": kwargs.get("sniff_time", 0.1), + "noise_ids": kwargs.get("noise_ids"), + "force": kwargs.get("force", False), + "stop_event": kwargs.get("stop_event"), + "bitrate": kwargs.get("bitrate", J1939_DEFAULT_BITRATE), + "busload": kwargs.get("busload", J1939_DEFAULT_BUSLOAD), + "reconnect_handler": kwargs.get("reconnect_handler"), + } + if kwargs.get("diag_pgn") is not None: + xcp_kwargs["diag_pgn"] = kwargs["diag_pgn"] + self.results = j1939_scan_xcp(**xcp_kwargs) + self._state_completed[state] = True + + +_J1939_TECHNIQUE_TC_MAP = { + "addr_claim": J1939_AddrClaim_TestCase, + "ecu_id": J1939_EcuId_TestCase, + "unicast": J1939_Unicast_TestCase, + "rts_probe": J1939_RtsProbe_TestCase, + "uds": J1939_UDS_TestCase, + "xcp": J1939_XCP_TestCase, +} + + +class J1939_Scanner(AutomotiveTestCaseExecutor): + """Automotive scanner for J1939 Controller Application enumeration. + + Coordinates test case execution across selected discovery techniques and + merges results into standard format. + """ + + @property + def default_test_case_clss(self): + # type: () -> List[Type[AutomotiveTestCaseABC]] + return [ + J1939_AddrClaim_TestCase, + J1939_EcuId_TestCase, + J1939_Unicast_TestCase, + J1939_RtsProbe_TestCase, + J1939_UDS_TestCase, + J1939_XCP_TestCase, + ] + + def get_results(self, verbose=False): + # type: (bool) -> Dict[int, Dict[str, object]] + """Merge scan results across all executed test cases.""" + merged = {} # type: Dict[int, Dict[str, object]] + for tc in self.configuration.test_cases: + if not isinstance(tc, J1939_CA_TestCaseBase): + continue + method_name = getattr(tc, "_method_name", "unknown") + for sa, scan_results in tc.results.items(): + src_addr = [] # type: List[int] + pkts = [] # type: List[J1939] + for r in scan_results: + pkts.append(r.packet) + if r.scanner_src is not None and r.scanner_src not in src_addr: + src_addr.append(r.scanner_src) + + if sa not in merged: + if verbose: + log_j1939.info( + "j1939_scan: found SA=0x%02X via %s", sa, method_name + ) + merged[sa] = { + "methods": [method_name], + "packets": [pkts], + "results": [scan_results], + "src_addrs": [src_addr], + } + else: + if verbose: + log_j1939.info( + "j1939_scan: SA=0x%02X also detected via %s", + sa, + method_name, + ) + cast(List[str], merged[sa]["methods"]).append(method_name) + cast(List[List[Any]], merged[sa]["packets"]).append(pkts) + cast(List[List[J1939ScanResult]], merged[sa]["results"]).append( + scan_results + ) + cast(List, merged[sa]["src_addrs"]).append(src_addr) + return merged + + +# --- Top-level combined scanner + + +def j1939_scan( + sock, # type: SuperSocket + scan_range=_J1939_SCAN_ADDR_RANGE, # type: Iterable[int] + methods=None, # type: Optional[List[str]] + src_addrs=None, # type: Optional[List[int]] + sniff_time=0.1, # type: float + broadcast_listen_time=1.0, # type: float + noise_listen_time=1.0, # type: float + noise_ids=None, # type: Optional[Set[int]] + force=False, # type: bool + stop_event=None, # type: Optional[Event] + verbose=False, # type: bool + bitrate=J1939_DEFAULT_BITRATE, # type: int + busload=J1939_DEFAULT_BUSLOAD, # type: float + skip_functional=False, # type: bool + diag_pgn=None, # type: Optional[int] + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, Dict[str, object]] + """Scan for J1939 Controller Applications using one or more techniques. + + Runs each requested scan method and merges the results. The returned + dictionary maps each discovered source address to a dict with keys: + + - ``"methods"`` (List[str]): list of all techniques that found this CA, + in the order they detected it. A CA discovered by more than one + technique will appear in all of their names. + - ``"packets"`` (List[List[CAN]]): list of lists of CAN response frames, + one inner list per entry in ``"methods"``, in the same order. + - ``"results"`` (List[List[J1939ScanResult]]): list of lists of + :class:`J1939ScanResult` objects, one inner list per entry in + ``"methods"``, in the same order. + - ``"src_addrs"`` (List[List[int]]): list of scanner source addresses, + one entry per technique in ``"methods"``. For techniques that use + physical addressing (``"uds"`` and ``"xcp"``), this records which + scanner source address produced the response — i.e. which SA must be + used for further access. An empty list is stored for techniques where + no scanner SA could be definitively identified. + + By default, before running any active probe the function performs a + passive bus listen (via :func:`j1939_scan_passive`) for *noise_listen_time* + seconds to detect pre-existing source addresses. Those addresses are then + excluded from active probing and from the results. Pass *force=True* to + disable this filtering, or supply an explicit *noise_ids* set to bypass the + passive pre-scan. + + :param sock: raw CAN socket + :param scan_range: DA range for unicast / RTS sweeps (default 0x00–0xFD) + :param methods: list of method names to run; valid values are + ``"addr_claim"``, ``"ecu_id"``, ``"unicast"``, + ``"rts_probe"``, ``"uds"``, ``"xcp"``. Default is all six. + :param src_addrs: list of source addresses to use in outgoing probes; + defaults to :data:`J1939_DIAGADAPTERS_ADDRESSES` ([0xF1..0xF9]) + :param sniff_time: per-address listen time for unicast / RTS methods + :param broadcast_listen_time: listen time for broadcast methods + :param noise_listen_time: seconds for the passive pre-scan (default 1.0). + Only used when *noise_ids* is None and *force* + is False. + :param noise_ids: explicit set of source addresses to exclude from + probing and results. When provided the passive pre-scan + is skipped. + :param force: if True, disable noise filtering entirely (no passive pre-scan, + all addresses are probed and reported) + :param stop_event: :class:`threading.Event` to abort the scan early + :param verbose: if True, set the ``log_j1939`` logger to + :data:`logging.DEBUG` and log discovered CAs to the + console. Matches the verbose pattern used by + :func:`~scapy.contrib.isotp.isotp_scanner.isotp_scan` and + :class:`~scapy.contrib.automotive.xcp.scanner.XCPOnCANScanner`. + :param bitrate: CAN bus bitrate in bit/s passed to unicast / RTS / UDS / XCP + methods. When not specified the scanner tries to read the + ``bitrate`` attribute of *sock* automatically, and falls + back to ``J1939_DEFAULT_BITRATE`` (250 kbps) if the + attribute is not available. + :param busload: maximum scanner bus-load fraction passed to unicast / RTS / + UDS / XCP methods (default 0.05 = 5 %) + :param skip_functional: passed to :func:`j1939_scan_uds` + :param diag_pgn: passed to :func:`j1939_scan_uds` and :func:`j1939_scan_xcp` + :param reconnect_handler: optional zero-argument callable returning a newly + created CAN socket passed down to each scan method. + :returns: dict mapping SA (int) to + ``{"methods": List[str], "packets": List[List[CAN]], + "src_addrs": List[List[int]]}`` + + Example:: + + >>> found = j1939_scan(sock) + >>> for sa, info in sorted(found.items()): + ... for method, src_addrs in zip(info["methods"], info["src_addrs"]): + ... s_sas = ", ".join("0x{:02X}".format(s) for s in src_addrs) + ... print("SA=0x{:02X} via {} (scanner SA={})".format( + ... sa, method, s_sas if s_sas else "broadcast")) + """ + if verbose: + log_j1939.setLevel(logging.DEBUG) + if methods is None: + methods = list(J1939_SCAN_METHODS) + + for m in methods: + if m not in J1939_SCAN_METHODS: + raise ValueError( + "Unknown scan method {!r}; valid methods: {}".format( + m, J1939_SCAN_METHODS + ) + ) + + if src_addrs is None: + src_addrs = J1939_DIAGADAPTERS_ADDRESSES + else: + src_addrs = list(src_addrs) + + # If the caller left bitrate at the sentinel default, try to pull the real + # value from the socket (e.g. CANSocket stores it as sock.bitrate). + # When reconnect_handler is provided, probe a temporary socket for the attribute. + if bitrate == J1939_DEFAULT_BITRATE: + _probe = reconnect_handler() if reconnect_handler is not None else sock + sock_bitrate = getattr(_probe, "bitrate", None) + if sock_bitrate is not None: + try: + bitrate = int(sock_bitrate) + except (TypeError, ValueError) as ex: + # Fall back to default bitrate if attribute is non-numeric + log_j1939.debug( + "invalid socket bitrate %r, using default: %s", + sock_bitrate, + ex, + ) + if reconnect_handler is not None and _probe is not sock: + try: + _probe.close() + except (AttributeError, OSError) as ex: + log_j1939.debug("failed to close probe socket: %s", ex) + + # Step 0: passive pre-scan to detect background noise unless disabled. + if not force and noise_ids is None: + if stop_event is not None and stop_event.is_set(): + return {} + noise_ids = j1939_scan_passive( + sock, + listen_time=noise_listen_time, + stop_event=stop_event, + reconnect_handler=reconnect_handler, + ) + if verbose and noise_ids: + log_j1939.info( + "j1939_scan: %d noise SA(s) detected, will skip: %s", + len(noise_ids), + [hex(s) for s in sorted(noise_ids)], + ) + + if not methods: + return {} + + if stop_event is not None and stop_event.is_set(): + return {} + + if sock is None and reconnect_handler is not None: + sock = reconnect_handler() + + scan_range_list = list(scan_range) + unique_methods = list(dict.fromkeys(methods)) + selected_tcs = [_J1939_TECHNIQUE_TC_MAP[m]() for m in unique_methods] + tc_kwargs = { + "bitrate": bitrate, + "broadcast_listen_time": broadcast_listen_time, + "busload": busload, + "force": force, + "noise_ids": noise_ids, + "reconnect_handler": reconnect_handler, + "scan_range": scan_range_list, + "skip_functional": skip_functional, + "sniff_time": sniff_time, + "src_addrs": src_addrs, + "stop_event": stop_event, + } + if diag_pgn is not None: + tc_kwargs["diag_pgn"] = diag_pgn + + scanner_kwargs = { + "{}_kwargs".format(tc.__class__.__name__): dict(tc_kwargs) + for tc in selected_tcs + } + scanner = J1939_Scanner( + sock, + test_cases=selected_tcs, + reconnect_handler=reconnect_handler, + **scanner_kwargs, + ) + if stop_event is not None: + scanner.configuration.stop_event = stop_event + scanner.scan() + return scanner.get_results(verbose=verbose) + + +def j1939_request_name( + sock, # type: SuperSocket + target_da=J1939_GLOBAL_ADDRESS, # type: int + src_addr=0xF1, # type: int + sniff_time=0.3, # type: float + bitrate=None, # type: Optional[int] + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Union[Optional[J1939Name], Dict[int, J1939Name]] + """Request and decode J1939 NAME for a given destination address (or broadcast). + + Sends a Request (PGN 59904, 0xEA00) for Address Claimed (PGN 60928, 0xEE00) + to *target_da* using source address *src_addr*. + + If *target_da* is a specific address (0x00..0xFD), waits for the Address + Claimed response from that address and returns a :class:`J1939Name` object + (or ``None`` if timed out). + + If *target_da* is the broadcast address (:data:`J1939_GLOBAL_ADDRESS` = 0xFF), + sniffs for all responses and returns a dictionary ``{sa: J1939Name}``. + """ + if bitrate is None: + bitrate = getattr(sock, "bitrate", None) + if bitrate is None: + can_bus = getattr(sock, "ins", None) + bitrate = getattr(can_bus, "bitrate", None) + if bitrate is None: + bitrate = J1939_DEFAULT_BITRATE + + req = J1939( + pgn=J1939_PGN_REQUEST, dst=target_da, src=src_addr + ) / J1939Request( + req_pgn=J1939_PGN_ADDRESS_CLAIMED + ) + + if target_da == J1939_GLOBAL_ADDRESS: + # Broadcast request + found = {} # type: Dict[int, J1939Name] + with j1939_get_sock( + sock, src_addr=src_addr, reconnect_handler=reconnect_handler + ) as j_sock: + log_j1939.debug( + "j1939_request_name: broadcast request sent (CAN-ID=0x%08X)", + req.to_can_id(), + ) + ans, _ = j_sock.sr(req, multi=True, timeout=sniff_time, verbose=False) + for _, rcv in ans: + if rcv.pgn == J1939_PGN_ADDRESS_CLAIMED: + if J1939Name in rcv and rcv.src not in found: + found[rcv.src] = rcv[J1939Name] + return found + else: + # Unicast request to target_da + with j1939_get_sock( + sock, + src_addr=src_addr, + reconnect_handler=reconnect_handler, + target_sa=target_da, + ) as j_sock: + log_j1939.debug( + "j1939_request_name: unicast request sent to DA=0x%02X (CAN-ID=0x%08X)", + target_da, + req.to_can_id(), + ) + rcv = j_sock.sr1(req, timeout=sniff_time, verbose=False) + if rcv is not None: + j1939_check_rx_filter_warning(rcv, target_da, [sock, j_sock]) + _extra = j1939_inter_probe_delay(bitrate, busload, 3, 8, sniff_time) + if _extra > 0.0: + time.sleep(_extra) + if rcv is not None and J1939Name in rcv: + return rcv[J1939Name] + return None + + +def j1939_request_names( + sock, # type: SuperSocket + target_das=None, # type: Optional[Iterable[int]] + src_addr=0xF1, # type: int + sniff_time=0.3, # type: float + bitrate=None, # type: Optional[int] + busload=J1939_DEFAULT_BUSLOAD, # type: float + reconnect_handler=None, # type: Optional[Callable[[], SuperSocket]] +): + # type: (...) -> Dict[int, Optional[J1939Name]] + """Request and decode J1939 NAMEs for multiple target Destination Addresses. + + :param sock: raw CAN socket or socket factory + :param target_das: iterable of destination addresses to probe. If None, + a single broadcast request is issued. + :param src_addr: scanner source address + :param sniff_time: timeout per probe + :param bitrate: bus bitrate in bit/s (optional, auto-detected from socket) + :param busload: max busload fraction + :param reconnect_handler: optional socket factory called per probe + :returns: mapping ``{da: J1939Name or None}`` + """ + if target_das is None: + broadcast_res = j1939_request_name( + sock, + target_da=J1939_GLOBAL_ADDRESS, + src_addr=src_addr, + sniff_time=sniff_time, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + ) + return broadcast_res if isinstance(broadcast_res, dict) else {} + + results = {} # type: Dict[int, Optional[J1939Name]] + for da in target_das: + res = j1939_request_name( + sock, + target_da=da, + src_addr=src_addr, + sniff_time=sniff_time, + bitrate=bitrate, + busload=busload, + reconnect_handler=reconnect_handler, + ) + results[da] = res if isinstance(res, J1939Name) else None + return results + + +__all__ = [ + "J1939ScanResult", + "J1939_ACK_CTRL_ACCESS_DENIED", + "J1939_ACK_CTRL_ACK", + "J1939_ACK_CTRL_CANNOT_RESPOND", + "J1939_ACK_CTRL_NACK", + "J1939_AddrClaim_TestCase", + "J1939_CA_TestCaseBase", + "J1939_DEFAULT_BITRATE", + "J1939_DEFAULT_BUSLOAD", + "J1939_DIAGADAPTERS_ADDRESSES", + "J1939_EcuId_TestCase", + "J1939_PGN_ECU_ID", + "J1939_PGN_XCP", + "J1939_RtsProbe_TestCase", + "J1939_SCAN_METHODS", + "J1939_Scanner", + "J1939_UDS_TESTER_PRESENT_REQS", + "J1939_UDS_TESTER_PRESENT_RESPS", + "J1939_UDS_TestCase", + "J1939_Unicast_TestCase", + "J1939_XCP_CONNECT_REQ", + "J1939_XCP_POSITIVE_RESPONSE", + "J1939_XCP_SRC_ADDRS", + "J1939_XCP_TestCase", + "j1939_check_rx_filter_warning", + "j1939_emit_sa_filter_warning", + "j1939_get_sock", + "j1939_inter_probe_delay", + "j1939_reconnect_with_retry", + "j1939_request_name", + "j1939_request_names", + "j1939_sa_filter", + "j1939_scan", + "j1939_scan_addr_claim", + "j1939_scan_ecu_id", + "j1939_scan_passive", + "j1939_scan_rts_probe", + "j1939_scan_uds", + "j1939_scan_unicast", + "j1939_scan_xcp", +] diff --git a/scapy/contrib/j1939.py b/scapy/contrib/j1939.py index f8d02c8a471..90e8bc9b1e7 100644 --- a/scapy/contrib/j1939.py +++ b/scapy/contrib/j1939.py @@ -41,21 +41,23 @@ Dict, List, Optional, + TYPE_CHECKING, Tuple, Type, Union, cast, - TYPE_CHECKING, ) from scapy.automaton import ObjectPipe, select_objects from scapy.compat import raw from scapy.config import conf from scapy.consts import LINUX +from scapy.contrib.automotive.uds import UDS from scapy.data import SO_TIMESTAMPNS -from scapy.error import Scapy_Exception, log_runtime +from scapy.error import Scapy_Exception, log_loading, log_runtime from scapy.fields import ( BitField, + ByteEnumField, ByteField, FieldLenField, FlagsField, @@ -68,7 +70,7 @@ XLE3BytesField, ) from scapy.layers.can import CAN -from scapy.packet import Packet +from scapy.packet import NoPayload, Packet, bind_layers from scapy.supersocket import SuperSocket from scapy.utils import EDecimal @@ -130,10 +132,26 @@ #: Global broadcast address J1939_BROADCAST_ADDR = socket.J1939_NO_ADDR # 0xFF +#: Global broadcast address +J1939_GLOBAL_ADDRESS = socket.J1939_NO_ADDR # 0xFF +#: Null address (no address) +J1939_NULL_ADDRESS = socket.J1939_IDLE_ADDR # 0xFE +#: Request PGN +J1939_PGN_REQUEST = socket.J1939_PGN_REQUEST # 0xEA00 +#: Acknowledgment PGN (J1939-21) +J1939_PGN_ACK = 0xE800 # 59392 +#: Address Claimed PGN +J1939_PGN_ADDRESS_CLAIMED = socket.J1939_PGN_ADDRESS_CLAIMED # 0xEE00 +#: Address Commanded PGN +J1939_PGN_ADDRESS_COMMANDED = socket.J1939_PGN_ADDRESS_COMMANDED # 0xFED8 #: Transport Protocol – Connection Management J1939_PGN_TP_CM = 0xEC00 #: Transport Protocol – Data Transfer J1939_PGN_TP_DT = 0xEB00 +#: PGN for J1939 Diagnostic Message A (PDU1 peer-to-peer, PF=0xDA) +J1939_PGN_DIAG_A = 0xDA00 +#: PGN for J1939 Diagnostic Message B (PDU1 peer-to-peer, PF=0xDB) +J1939_PGN_DIAG_B = 0xDB00 # TP control byte values (integer constants; the classes share the prefix name) J1939_TP_CTRL_RTS = 16 # Request To Send @@ -145,8 +163,15 @@ # PDU format threshold: PF < 240 → PDU1 (peer-to-peer), PF ≥ 240 → PDU2 (broadcast) J1939_PDU1_MAX_PF = 239 -# Default configuration key -conf.contribs['J1939'] = {'channel': 'can0'} +# Default configuration keys +try: + conf.contribs['J1939'].setdefault('channel', 'can0') + conf.contribs['J1939'].setdefault('generic-answers-fallback', True) +except KeyError: + conf.contribs['J1939'] = { + 'channel': 'can0', + 'generic-answers-fallback': True, + } # Common source address names (informational) J1939_ADDR_NAMES = { @@ -214,7 +239,7 @@ def j1939_to_can_id(priority, reserved, data_page, pdu_format, pdu_specific, src ) -def pgn_from_fields(data_page, pdu_format, pdu_specific): +def j1939_pgn_from_fields(data_page, pdu_format, pdu_specific): # type: (int, int, int) -> int """Compute the PGN from J1939 CAN identifier sub-fields. @@ -231,19 +256,6 @@ def pgn_from_fields(data_page, pdu_format, pdu_specific): return (data_page << 16) | (pdu_format << 8) | pdu_specific -def dst_from_fields(pdu_format, pdu_specific): - # type: (int, int) -> int - """Return the destination address encoded in J1939 identifier fields. - - :param pdu_format: PDU format byte (0-255) - :param pdu_specific: PDU specific byte (0-255) - :returns: destination address (0x00-0xFF), or ``socket.J1939_NO_ADDR`` for PDU2 - """ - if pdu_format <= J1939_PDU1_MAX_PF: - return pdu_specific - return socket.J1939_NO_ADDR - - # --------------------------------------------------------------------------- # J1939 application-layer packet # --------------------------------------------------------------------------- @@ -282,13 +294,189 @@ def __init__(self, *args, **kwargs): self.pgn = kwargs.pop('pgn', 0) # type: int self.src = kwargs.pop('src', socket.J1939_NO_ADDR) # type: int self.dst = kwargs.pop('dst', socket.J1939_NO_ADDR) # type: int - Packet.__init__(self, *args, **kwargs) + super().__init__(*args, **kwargs) + + def clone_with(self, payload=None, **kargs): + # type: (Optional[Any], **Any) -> J1939 + pkt = super().clone_with(payload=payload, **kargs) + pkt.priority = kargs.get('priority', self.priority) + pkt.pgn = kargs.get('pgn', self.pgn) + pkt.src = kargs.get('src', self.src) + pkt.dst = kargs.get('dst', self.dst) + return pkt + + def copy(self): + # type: () -> J1939 + clone = super().copy() + clone.priority = self.priority + clone.pgn = self.pgn + clone.src = self.src + clone.dst = self.dst + return clone + + def to_can_id(self): + # type: () -> int + """29-bit CAN arbitration identifier derived from J1939 fields.""" + pf = (self.pgn >> 8) & 0xFF + dp = (self.pgn >> 16) & 0x1 + if pf <= J1939_PDU1_MAX_PF: + ps = self.dst if self.dst != socket.J1939_NO_ADDR else 0xFF + else: + ps = self.pgn & 0xFF + return j1939_to_can_id(self.priority, 0, dp, pf, ps, self.src) + + def to_can(self): + # type: () -> CAN + """Convert this J1939 frame into a standard :class:`~scapy.layers.can.CAN` packet.""" # noqa: E501 + data = bytes(self.payload) if self.payload else self.data + pkt = CAN( + flags="extended", + identifier=self.to_can_id(), + length=len(data), + data=data, + ) + pkt.time = self.time + return pkt + + @classmethod + def from_can(cls, pkt): + # type: (CAN) -> J1939 + """Create a :class:`J1939` from a :class:`~scapy.layers.can.CAN` packet.""" + fields = can_id_to_j1939(pkt.identifier) + pgn = j1939_pgn_from_fields( + fields["data_page"], fields["pdu_format"], fields["pdu_specific"] + ) + dst = ( + fields["pdu_specific"] + if fields["pdu_format"] <= J1939_PDU1_MAX_PF + else socket.J1939_NO_ADDR + ) + data = ( + bytes(pkt.data) + if pkt.data + else (bytes(pkt.payload) if pkt.payload else b"") + ) + result = cls( + data, + priority=fields["priority"], + pgn=pgn, + src=fields["src"], + dst=dst, + ) + result.time = pkt.time + return result + + def do_dissect(self, s): + # type: (bytes) -> bytes + cls = self.guess_payload_class(s) + if cls and cls is not conf.raw_layer: + return s + return super().do_dissect(s) + + def guess_payload_class(self, payload): + # type: (bytes) -> Type[Packet] + cls = super().guess_payload_class(payload) + if cls and cls is not conf.raw_layer: + min_len = getattr(cls, "MIN_LEN", None) + if min_len is not None and len(payload) < min_len: + return conf.raw_layer + return cls + + def getfieldval(self, attr): + # type: (str) -> Any + if attr in ('priority', 'pgn', 'src', 'dst'): + return getattr(self, attr) + return super().getfieldval(attr) + + def getfield_and_val(self, attr): + # type: (str) -> Tuple[Any, Any] + if attr == 'data': + if 'data' in self.fields: + return self.fieldtype['data'], self.fields['data'] + if self.payload and not isinstance(self.payload, NoPayload): + return self.fieldtype['data'], bytes(self.payload) + return super().getfield_and_val(attr) + + def add_payload(self, payload): + # type: (Packet) -> None + super().add_payload(payload) + if self.pgn == 0: + payload_pgn = getattr(payload, "PGN", None) + if payload_pgn is not None: + self.pgn = payload_pgn def answers(self, other): # type: (Packet) -> int - if not isinstance(other, J1939): + other_j = other if isinstance(other, J1939) else other.getlayer(J1939) + other_req = other.getlayer(J1939Request) + if ( + other_j is None + and other_req is None + and not isinstance(other, J1939Request) + ): + return 0 + other_src = ( + getattr(other_j, "src", socket.J1939_NO_ADDR) + if other_j is not None + else getattr(other, "src", socket.J1939_NO_ADDR) + ) + other_dst = ( + getattr(other_j, "dst", socket.J1939_NO_ADDR) + if other_j is not None + else getattr(other, "dst", socket.J1939_NO_ADDR) + ) + # Responses cannot originate from the sender itself (echo/loopback) + if ( + other_src not in (socket.J1939_NO_ADDR, 0xFF) + and self.src == other_src + ): return 0 - return self.data == other.data + # Per (SA, DA) session tracking: directed requests must originate from other.dst + if other_dst not in (socket.J1939_NO_ADDR, 0xFF) and self.src != other_dst: + return 0 + # If both other.src and self.dst are unicast, verify session return address + if ( + other_src not in (socket.J1939_NO_ADDR, 0xFF) + and self.dst not in (socket.J1939_NO_ADDR, 0xFF) + and self.dst != other_src + ): + return 0 + # Extract target PGN for Request PGN (0xEA00 / 59904) matching + target_pgn = None # type: Optional[int] + other_req = other.getlayer(J1939Request) + if other_req is not None: + target_pgn = other_req.req_pgn + elif getattr(other, "req_pgn", None) is not None: + target_pgn = other.req_pgn + + if target_pgn is not None and self.pgn == target_pgn: + return 1 + + # Check explicit payload layer if present + if self.payload and not isinstance( + self.payload, (conf.raw_layer, conf.padding_layer) + ): + ans = self.payload.answers(other) + if not ans and other.payload: + ans = self.payload.answers(other.payload) + if type(self.payload).answers is not Packet.answers: + return ans + if ans: + return ans + + # Generic fallback heuristic: same PGN with swapped DA and SA + if (self.pgn == getattr(other, "pgn", None) and + self.src == other_dst and + self.dst == other_src and + self.src not in (socket.J1939_NO_ADDR, 0xFF) and + self.dst not in (socket.J1939_NO_ADDR, 0xFF)): + j1939_conf = conf.contribs.get('J1939', {}) + if j1939_conf.get( + 'generic-answers-fallback', + j1939_conf.get('generic_answers_fallback', True) + ): + return 1 + return 0 def mysummary(self): # type: () -> str @@ -298,6 +486,33 @@ def mysummary(self): ) +class J1939Request(Packet): + """J1939 Request frame (PGN 0xEA00 / 59904). + + Used to request a Parameter Group from a network node or broadcast. + + Example:: + + >>> req = J1939(pgn=0xEA00, dst=0x10) / J1939Request(req_pgn=0xFECA) + >>> bytes(req) + b'\xca\xfe\x00' + >>> pkt = J1939(bytes(req), pgn=0xEA00) + >>> pkt[J1939Request].req_pgn == 0xFECA + True + """ + + name = 'J1939Request' + PGN = J1939_PGN_REQUEST + MIN_LEN = 3 + + fields_desc = [ + XLE3BytesField('req_pgn', 0), + ] + + +bind_layers(J1939, J1939Request, pgn=J1939_PGN_REQUEST) + + # --------------------------------------------------------------------------- # J1939 CAN-frame-level packet # --------------------------------------------------------------------------- @@ -368,32 +583,87 @@ def pgn(self): # type: () -> int """PGN (Parameter Group Number) derived from ``data_page``, ``pdu_format``, and ``pdu_specific``.""" - return pgn_from_fields(self.data_page, self.pdu_format, self.pdu_specific) + return j1939_pgn_from_fields(self.data_page, self.pdu_format, self.pdu_specific) @property def dst(self): # type: () -> int """Destination address for PDU1 frames; :data:`socket.J1939_NO_ADDR` for PDU2.""" # noqa: E501 - return dst_from_fields(self.pdu_format, self.pdu_specific) + if self.pdu_format <= J1939_PDU1_MAX_PF: + return self.pdu_specific + return socket.J1939_NO_ADDR + + @property + def identifier(self): + # type: () -> int + """29-bit CAN arbitration identifier derived from J1939 sub-fields.""" + return j1939_to_can_id( + self.priority, + self.reserved, + self.data_page, + self.pdu_format, + self.pdu_specific, + self.src, + ) + + @identifier.setter + def identifier(self, val): + # type: (int) -> None + fields = can_id_to_j1939(val) + self.priority = fields["priority"] + self.reserved = fields["reserved"] + self.data_page = fields["data_page"] + self.pdu_format = fields["pdu_format"] + self.pdu_specific = fields["pdu_specific"] + self.src = fields["src"] def to_can(self): # type: () -> CAN - """Convert to a standard :class:`~scapy.layers.can.CAN` packet. + """Convert to a standard :class:`~scapy.layers.can.CAN` packet.""" + pkt_len = self.length + if pkt_len is None and self.payload: + pkt_len = len(self.payload) + pkt = CAN( + flags=self.flags, + identifier=self.identifier, + length=pkt_len, + reserved=self.reserved2, + data=self.data, + ) + pkt.time = self.time + if self.payload: + pkt.add_payload(self.payload.copy()) + return pkt - The wire bytes are identical so this is simply a class change. - """ - return CAN(bytes(self)) + def post_build(self, pkt, pay): + # type: (bytes, bytes) -> bytes + if self.length is None and pay: + pkt = pkt[:4] + struct.pack("B", len(pay)) + pkt[5:] + return super().post_build(pkt, pay) @classmethod def from_can(cls, pkt): # type: (CAN) -> J1939_CAN """Create a :class:`J1939_CAN` from a :class:`~scapy.layers.can.CAN` packet. - The wire bytes are identical so this is simply a class change. The packet timestamp is preserved from *pkt*. """ - result = cls(bytes(pkt)) + fields = can_id_to_j1939(pkt.identifier) + result = cls( + flags=pkt.flags, + priority=fields["priority"], + reserved=fields["reserved"], + data_page=fields["data_page"], + pdu_format=fields["pdu_format"], + pdu_specific=fields["pdu_specific"], + src=fields["src"], + length=pkt.length, + reserved2=pkt.reserved, + data=pkt.data, + ) result.time = pkt.time + if pkt.payload: + result.add_payload(pkt.payload.copy()) return result def mysummary(self): @@ -448,6 +718,15 @@ class J1939_TP_CM_RTS(Packet): XLE3BytesField('pgn', 0), # PGN of the message being transferred ] + def answers(self, other): + # type: (Packet) -> int + other_req = other.getlayer(J1939Request) + if other_req is not None: + return int(self.pgn == other_req.req_pgn) + if getattr(other, "req_pgn", None) is not None: + return int(self.pgn == other.req_pgn) + return 0 + class J1939_TP_CM_CTS(Packet): """J1939 TP Connection Management – Clear To Send (CTS). @@ -464,6 +743,13 @@ class J1939_TP_CM_CTS(Packet): XLE3BytesField('pgn', 0), # PGN of the message ] + def answers(self, other): + # type: (Packet) -> int + other_rts = other.getlayer(J1939_TP_CM_RTS) + if other_rts is not None: + return int(self.pgn == other_rts.pgn) + return 0 + class J1939_TP_CM_ACK(Packet): """J1939 TP Connection Management – End of Message Acknowledge (EoMAck). @@ -494,6 +780,15 @@ class J1939_TP_CM_BAM(Packet): XLE3BytesField('pgn', 0), # PGN of the message ] + def answers(self, other): + # type: (Packet) -> int + other_req = other.getlayer(J1939Request) + if other_req is not None: + return int(self.pgn == other_req.req_pgn) + if getattr(other, "req_pgn", None) is not None: + return int(self.pgn == other.req_pgn) + return 0 + class J1939_TP_CM_ABORT(Packet): """J1939 TP Connection Management – Connection Abort.""" @@ -506,6 +801,16 @@ class J1939_TP_CM_ABORT(Packet): XLE3BytesField('pgn', 0), # PGN of the aborted message ] + def answers(self, other): + # type: (Packet) -> int + other_rts = other.getlayer(J1939_TP_CM_RTS) + if other_rts is not None: + return int(self.pgn == other_rts.pgn) + other_cts = other.getlayer(J1939_TP_CM_CTS) + if other_cts is not None: + return int(self.pgn == other_cts.pgn) + return 0 + class J1939_TP_CM(Packet): """J1939 TP Connection Management frame dispatcher. @@ -554,6 +859,263 @@ class J1939_TP_DT(Packet): ] +J1939_ACK_CTRL = { + 0: 'ACK', + 1: 'NACK', + 2: 'Access Denied', + 3: 'Cannot Respond', +} + + +class J1939Ack(Packet): + """J1939 Acknowledgment frame (PGN 0xE800 / 59392; J1939-21 §5.4.4).""" + name = 'J1939Ack' + PGN = J1939_PGN_ACK + + fields_desc = [ + ByteEnumField('ctrl', 0, J1939_ACK_CTRL), + ByteField('group_func', 0xFF), + ShortField('reserved', 0xFFFF), + ByteField('address', 0xFF), + XLE3BytesField('pgn', 0), + ] + + def pre_dissect(self, s): + # type: (bytes) -> bytes + if 4 <= len(s) < 8: + return s[:1] + b'\xff\xff\xff\xff' + s[1:4] + if len(s) < 8: + return s + b'\xff' * (8 - len(s)) + return s + + def answers(self, other): + # type: (Packet) -> int + if not isinstance(other, Packet): + return 0 + + other_j = other if isinstance(other, J1939) else other.getlayer(J1939) + if isinstance(getattr(other, "underlayer", None), Packet): + outer_j = ( + other.underlayer + if isinstance(other.underlayer, J1939) + else other.underlayer.getlayer(J1939) + ) + if ( + outer_j is not None + and outer_j.src not in (None, socket.J1939_NO_ADDR, 0xFF) + ): + other_j = outer_j + + other_src = ( + other_j.src + if other_j is not None + else getattr(other, "src", socket.J1939_NO_ADDR) + ) + if ( + self.address not in (None, 0xFF) + and other_src not in (None, socket.J1939_NO_ADDR, 0xFF) + and self.address != other_src + ): + return 0 + + target_pgn = None # type: Optional[int] + other_req = other.getlayer(J1939Request) + other_rts = other.getlayer(J1939_TP_CM_RTS) + if other_req is not None: + target_pgn = other_req.req_pgn + elif other_rts is not None: + target_pgn = other_rts.pgn + elif getattr(other, "req_pgn", None) is not None: + target_pgn = other.req_pgn + elif other_j is not None and other_j.dst not in (socket.J1939_NO_ADDR, 0xFF): + target_pgn = other_j.pgn + + if target_pgn is not None and self.pgn == target_pgn: + return 1 + return 0 + + +bind_layers(J1939, J1939_TP_CM, pgn=0xEC00) +bind_layers(J1939, J1939Ack, pgn=0xE800) + + +class _J1939DiagBase(Packet): + fields_desc = [ + StrField("data", b""), + ] + + def _extract_uds(self): + # type: () -> Optional[Packet] + uds = self.getlayer(UDS) + if uds is not None: + return uds + if self.payload and not isinstance( + self.payload, (conf.raw_layer, conf.padding_layer) + ): + if ( + hasattr(self.payload, "service") + or "UDS" in type(self.payload).__name__ + ): + return self.payload + data = bytes(self.payload) + else: + data = getattr(self, "data", None) + if not data and self.payload: + data = bytes(self.payload) + + if not isinstance(data, (bytes, bytearray)) or not data: + return None + + if 1 <= data[0] <= 7 and len(data) > 1 and data[0] <= len(data) - 1: + uds_bytes = data[1:1 + data[0]] + else: + uds_bytes = data + try: + return UDS(uds_bytes) + except Exception: + return None + + def answers(self, other): + # type: (Packet) -> int + if not isinstance(other, Packet): + return 0 + + self_j = ( + self.underlayer + if isinstance(getattr(self, "underlayer", None), J1939) + else self.getlayer(J1939) + ) + other_j = ( + other + if isinstance(other, J1939) + else ( + other.getlayer(J1939) + or ( + other.underlayer + if isinstance(getattr(other, "underlayer", None), J1939) + else None + ) + ) + ) + + if self_j is not None and other_j is not None: + self_src = getattr(self_j, "src", socket.J1939_NO_ADDR) + self_dst = getattr(self_j, "dst", socket.J1939_NO_ADDR) + other_src = getattr(other_j, "src", socket.J1939_NO_ADDR) + other_dst = getattr(other_j, "dst", socket.J1939_NO_ADDR) + + # Responses cannot originate from the sender itself (echo/loopback) + if ( + other_src not in (socket.J1939_NO_ADDR, 0xFF) + and self_src == other_src + ): + return 0 + + # Directed request: response must originate from the requested node + if ( + other_dst not in (socket.J1939_NO_ADDR, 0xFF) + and self_src not in (socket.J1939_NO_ADDR, 0xFF) + and self_src != other_dst + ): + return 0 + + # Verify session return address + if ( + other_src not in (socket.J1939_NO_ADDR, 0xFF) + and self_dst not in (socket.J1939_NO_ADDR, 0xFF) + and self_dst != other_src + ): + return 0 + + other_req = other.getlayer(J1939Request) + if other_req is not None: + if getattr(self, "PGN", None) == J1939_PGN_DIAG_A: + return int( + other_req.req_pgn in (J1939_PGN_DIAG_A, J1939_PGN_DIAG_B) + ) + return int(other_req.req_pgn == getattr(self, "PGN", None)) + + other_diag = ( + other + if isinstance(other, _J1939DiagBase) + else ( + other.getlayer(_J1939DiagBase) + or other.getlayer(J1939DiagA) + or other.getlayer(J1939DiagB) + ) + ) + other_uds = None + if other_diag is not None: + other_uds = ( + other_diag._extract_uds() + if hasattr(other_diag, "_extract_uds") + else None + ) + if other_uds is None and hasattr(other_diag, "getlayer"): + other_uds = other_diag.getlayer(UDS) + elif other_j is not None and other_j.pgn in ( + J1939_PGN_DIAG_A, J1939_PGN_DIAG_B + ): + j_data = getattr(other_j, "data", None) or ( + bytes(other_j.payload) if other_j.payload else b"" + ) + if j_data: + if ( + 1 <= j_data[0] <= 7 + and len(j_data) > 1 + and j_data[0] <= len(j_data) - 1 + ): + uds_bytes = j_data[1:1 + j_data[0]] + else: + uds_bytes = j_data + try: + other_uds = UDS(uds_bytes) + except Exception: + other_uds = None + else: + other_uds = other.getlayer(UDS) + + if other_diag is not None or other_uds is not None: + self_uds = self._extract_uds() + if self_uds is not None and other_uds is not None: + return int(bool(self_uds.answers(other_uds))) + self_data = ( + self.data + if isinstance(getattr(self, "data", None), (bytes, bytearray)) + else (bytes(self.payload) if self.payload else b"") + ) + other_data = ( + getattr(other_diag, "data", None) + if other_diag is not None + else getattr(other_j, "data", None) + ) or b"" + return int(not self_data and not other_data) + + other_j = other if isinstance(other, J1939) else other.getlayer(J1939) + if other_j is not None and other_j.pgn in ( + J1939_PGN_DIAG_A, J1939_PGN_DIAG_B + ): + return 1 + + return 0 + + +class J1939DiagA(_J1939DiagBase): + """J1939 Diagnostic A – Physical Diagnostic (PGN 0xDA00 = 55808).""" + name = "J1939DiagA" + PGN = J1939_PGN_DIAG_A + + +class J1939DiagB(_J1939DiagBase): + """J1939 Diagnostic B – Functional Diagnostic (PGN 0xDB00 = 56064).""" + name = "J1939DiagB" + PGN = J1939_PGN_DIAG_B + + +bind_layers(J1939, J1939DiagA, pgn=J1939_PGN_DIAG_A) +bind_layers(J1939, J1939DiagB, pgn=J1939_PGN_DIAG_B) + + # --------------------------------------------------------------------------- # NativeJ1939Socket # --------------------------------------------------------------------------- @@ -793,15 +1355,18 @@ def send(self, x): # Extract payload bytes if isinstance(x, J1939): - data = x.data if isinstance(x.data, bytes) else raw(x) + x_data = getattr(x, "data", None) + data = x_data if isinstance(x_data, bytes) else raw(x) dst_pgn = x.pgn if x.pgn != 0 else socket.J1939_NO_PGN dst_addr = x.dst priority = x.priority else: data = raw(x) - dst_pgn = socket.J1939_NO_PGN - dst_addr = socket.J1939_NO_ADDR - priority = 6 + dst_pgn = getattr(x, "PGN", getattr(x, "pgn", socket.J1939_NO_PGN)) + if dst_pgn == 0: + dst_pgn = socket.J1939_NO_PGN + dst_addr = getattr(x, "dst", socket.J1939_NO_ADDR) + priority = getattr(x, "priority", 6) # Set per-message priority try: @@ -943,7 +1508,10 @@ def __init__( listen_only=False, # type: bool pgn_filter=socket.J1939_NO_PGN, # type: int basecls=None, # type: Optional[Type[Packet]] + promisc=False, # type: bool + include_tp_cm=False, # type: bool ): + # type: (...) -> None from scapy.contrib.isotp.isotp_soft_socket import TimeoutScheduler self._TimeoutScheduler = TimeoutScheduler @@ -953,11 +1521,14 @@ def __init__( self.listen_only = listen_only self.pgn_filter = pgn_filter self.basecls = basecls or J1939 # type: Type[Packet] + self.promisc = promisc + self.include_tp_cm = include_tp_cm self.closed = False self.closing = False self.rx_tx_poll_rate = 0.005 # ── receive path ────────────────────────────────────────────────────── + # In-progress receptions, keyed by (source address, destination). self.rx_sessions = {} # type: Dict[Tuple[int, int], _J1939_RXSession] @@ -1060,7 +1631,8 @@ def close(self, timeout=None): if timeout is None: timeout = self.drain_timeout() deadline = time.monotonic() + timeout - while time.monotonic() < deadline: + hard_deadline = time.monotonic() + max(timeout * 3, 10.0) + while time.monotonic() < min(deadline, hard_deadline): tx_pending = bool(select_objects([self.tx_queue], 0)) if (self.tx_state == _J1939_TX_IDLE and not tx_pending and @@ -1188,7 +1760,7 @@ def on_can_recv(self, pkt): # ── Short (≤ 8-byte) data frame ────────────────────────────────────── # PDU1: ps is the destination address. PDU2: always broadcast. if pf <= J1939_PDU1_MAX_PF: - if ps != self.src_addr and ps != socket.J1939_NO_ADDR: + if not self.promisc and ps != self.src_addr and ps != socket.J1939_NO_ADDR: return self._on_short_frame(j) @@ -1225,8 +1797,13 @@ def _on_tp_cm(self, j): total=bam.total_size, npkts=bam.num_packets, max_packets=bam.num_packets, is_bam=True, ts=ts, priority=j.priority) + if self.include_tp_cm: + msg = self.basecls(data, pgn=j.pgn, src=j.src, dst=j.dst, + priority=j.priority) + self.rx_queue.send((msg, j.time)) elif ctrl == J1939_TP_CTRL_RTS: + # RTS is directed; broadcast RTS must not start a session or CTS. if j.dst != self.src_addr: return @@ -1239,6 +1816,10 @@ def _on_tp_cm(self, j): total=rts.total_size, npkts=rts.num_packets, max_packets=rts.max_packets, is_bam=False, ts=ts, priority=j.priority) + if self.include_tp_cm: + msg = self.basecls(data, pgn=j.pgn, src=j.src, dst=j.dst, + priority=j.priority) + self.rx_queue.send((msg, j.time)) elif ctrl == J1939_TP_CTRL_CTS: if j.dst != self.src_addr: @@ -1249,6 +1830,10 @@ def _on_tp_cm(self, j): if (self.tx_state == _J1939_TX_RTS_WAIT_CTS and sa == self.tx_peer_sa and cts.pgn == self.tx_pgn): self._tx_handle_cts(cts) + else: + msg = self.basecls(data, pgn=j.pgn, src=j.src, dst=j.dst, + priority=j.priority) + self.rx_queue.send((msg, j.time)) elif ctrl == J1939_TP_CTRL_ACK: if j.dst != self.src_addr: @@ -1272,6 +1857,7 @@ def _on_tp_cm(self, j): if j.dst != self.src_addr: return abort = J1939_TP_CM_ABORT(data) if len(data) >= 8 else None + aborted = False # Only the peer of a session actually in progress may abort it, # and only for the PGN being transferred: an address left over # from an earlier session must not tear down the current one. @@ -1281,13 +1867,20 @@ def _on_tp_cm(self, j): "J1939 TP: TX session aborted by peer (reason %d)", abort.reason) self._tx_reset() + aborted = True # A peer may equally abort a reception it started. session = self.rx_sessions.get((sa, self.src_addr)) if session is not None and abort is not None and \ abort.pgn == session.pgn: self._rx_drop(session, "aborted by peer") + aborted = True + if not aborted: + msg = self.basecls(data, pgn=j.pgn, src=j.src, dst=j.dst, + priority=j.priority) + self.rx_queue.send((msg, j.time)) def _on_tp_dt(self, j): + # type: (J1939_CAN) -> None sa = j.src session = self.rx_sessions.get((sa, j.pdu_specific)) @@ -1524,7 +2117,9 @@ def _payload_of(msg): # type: (Packet) -> bytes """The bytes *msg* puts on the bus, however it was constructed.""" if isinstance(msg, J1939): - data = msg.data + if msg.payload: + return bytes(msg) + data = getattr(msg, "data", None) if not isinstance(data, (bytes, bytearray)): data = bytes(msg) return bytes(data) @@ -1539,9 +2134,9 @@ def _begin_send(self, msg): dst = msg.dst priority = msg.priority else: - pgn = 0 - dst = socket.J1939_NO_ADDR - priority = 6 + pgn = getattr(msg, "PGN", getattr(msg, "pgn", 0)) + dst = getattr(msg, "dst", socket.J1939_NO_ADDR) + priority = getattr(msg, "priority", 6) data_page = (pgn >> 16) & 0x1 pf = (pgn >> 8) & 0xFF @@ -1552,14 +2147,21 @@ def _begin_send(self, msg): ps = dst & 0xFF else: ps = pgn & 0xFF + msg_src = getattr(msg, "src", socket.J1939_NO_ADDR) + src = ( + msg_src + if msg_src != socket.J1939_NO_ADDR + else self.src_addr + ) pkt = J1939_CAN( priority=priority, data_page=data_page, pdu_format=pf, pdu_specific=ps, - src=self.src_addr, data=data, + src=src, data=data, ) self._can_send(pkt) elif dst == socket.J1939_NO_ADDR: + # Broadcast multi-packet message via BAM. self._tx_start_bam(data, pgn, dst, priority) @@ -1815,7 +2417,10 @@ def __init__( basecls=J1939, # type: Type[Packet] listen_only=False, # type: bool pgn=socket.J1939_NO_PGN, # type: int + promisc=False, # type: bool + include_tp_cm=False, # type: bool ): + # type: (...) -> None if LINUX and isinstance(can_socket, str): from scapy.contrib.cansocket_native import NativeCANSocket @@ -1834,8 +2439,12 @@ def __init__( listen_only=listen_only, pgn_filter=pgn, basecls=self.basecls, + promisc=promisc, + include_tp_cm=include_tp_cm, ) + # Cast so SuperSocket internals are satisfied (recv/send are overridden). + self.ins = cast(socket.socket, impl) self.outs = cast(socket.socket, impl) self.impl = impl @@ -1963,3 +2572,79 @@ def select(sockets, remain=None): # type: ignore[override] if isinstance(x, ObjectPipe) and x in ready_pipes ] return result # type: ignore[return-value] + + +# --------------------------------------------------------------------------- +# J1939Socket selection +# --------------------------------------------------------------------------- + +if LINUX: + try: + if conf.contribs['J1939']['use-can-j1939-kernel-module']: + pass + except KeyError: + log_loading.info( + "Specify 'conf.contribs['J1939'] = {'use-can-j1939-kernel-module': True}' " # noqa: E501 + "to enable usage of can-j1939 kernel module." + ) + + +def J1939Socket(*args, **kwargs): + # type: (*Any, **Any) -> Union[NativeJ1939Socket, J1939SoftSocket] + """Create a J1939 socket. + + Dispatches to :class:`NativeJ1939Socket` if running on Linux and configured + via ``conf.contribs['J1939']['use-can-j1939-kernel-module'] = True``; + otherwise dispatches to :class:`J1939SoftSocket`. + """ + if LINUX and conf.contribs.get('J1939', {}).get( + 'use-can-j1939-kernel-module', False + ): + return NativeJ1939Socket(*args, **kwargs) + return J1939SoftSocket(*args, **kwargs) + + +__all__ = [ + "J1939", + "J1939Ack", + "J1939DiagA", + "J1939DiagB", + "J1939Request", + "J1939Socket", + "J1939SoftSocket", + "J1939TPImplementation", + "J1939_ACK_CTRL", + "J1939_ADDR_NAMES", + "J1939_BROADCAST_ADDR", + "J1939_CAN", + "J1939_GLOBAL_ADDRESS", + "J1939_NULL_ADDRESS", + "J1939_PDU1_MAX_PF", + "J1939_PGN_ACK", + "J1939_PGN_ADDRESS_CLAIMED", + "J1939_PGN_ADDRESS_COMMANDED", + "J1939_PGN_DIAG_A", + "J1939_PGN_DIAG_B", + "J1939_PGN_REQUEST", + "J1939_PGN_TP_CM", + "J1939_PGN_TP_DT", + "J1939_TP_CM", + "J1939_TP_CM_ABORT", + "J1939_TP_CM_ACK", + "J1939_TP_CM_BAM", + "J1939_TP_CM_CTS", + "J1939_TP_CM_RTS", + "J1939_TP_CTRL_ABORT", + "J1939_TP_CTRL_ACK", + "J1939_TP_CTRL_BAM", + "J1939_TP_CTRL_CTS", + "J1939_TP_CTRL_RTS", + "J1939_TP_DT", + "NativeJ1939Socket", + "SOL_CAN_BASE", + "can_id_to_j1939", + "j1939_pgn_from_fields", + "j1939_to_can_id", + "log_j1939", + "pgn_is_pdu1", +] diff --git a/scapy/layers/can.py b/scapy/layers/can.py index 9453eeca910..32ada241b5d 100644 --- a/scapy/layers/can.py +++ b/scapy/layers/can.py @@ -14,6 +14,7 @@ import os import gzip +import socket import struct from scapy.config import conf @@ -43,19 +44,44 @@ cast, ) -__all__ = ["CAN", "SignalPacket", "SignalField", "LESignedSignalField", - "LEUnsignedSignalField", "LEFloatSignalField", "BEFloatSignalField", - "BESignedSignalField", "BEUnsignedSignalField", "rdcandump", - "CandumpReader", "SignalHeader", "CAN_MTU", "CAN_MAX_IDENTIFIER", - "CAN_MAX_DLEN", "CAN_INV_FILTER", "CANFD", "CAN_FD_MTU", - "CAN_FD_MAX_DLEN", "CANXL", "CANXL_MTU", "CANXL_MAX_DLEN", - "CANXL_MIN_DLEN", "CANXL_HDR_SIZE", "CANXL_XLF", "CANXL_FDF", - "CANXL_IDE", "CANXL_SEC", "CANXL_RRS"] +__all__ = [ + "BEFloatSignalField", + "BESignedSignalField", + "BEUnsignedSignalField", + "CAN", + "CANFD", + "CANXL", + "CANXL_FDF", + "CANXL_HDR_SIZE", + "CANXL_IDE", + "CANXL_MAX_DLEN", + "CANXL_MIN_DLEN", + "CANXL_MTU", + "CANXL_RRS", + "CANXL_SEC", + "CANXL_XLF", + "CAN_EFF_FLAG", + "CAN_FD_MAX_DLEN", + "CAN_FD_MTU", + "CAN_INV_FILTER", + "CAN_MAX_DLEN", + "CAN_MAX_IDENTIFIER", + "CAN_MTU", + "CandumpReader", + "LEFloatSignalField", + "LESignedSignalField", + "LEUnsignedSignalField", + "SignalField", + "SignalHeader", + "SignalPacket", + "rdcandump", +] # CONSTANTS CAN_MAX_IDENTIFIER = (1 << 29) - 1 # Maximum 29-bit identifier CAN_MTU = 16 CAN_MAX_DLEN = 8 +CAN_EFF_FLAG = getattr(socket, "CAN_EFF_FLAG", 0x80000000) CAN_INV_FILTER = 0x20000000 CAN_FD_MTU = 72 CAN_FD_MAX_DLEN = 64 diff --git a/test/contrib/automotive/j1939_dm.uts b/test/contrib/automotive/j1939_dm.uts new file mode 100644 index 00000000000..da46724e0ab --- /dev/null +++ b/test/contrib/automotive/j1939_dm.uts @@ -0,0 +1,404 @@ +% Regression tests for J1939 Diagnostic Messages (DM1, DM13, DM14) +~ automotive_comm + ++ Configuration +~ conf + += Imports +from scapy.layers.can import CAN +from scapy.contrib.j1939 import ( + J1939, J1939SoftSocket, J1939_GLOBAL_ADDRESS, +) +from scapy.contrib.automotive.j1939.j1939_dm import ( + J1939Dm1, J1939Dm13, J1939Dm14, J1939Dtc, + J1939_PGN_DM1, J1939_PGN_DM13, J1939_PGN_DM14, +) +from scapy.error import Scapy_Exception +from test.testsocket import TestSocket, cleanup_testsockets + += Redirect logging +import logging +from scapy.error import log_runtime +from io import StringIO +log_stream = StringIO() +handler = logging.StreamHandler(log_stream) +log_runtime.addHandler(handler) + + ++ J1939Dtc — Bit-boundary and packing tests + += DTC size is exactly 4 bytes (bit-boundary checkpoint) +assert len(J1939Dtc()) == 4, \ + "J1939Dtc must be exactly 4 bytes (32 bits); got {}".format(len(J1939Dtc())) + += DTC packing: known raw bytes produce correct field values +# SPN=100 (0x64), FMI=2, CM=0, OC=5 +# LE bytes: [SPN[7:0], SPN[15:8], FMI|SPN[18:16], OC|CM] +# = [0x64, 0x00, 0x10, 0x0A] +raw = b'\x64\x00\x10\x0a' +dtc = J1939Dtc(raw) +assert dtc.SPN == 100, "SPN: expected 100, got {}".format(dtc.SPN) +assert dtc.FMI == 2, "FMI: expected 2, got {}".format(dtc.FMI) +assert dtc.CM == 0, "CM: expected 0, got {}".format(dtc.CM) +assert dtc.OC == 5, "OC: expected 5, got {}".format(dtc.OC) + += DTC unpacking: field values produce correct raw bytes +dtc = J1939Dtc(SPN=100, FMI=2, CM=0, OC=5) +assert bytes(dtc) == b'\x64\x00\x10\x0a', \ + "Expected 64 00 10 0a, got {}".format(bytes(dtc).hex()) + += DTC round-trip: build then parse recovers all fields +for spn, fmi, cm, oc in [ + (100, 2, 0, 5), + (0x7FFFF, 0x1F, 1, 0x7F), # all-ones (max values) + (0, 0, 0, 0), # all-zeros (min values) + (512, 7, 0, 10), +]: + built = bytes(J1939Dtc(SPN=spn, FMI=fmi, CM=cm, OC=oc)) + parsed = J1939Dtc(built) + assert parsed.SPN == spn, "SPN round-trip failed: {} != {}".format(parsed.SPN, spn) + assert parsed.FMI == fmi, "FMI round-trip failed: {} != {}".format(parsed.FMI, fmi) + assert parsed.CM == cm, "CM round-trip failed: {} != {}".format(parsed.CM, cm) + assert parsed.OC == oc, "OC round-trip failed: {} != {}".format(parsed.OC, oc) + += DTC: little-endian byte order is correct (SPN LSB in byte 0) +dtc = J1939Dtc(SPN=0x100, FMI=0, CM=0, OC=0) +raw = bytes(dtc) +# SPN=0x100=256: byte0=0x00 (SPN[7:0]), byte1=0x01 (SPN[15:8]), rest=0x00 +assert raw[0] == 0x00, "byte0 should be SPN[7:0]=0x00, got 0x{:02X}".format(raw[0]) +assert raw[1] == 0x01, "byte1 should be SPN[15:8]=0x01, got 0x{:02X}".format(raw[1]) + + ++ J1939Dm1 — Single-frame tests + += DM1 PGN is 65226 (0xFECA) +assert J1939Dm1.PGN == 65226, "PGN: {}".format(J1939Dm1.PGN) +assert J1939_PGN_DM1 == 65226 + += DM1 single-frame: 1 DTC produces 6 bytes (2 lamp + 4 DTC) +dtc = J1939Dtc(SPN=100, FMI=2, CM=0, OC=5) +dm1 = J1939Dm1(dtcs=[dtc]) +raw = bytes(dm1) +assert len(raw) == 6, \ + "DM1 with 1 DTC must be 6 bytes; got {}".format(len(raw)) + += DM1 single-frame: lamp status fields are parsed correctly +dm1 = J1939Dm1( + mil_status=1, rsl_status=0, awl_status=0, pl_status=0, + dtcs=[J1939Dtc(SPN=100, FMI=2, CM=0, OC=5)], +) +assert dm1.mil_status == 1, "MIL: expected 1, got {}".format(dm1.mil_status) +assert dm1.rsl_status == 0, "RSL: expected 0, got {}".format(dm1.rsl_status) +assert dm1.awl_status == 0, "AWL: expected 0, got {}".format(dm1.awl_status) +assert dm1.pl_status == 0, "PL: expected 0, got {}".format(dm1.pl_status) + + ++ J1939Dm1 — Multi-frame tests + += DM1 multi-frame: 5 DTCs produce 22 bytes (no padding) +dtcs = [J1939Dtc(SPN=i * 100, FMI=2, CM=0, OC=1) for i in range(5)] +dm1 = J1939Dm1(dtcs=dtcs) +raw = bytes(dm1) +assert len(raw) == 22, \ + "DM1 with 5 DTCs must be 22 bytes; got {}".format(len(raw)) + += DM1 multi-frame: payload is not truncated +dtcs = [J1939Dtc(SPN=i * 100, FMI=2, CM=0, OC=1) for i in range(5)] +dm1 = J1939Dm1(dtcs=dtcs) +raw = bytes(dm1) +# Verify each DTC survives the round-trip through the raw byte string +parsed = J1939Dm1(raw) +assert len(parsed.dtcs) == 5, \ + "Expected 5 DTCs after dissection, got {}".format(len(parsed.dtcs)) +for i, dtc in enumerate(parsed.dtcs): + assert dtc.SPN == i * 100, \ + "DTC[{}] SPN: expected {}, got {}".format(i, i * 100, dtc.SPN) + + ++ J1939Dm1 — Dissection round-trip tests + += DM1 dissection round-trip with 2 DTCs preserves lamp status and DTC values +dtcs_in = [ + J1939Dtc(SPN=100, FMI=2, CM=0, OC=5), + J1939Dtc(SPN=200, FMI=3, CM=1, OC=10), +] +dm1_orig = J1939Dm1(mil_status=1, awl_status=1, dtcs=dtcs_in) +raw = bytes(dm1_orig) +dm1_p = J1939Dm1(raw) +assert dm1_p.mil_status == 1, "mil_status: {}".format(dm1_p.mil_status) +assert dm1_p.awl_status == 1, "awl_status: {}".format(dm1_p.awl_status) +assert len(dm1_p.dtcs) == 2 +assert dm1_p.dtcs[0].SPN == 100 +assert dm1_p.dtcs[1].SPN == 200 +assert dm1_p.dtcs[1].CM == 1 + += DM1 dissection: trailing 0xFF padding bytes are not parsed as DTCs +dtc = J1939Dtc(SPN=100, FMI=2, CM=0, OC=5) +dm1 = J1939Dm1(dtcs=[dtc]) +raw = bytes(dm1) + b"\xff\xff" # 8 bytes: 2 lamp + 4 DTC + 2 padding +dm1_p = J1939Dm1(raw) +assert len(dm1_p.dtcs) == 1, \ + "Expected 1 DTC (not 2), got {}".format(len(dm1_p.dtcs)) + += DM1 does not overwrite repr +assert "__repr__" not in J1939Dm1.__dict__ + += DM1 does not overwrite post_build +assert "post_build" not in J1939Dm1.__dict__ + += DM1 does not overwrite do_build +assert "do_build" not in J1939Dm1.__dict__ + + + ++ J1939Dm13 — Creation and PGN tests + += DM13 PGN is 57088 (0xDF00) +assert J1939Dm13.PGN == 57088, "PGN: {}".format(J1939Dm13.PGN) +assert J1939_PGN_DM13 == 57088 + += DM13 instantiation with default values +dm13 = J1939Dm13() +assert dm13.PGN == 57088 +assert dm13.hold_signal == 0xFF + += DM13 instantiation with custom hold_signal +dm13 = J1939Dm13(hold_signal=0xFE) +assert dm13.hold_signal == 0xFE + += DM13 with dummy payload data (8 bytes total) +dm13 = J1939Dm13(hold_signal=0xFF, data=b'\xfe\xff\xff\xff\xff\xff\xff') +assert len(bytes(dm13)) == 8 + += DM13 _hold_signal_enum is unused and removed +assert not hasattr(J1939Dm13, "_hold_signal_enum") + + ++ J1939Dm14 — Creation and PGN tests + += DM14 PGN is 55552 (0xD900) +assert J1939Dm14.PGN == 55552, "PGN: {}".format(J1939Dm14.PGN) +assert J1939_PGN_DM14 == 55552 + += DM14 size is exactly 8 bytes +assert len(J1939Dm14()) == 8, \ + "J1939Dm14 must be 8 bytes; got {}".format(len(J1939Dm14())) + += DM14 instantiation with dummy data verifies PGN default +dm14 = J1939Dm14(address=0x1000, length=4, command_type=1) +assert dm14.PGN == 55552 +assert dm14.address == 0x1000 +assert dm14.length == 4 +assert dm14.command_type == 1 + += DM14 command_type field values +dm14_read = J1939Dm14(command_type=1) +dm14_write = J1939Dm14(command_type=2) +dm14_erase = J1939Dm14(command_type=0) +assert dm14_read.command_type == 1 +assert dm14_write.command_type == 2 +assert dm14_erase.command_type == 0 + += DM14 address is stored in little-endian byte order +dm14 = J1939Dm14(address=0x00001234) +raw = bytes(dm14) +# XLEIntField: byte1=0x34, byte2=0x12, byte3=0x00, byte4=0x00 +assert raw[1] == 0x34, "LE address byte1=0x{:02X}".format(raw[1]) +assert raw[2] == 0x12, "LE address byte2=0x{:02X}".format(raw[2]) + + ++ Socket integration — DM routing via J1939 base class + += Socket integration: wrap DM1 in J1939 frame then re-dissect +# Build a DM1 payload, wrap in a J1939 frame, and verify the +# DM1 Scapy class correctly dissects the payload. +dtc = J1939Dtc(SPN=100, FMI=2, CM=0, OC=5) +dm1_orig = J1939Dm1(mil_status=1, dtcs=[dtc]) +j1939_frame = J1939(pgn=J1939_PGN_DM1, data=bytes(dm1_orig)) +# Dissect payload into DM1 class +dm1_parsed = J1939Dm1(j1939_frame.data) +assert dm1_parsed.mil_status == 1 +assert len(dm1_parsed.dtcs) == 1 +assert dm1_parsed.dtcs[0].SPN == 100 + += Socket integration: receive DM1 via J1939SoftSocket +from scapy.contrib.j1939 import j1939_to_can_id + +# Build DM1 payload +dtc = J1939Dtc(SPN=100, FMI=2, CM=0, OC=5) +dm1_data = bytes(J1939Dm1(mil_status=1, dtcs=[dtc])) + +# PGN 0xFECA: PF=0xFE >= 0xF0 (PDU2), PS=0xCA, SA=0x80 +can_id = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x80) + +with J1939SoftSocket(TestSocket(CAN), pgn=0xFECA, src_addr=0x11) as s: + # Inject CAN frame directly (bypasses background polling thread) + s.impl.on_can_recv( + CAN(identifier=can_id, flags="extended", data=dm1_data) + ) + result = s.impl.rx_queue.recv() + +assert result is not None, "rx_queue.recv() returned None" +msg, _ts = result +dm1_rx = J1939Dm1(bytes(msg.data)) +assert dm1_rx.mil_status == 1, "mil_status: {}".format(dm1_rx.mil_status) +assert len(dm1_rx.dtcs) == 1 +assert dm1_rx.dtcs[0].SPN == 100 +cleanup_testsockets() + + ++ J1939Dm1 and J1939Dm14 transmission and reception tests + += J1939Dm1 transmitted and received over J1939SoftSocket +with TestSocket(CAN) as cans1, TestSocket(CAN) as cans2: + cans1.pair(cans2) + with J1939SoftSocket(cans1, src_addr=0xFA) as tx_sock, \ + J1939SoftSocket(cans2, src_addr=0x20) as rx_sock: + dtc = J1939Dtc(SPN=100, FMI=2, CM=0, OC=5) + dm1_pkt = J1939Dm1(mil_status=1, dtcs=[dtc]) + tx_sock.send(J1939(data=bytes(dm1_pkt), pgn=J1939_PGN_DM1, dst=0x20)) + pkts = rx_sock.sniff(count=1, timeout=2) + +assert len(pkts) == 1 +recvd = pkts[0] +assert recvd.pgn == J1939_PGN_DM1 +recvd_dm1 = J1939Dm1(bytes(recvd.data)) +assert recvd_dm1.mil_status == 1 +assert recvd_dm1.dtcs[0].SPN == 100 +cleanup_testsockets() + += J1939Dm14 transmitted and received over J1939SoftSocket +with TestSocket(CAN) as cans1, TestSocket(CAN) as cans2: + cans1.pair(cans2) + with J1939SoftSocket(cans1, src_addr=0xFA) as tx_sock, \ + J1939SoftSocket(cans2, src_addr=0x20) as rx_sock: + dm14 = J1939Dm14(address=0x12345678, length=4) + tx_sock.send(J1939(data=bytes(dm14), pgn=J1939_PGN_DM14, dst=0x20)) + pkts = rx_sock.sniff(count=1, timeout=2) + +assert len(pkts) == 1 +recvd = pkts[0] +assert recvd.pgn == J1939_PGN_DM14 +dm14_payload = J1939Dm14(bytes(recvd.data)) +assert dm14_payload.address == 0x12345678 +assert dm14_payload.length == 4 +cleanup_testsockets() + += J1939-73 layers payload dissection and stacking +from scapy.packet import Raw +from scapy.contrib.automotive.j1939.j1939_dm import ( + J1939Dm1, J1939Dm13, J1939Dm14, J1939Dm15, J1939Dtc, +) + +# J1939Dtc treats subsequent bytes as padding (for PacketListField dissection) +dtc_raw = J1939Dtc(bytes(J1939Dtc()) + b"payload") +assert not dtc_raw.haslayer(Raw) +assert dtc_raw.extract_padding(b"payload") == (b"", b"payload") + +# J1939Dm13 preserves payload +dm13_raw = J1939Dm13(b"\xff" * 8 + b"trailing") +assert dm13_raw.haslayer(Raw) +assert dm13_raw[Raw].load == b"trailing" + +# J1939Dm14 preserves payload +dm14_raw = J1939Dm14(bytes(J1939Dm14()) + b"trailing_dm14") +assert dm14_raw.haslayer(Raw) +assert dm14_raw[Raw].load == b"trailing_dm14" + +# J1939Dm15 preserves payload +dm15_raw = J1939Dm15(bytes(J1939Dm15()) + b"trailing_dm15") +assert dm15_raw.haslayer(Raw) +assert dm15_raw[Raw].load == b"trailing_dm15" + +# J1939Dm1 preserves payload after DTCs +dm1_raw = J1939Dm1(bytes(J1939Dm1()) + b"pad") +assert dm1_raw.haslayer(Raw) +assert bytes(dm1_raw[Raw]) == b"pad" + ++ J1939Dm15 — Creation, PGN and answers() tests + += J1939Dm15 structure, PGN and fields +from scapy.contrib.automotive.j1939.j1939_dm import ( + J1939Dm14, J1939Dm15, J1939_PGN_DM14, J1939_PGN_DM15, +) +assert J1939Dm15.PGN == 0xD800 +assert len(J1939Dm15()) == 8 +dm15 = J1939Dm15(status=0, address=0x12345678, length=4) +assert dm15.status == 0 +assert dm15.address == 0x12345678 +assert dm15.length == 4 + += J1939Dm15 packing and unpacking +raw_dm15 = bytes(dm15) +parsed_dm15 = J1939Dm15(raw_dm15) +assert parsed_dm15.address == 0x12345678 +assert parsed_dm15.length == 4 + += J1939Dm15 answers() correlation +dm14 = J1939Dm14(address=0x12345678, length=4) +assert dm15.answers(dm14) == 1 +assert not dm14.answers(dm15) + +from scapy.contrib.j1939 import J1939 +req_dm14 = J1939(pgn=J1939_PGN_DM14, src=0x10, dst=0x20) / dm14 +resp_dm15 = J1939(pgn=J1939_PGN_DM15, src=0x20, dst=0x10) / dm15 +assert resp_dm15.answers(req_dm14) == 1 + +# Mismatched responder SA +resp_bad_sa = J1939(pgn=J1939_PGN_DM15, src=0x30, dst=0x10) / dm15 +assert resp_bad_sa.answers(req_dm14) == 0 + +# Mismatched address +dm14_bad_addr = J1939Dm14(address=0x87654321, length=4) +assert dm15.answers(dm14_bad_addr) == 0 + +# Mismatched length +dm14_bad_len = J1939Dm14(address=0x12345678, length=8) +assert dm15.answers(dm14_bad_len) == 0 + +# Dissected J1939 wire frame with PGN DM14 matching address/length +req_raw_dm14 = J1939(bytes(dm14), pgn=J1939_PGN_DM14, src=0x10, dst=0x20) +assert resp_dm15.answers(req_raw_dm14) == 1 + +# Dissected J1939 wire frame with PGN DM14 but mismatched address +req_raw_bad_addr = J1939(bytes(dm14_bad_addr), pgn=J1939_PGN_DM14, src=0x10, dst=0x20) +assert resp_dm15.answers(req_raw_bad_addr) == 0 + +# Dissected J1939 wire frame with PGN DM14 but mismatched SA +req_raw_bad_sa = J1939(bytes(dm14), pgn=J1939_PGN_DM14, src=0x30, dst=0x20) +assert resp_dm15.answers(req_raw_bad_sa) == 0 + += J1939-73 layers dissect truncated and short frames gracefully +from scapy.config import conf +_old_dbg = conf.debug_dissector +try: + conf.debug_dissector = True + _j_dm1_short = J1939(b"X", pgn=J1939_PGN_DM1, dst=0xFF) + assert not _j_dm1_short.haslayer(J1939Dm1) + assert _j_dm1_short.data == b"X" + _j_dm1_ok = J1939(b"\x00\x00", pgn=J1939_PGN_DM1, dst=0xFF) + assert _j_dm1_ok.haslayer(J1939Dm1) + _j_dm14_short = J1939(b"X", pgn=J1939_PGN_DM14, dst=0xFF) + assert not _j_dm14_short.haslayer(J1939Dm14) + assert _j_dm14_short.data == b"X" + _j_dm14_ok = J1939(b"\x00" * 8, pgn=J1939_PGN_DM14, dst=0xFF) + assert _j_dm14_ok.haslayer(J1939Dm14) + _j_dm15_short = J1939(b"X", pgn=J1939_PGN_DM15, dst=0xFF) + assert not _j_dm15_short.haslayer(J1939Dm15) + assert _j_dm15_short.data == b"X" + _j_dm15_ok = J1939(b"\x00" * 8, pgn=J1939_PGN_DM15, dst=0xFF) + assert _j_dm15_ok.haslayer(J1939Dm15) + _j_max_dm1 = J1939(b"X" * 1785, pgn=J1939_PGN_DM1, dst=0xFF) + assert len(_j_max_dm1[J1939Dm1].dtcs) == 445 +finally: + conf.debug_dissector = _old_dbg + += Scheduler teardown +from scapy.contrib.isotp.isotp_soft_socket import TimeoutScheduler +_ts = TimeoutScheduler._thread +TimeoutScheduler.clear() +if _ts is not None: + _ts.join(timeout=5) + +_ts is None or not _ts.is_alive() + diff --git a/test/contrib/automotive/j1939_dm_scanner.uts b/test/contrib/automotive/j1939_dm_scanner.uts new file mode 100644 index 00000000000..c457e1db3b7 --- /dev/null +++ b/test/contrib/automotive/j1939_dm_scanner.uts @@ -0,0 +1,1592 @@ +% Regression tests for J1939 Diagnostic Message (DM) Scanner +~ automotive_comm scanner + ++ Configuration +~ conf + += Imports +from threading import Event +from scapy.layers.can import CAN +from scapy.ansmachine import AnsweringMachine +from scapy.contrib.automotive.j1939.j1939_dm_scanner import ( + J1939PgnScanResult, + J1939_ACK_CTRL_NACK, + J1939_DM_PGNS, + J1939_DM_Scanner, + J1939_PGN_Enumerator, + J1939_PGN_VIN, + j1939_scan_dm, + j1939_scan_pgns, +) +from scapy.contrib.j1939 import ( + J1939Request, + J1939_GLOBAL_ADDRESS, + J1939_NULL_ADDRESS, + J1939_PGN_ACK, + J1939_PGN_REQUEST, + J1939_PGN_TP_CM, + J1939_TP_CM, + J1939_TP_CM_BAM, + J1939_TP_CM_RTS, + J1939_TP_CTRL_BAM, + J1939_TP_CTRL_RTS, + can_id_to_j1939, + j1939_to_can_id, +) + +J1939_PF_ACK = (J1939_PGN_ACK >> 8) & 0xFF +J1939_PF_REQUEST = (J1939_PGN_REQUEST >> 8) & 0xFF +J1939_TP_CM_PF = (J1939_PGN_TP_CM >> 8) & 0xFF +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_DEFAULT_BITRATE, + J1939_DEFAULT_BUSLOAD, + j1939_inter_probe_delay, +) +from test.testsocket import TestSocket, SlowTestSocket, cleanup_testsockets + += Redirect logging +import logging +from scapy.error import log_runtime +from io import StringIO +log_stream = StringIO() +handler = logging.StreamHandler(log_stream) +log_runtime.addHandler(handler) +j1939_logger = logging.getLogger("scapy.contrib.automotive.j1939") +j1939_logger.addHandler(handler) + + ++ DM PGN constants + += J1939_DM_PGNS contains all standard DM entries +assert len(J1939_DM_PGNS) == 57 +for name in ("DM1", "DM2", "DM3", "DM4", "DM5", "DM6", "DM11", "DM12"): + assert name in J1939_DM_PGNS, "Missing {}".format(name) + += DM PGN values are correct (spot-check DM1 and DM6) +assert J1939_DM_PGNS["DM1"] == 0xFECA, "DM1 PGN: 0x{:04X}".format(J1939_DM_PGNS["DM1"]) +assert J1939_DM_PGNS["DM6"] == 0xFECF, "DM6 PGN: 0x{:04X}".format(J1939_DM_PGNS["DM6"]) + += PDU2 DM PGNs have PF byte >= 0xF0 +for name, pgn in J1939_DM_PGNS.items(): + pf = (pgn >> 8) & 0xFF + if pf >= 0xF0: + assert pf >= 0xF0, "{} PF=0x{:02X} should be PDU2".format(name, pf) + += J1939_PF_ACK and J1939_PGN_ACK have correct values +assert J1939_PF_ACK == 0xE8, "J1939_PF_ACK: 0x{:02X}".format(J1939_PF_ACK) +assert J1939_PGN_ACK == 0xE800, "J1939_PGN_ACK: 0x{:04X}".format(J1939_PGN_ACK) + + + ++ J1939PgnScanResult class + += J1939PgnScanResult: supported result sets correct attributes +res = J1939PgnScanResult(pgn=0xFECA, supported=True, name="DM1") +assert res.name == "DM1" +assert res.pgn == 0xFECA +assert res.supported is True +assert res.packet is None +assert res.error is None + += J1939PgnScanResult: NACK result sets correct attributes +res = J1939PgnScanResult(pgn=0xFECB, supported=False, name="DM2", error="NACK") +assert res.supported is False +assert res.error == "NACK" + += J1939PgnScanResult: Timeout result +res = J1939PgnScanResult(pgn=0xFECE, supported=False, name="DM5", error="Timeout") +assert res.supported is False +assert res.error == "Timeout" +assert res.packet is None + += J1939PgnScanResult: __repr__ contains name and pgn +res = J1939PgnScanResult(pgn=0xFECA, supported=True, name="DM1") +r = repr(res) +assert "DM1" in r, "repr should contain name" +assert str(0xFECA) in r or "FECA" in r.upper(), "repr should contain pgn" + += J1939PgnScanResult: equality +res1 = J1939PgnScanResult(pgn=0xFECA, supported=True, name="DM1") +res2 = J1939PgnScanResult(pgn=0xFECA, supported=True, name="DM1") +assert res1 == res2 + + ++ j1939_scan_dm - probe frame format + += dm_pgn_probe: sends a unicast Request frame to target_da +def test_dm_pgn_probe_frame(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_dm(tx_sock, target_da=0x00, dms=["DM1"], sniff_time=0.0) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1, "Expected 1 probe frame, got {}".format(len(pkts)) + probe = pkts[0] + f = can_id_to_j1939(probe.identifier); pf, ps, sa = f["pdu_format"], f["pdu_specific"], f["src"] + assert probe.flags & 0x4, "Expected extended CAN frame" + assert pf == J1939_PF_REQUEST, "PF should be 0xEA (Request)" + assert ps == 0x00, "DA should be target_da=0x00" + assert sa == 0xF9, "SA should be 0xF9 (diag adapter)" + expected_payload = bytes(J1939Request(req_pgn=J1939_DM_PGNS["DM1"])) + assert bytes(probe.data) == expected_payload, \ + "Payload should be LE PGN, got {}".format(bytes(probe.data).hex()) + cleanup_testsockets() + +test_dm_pgn_probe_frame() + += dm_pgn_probe: payload encodes the requested PGN in little-endian +def test_dm_pgn_probe_payload_le(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_dm(tx_sock, target_da=0x10, dms=["DM6"], sniff_time=0.0) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1 + payload = bytes(pkts[0].data) + # DM6 = 0xFECF = 65231; LE 3 bytes: CF FE 00 + assert payload == b'\xcf\xfe\x00', \ + "DM6 LE payload should be CF FE 00, got {}".format(payload.hex()) + cleanup_testsockets() + +test_dm_pgn_probe_payload_le() + + ++ j1939_scan_dm - response classification + += dm_pgn_probe: positive response (ECU replies with requested PGN) +sock = TestSocket(CAN) +# Inject a DM1 response from SA=0x10 (PDU2: PF=0xFE, PS=0xCA) +resp_can_id = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x10) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xff\xff' + b'\x00' * 6))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.1)["DM1"] +assert res.supported is True, "ECU DM1 reply should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += dm_pgn_probe: NACK response (ECU replies with PGN 0xE800, ctrl=0x01) +sock = TestSocket(CAN) +# NACK from SA=0x20, directed to our src_addr=0xF9 (PDU1: PF=0xE8, PS=src_addr) +nack_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, 0xF9, 0x20) +# NACK payload: ctrl=0x01, group_fn=0xFF, reserved=0xFFFF, addr=0xFF, pgn LE (3 bytes) +nack_pgn_le = bytes(J1939Request(req_pgn=J1939_DM_PGNS["DM2"])) +nack_data = b'\x01\xff\xff\xff\xff' + nack_pgn_le +sock.ins.send(bytes(CAN(identifier=nack_can_id, flags="extended", + data=nack_data))) +res = j1939_scan_dm(sock, target_da=0x20, dms=["DM2"], sniff_time=0.1)["DM2"] +assert res.supported is False, "NACK should mark PGN as not supported" +assert res.error == "NACK" +assert res.packet is not None +cleanup_testsockets() + += dm_pgn_probe: ignores NACK for a different PGN +sock = TestSocket(CAN) +nack_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, 0xF9, 0x20) +foreign_pgn_le = bytes(J1939Request(req_pgn=J1939_DM_PGNS["DM1"])) # different PGN +nack_data = b'\x01\xff\xff\xff\xff' + foreign_pgn_le +sock.ins.send(bytes(CAN(identifier=nack_can_id, flags="extended", + data=nack_data))) +res = j1939_scan_dm(sock, target_da=0x20, dms=["DM2"], sniff_time=0.05)["DM2"] +assert res.supported is False +assert res.error == "Timeout" +cleanup_testsockets() + += dm_pgn_probe: timeout (no response within sniff_time) +sock = TestSocket(CAN) +res = j1939_scan_dm(sock, target_da=0x30, dms=["DM5"], sniff_time=0.05)["DM5"] +assert res.supported is False +assert res.error == "Timeout" +assert res.packet is None +cleanup_testsockets() + += dm_pgn_probe: non-extended (11-bit) frames are ignored +sock = TestSocket(CAN) +# 11-bit frame - flags has no extended bit +sock.ins.send(bytes(CAN(identifier=0x040, data=b'\xca\xfe\x00\x00\x00\x00\x00\x00'))) +res = j1939_scan_dm(sock, target_da=0x40, dms=["DM1"], sniff_time=0.1)["DM1"] +assert res.supported is False +assert res.error == "Timeout", "Non-extended frames must be ignored" +cleanup_testsockets() + += dm_pgn_probe: response from wrong SA is ignored +sock = TestSocket(CAN) +# Response from SA=0x55 when we probed DA=0x30 +resp_can_id = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x55) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xff\xff' + b'\x00' * 6))) +res = j1939_scan_dm(sock, target_da=0x30, dms=["DM1"], sniff_time=0.1)["DM1"] +assert res.supported is False, "Response from wrong SA must be ignored" +assert res.error == "Timeout" +cleanup_testsockets() + += dm_pgn_probe: stop_event already set returns Aborted immediately +def test_dm_pgn_stop_event(): + ev = Event() + ev.set() + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + res = j1939_scan_dm(tx_sock, target_da=0x00, + dms=["DM1"], stop_event=ev, + sniff_time=0.05)["DM1"] + probes = monitor.sniff(count=1, timeout=0.1) + assert len(probes) == 0, "No probe should be sent when stop_event is set" + assert res.error == "Aborted" + cleanup_testsockets() + +test_dm_pgn_stop_event() + + ++ j1939_scan_dm - combined scanner + += j1939_scan_dm: scans all DMs by default and returns dict with all entries +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, sniff_time=0.002) +assert len(results) == len(J1939_DM_PGNS), "Expected {} results, got {}".format(len(J1939_DM_PGNS), len(results)) +for name in J1939_DM_PGNS: + assert name in results, "Missing result for {}".format(name) + +cleanup_testsockets() + += j1939_scan_dm: all entries are J1939PgnScanResult instances +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, sniff_time=0.002) +for name, res in results.items(): + assert isinstance(res, J1939PgnScanResult), "{} not J1939PgnScanResult".format(name) + +cleanup_testsockets() + += j1939_scan_dm: detects positive response for selected DM +sock = TestSocket(CAN) +# Inject DM1 positive response from SA=0x10 +resp_can_id = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x10) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xff\xff' + b'\x00' * 6))) +results = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.1) +assert results["DM1"].supported is True, "DM1 should be detected as supported" +cleanup_testsockets() + += j1939_scan_dm: raises ValueError for unknown DM name +def test_dm_scan_invalid_name(): + sock = TestSocket(CAN) + try: + j1939_scan_dm(sock, target_da=0x00, dms=["DM99"]) + assert False, "Expected ValueError" + except ValueError as e: + assert "DM99" in str(e), "Error should mention the bad name" + cleanup_testsockets() + +test_dm_scan_invalid_name() + += j1939_scan_dm: stop_event halts scan after current PGN +def test_dm_scan_stop_event(): + from threading import Event + ev = Event() + ev.set() + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + results = j1939_scan_dm(tx_sock, target_da=0x00, + dms=["DM1", "DM2", "DM3"], + stop_event=ev, sniff_time=0.05) + probes = monitor.sniff(count=1, timeout=0.1) + assert len(probes) == 0, "No probes should be sent when stop_event is set" + # All entries should be Aborted because stop_event was set before scan + assert len(results) == 0 or all( + r.error == "Aborted" for r in results.values() + ), "All results should be Aborted" + cleanup_testsockets() + +test_dm_scan_stop_event() + += j1939_scan_dm: custom pgns subset scans only requested DMs +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM5"], + sniff_time=0.02) +assert set(results.keys()) == {"DM1", "DM5"}, \ + "Expected only DM1 and DM5, got {}".format(set(results.keys())) +cleanup_testsockets() + + ++ Pacing - DM scanner +~ automotive_comm + += scan_dm: bitrate and busload params accepted without error (timeout path) +sock = TestSocket(CAN) +res = j1939_scan_dm(sock, target_da=0x00, dms=["DM1"], + bitrate=250000, busload=0.05, + sniff_time=0.02)["DM1"] +assert res.error == "Timeout" +cleanup_testsockets() + += scan_dm: invalid busload raises ValueError +def test_dm_scan_invalid_busload(): + sock = TestSocket(CAN) + try: + j1939_scan_dm(sock, target_da=0x00, dms=["DM1"], + busload=0.0, sniff_time=0.02) + assert False, "Expected ValueError" + except ValueError as e: + assert "busload" in str(e).lower(), str(e) + cleanup_testsockets() + +test_dm_scan_invalid_busload() + += scan_dm: bitrate and busload params propagate to inter-probe pacing +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1"], + bitrate=250000, busload=0.1, sniff_time=0.02) +assert "DM1" in results +assert results["DM1"].error == "Timeout" +cleanup_testsockets() + += pacing delay for DM scan is consistent with j1939_inter_probe_delay math +# For request=3 bytes, response=8 bytes, bitrate=250000, busload=0.005: +# probe_bits = 131 + 8*3 = 155 +# resp_bits = 131 + 8*8 = 195 +# min_period = 350 / 1250 = 0.28 s +d = j1939_inter_probe_delay(250000, 0.005, 3, 8, 0.0) +assert abs(d - 0.1776) < 1e-4, "Expected ~0.1776 s, got {}".format(d) + + ++ reconnect_handler and reset_handler +~ automotive_comm + += scan_dm: reset_handler is called between probes +call_log = [] + +def my_reset(): + call_log.append("reset") + +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2"], + reset_handler=my_reset, sniff_time=0.02) +# Two PGNs -> one reset call between them +assert call_log == ["reset"], "Expected 1 reset call, got: {}".format(call_log) +cleanup_testsockets() + += scan_dm: reset_handler called N-1 times for N pgns +call_log2 = [] + +def my_reset2(): + call_log2.append("reset") + +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2", "DM3"], + reset_handler=my_reset2, sniff_time=0.02) +# 3 PGNs -> 2 reset calls +assert len(call_log2) == 2, "Expected 2 reset calls, got: {}".format(call_log2) +cleanup_testsockets() + += scan_dm: reset_handler not called for single-pgn scan +call_log3 = [] + +def my_reset3(): + call_log3.append("reset") + +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1"], + reset_handler=my_reset3, sniff_time=0.02) +assert call_log3 == [], "Expected no reset calls for single pgn" +cleanup_testsockets() + += scan_dm: reconnect_handler is called after reset_handler and returns new socket +call_log4 = [] + +def my_reset4(): + call_log4.append("reset") + +new_sock_holder = [] + +def my_reconnect(): + call_log4.append("reconnect") + s = TestSocket(CAN) + new_sock_holder.append(s) + return s + +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2"], + reset_handler=my_reset4, reconnect_handler=my_reconnect, + sniff_time=0.02) +assert call_log4 == ["reset", "reconnect"], \ + "Expected reset+reconnect, got: {}".format(call_log4) +assert len(new_sock_holder) == 1 +cleanup_testsockets() + += scan_dm: reconnect_handler alone (no reset_handler) is accepted +reconnect_log = [] + +def my_reconnect_only(): + reconnect_log.append("reconnect") + return TestSocket(CAN) + +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2"], + reconnect_handler=my_reconnect_only, sniff_time=0.02) +assert reconnect_log == ["reconnect"], \ + "Expected 1 reconnect call, got: {}".format(reconnect_log) +cleanup_testsockets() + += scan_dm: no reset/reconnect handlers -> same behaviour as before +sock = TestSocket(CAN) +results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1"], + sniff_time=0.02) +assert "DM1" in results +cleanup_testsockets() + + ++ Send-then-sniff race condition regression tests +~ conf + += scan_dm: immediate ECU reply is captured (sniff-before-send regression) +def test_dm_immediate_reply(): + import threading + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + dm1_pgn = J1939_DM_PGNS["DM1"] + dm1_pf = (dm1_pgn >> 8) & 0xFF + dm1_ps = dm1_pgn & 0xFF + def simulate_ecu(): + pkts = monitor.sniff(count=1, timeout=0.5) + if pkts: + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f["pdu_format"], f["pdu_specific"], f["src"] + if pf == J1939_PF_REQUEST: + resp_id = j1939_to_can_id(6, 0, 0, dm1_pf, dm1_ps, ps) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + t = threading.Thread(target=simulate_ecu) + t.start() + results = j1939_scan_dm(sock, target_da=0x42, dms=["DM1"], sniff_time=0.3) + result = results["DM1"] + t.join(timeout=1.0) + assert result.supported, "Immediate DM1 reply must be captured, got: {}".format(result) + cleanup_testsockets() + +test_dm_immediate_reply() + += scan_dm: sniff exits early when response found (stop_filter) +def test_dm_early_exit(): + import time + sock = TestSocket(CAN) + dm1_pgn = J1939_DM_PGNS["DM1"] + dm1_pf = (dm1_pgn >> 8) & 0xFF + dm1_ps = dm1_pgn & 0xFF + resp_id = j1939_to_can_id(6, 0, 0, dm1_pf, dm1_ps, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + t0 = time.monotonic() + results = j1939_scan_dm(sock, target_da=0x42, dms=["DM1"], sniff_time=5.0) + result = results["DM1"] + elapsed = time.monotonic() - t0 + assert result.supported, "Expected DM1 supported, got: {}".format(result) + assert elapsed < 2.0, "Sniff should exit early, took {:.1f}s (max 2.0s)".format(elapsed) + cleanup_testsockets() + +test_dm_early_exit() + += scan_dm: response found despite stale frames (kernel buffer flush) +~ slow_test +def test_dm_stale_frames(): + import time + sock = SlowTestSocket(CAN, frame_delay=0.0002, mux_throttle=0.001) + dm1_pgn = J1939_DM_PGNS["DM1"] + dm1_pf = (dm1_pgn >> 8) & 0xFF + dm1_ps = dm1_pgn & 0xFF + stale_id = j1939_to_can_id(6, 0, 0, dm1_pf, dm1_ps, 0x99) + for _ in range(50): + with sock._serial_lock: + sock._serial_buffer.append( + bytes(CAN(identifier=stale_id, flags="extended", data=b'\xAA' * 8)) + ) + resp_id = j1939_to_can_id(6, 0, 0, dm1_pf, dm1_ps, 0x42) + with sock._serial_lock: + sock._serial_buffer.append( + bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8)) + ) + results = j1939_scan_dm(sock, target_da=0x42, dms=["DM1"], sniff_time=2.0) + result = results["DM1"] + assert result.supported, "Expected DM1 supported despite stale frames, got: {}".format(result) + cleanup_testsockets() + +test_dm_stale_frames() + += scan_dm: multiple DAs with stale traffic (simulates slow embedded system) +~ slow_test +def test_dm_multi_da_stale(): + import time + sock = SlowTestSocket(CAN, frame_delay=0.0002, mux_throttle=0.001) + dm1_pgn = J1939_DM_PGNS["DM1"] + dm1_pf = (dm1_pgn >> 8) & 0xFF + dm1_ps = dm1_pgn & 0xFF + target_das = [0x10, 0x20, 0x30] + for da in target_das: + stale_id = j1939_to_can_id(6, 0, 0, 0xFE, 0x00, 0xEE) + for _ in range(20): + with sock._serial_lock: + sock._serial_buffer.append( + bytes(CAN(identifier=stale_id, flags="extended", data=b'\xBB' * 8)) + ) + resp_id = j1939_to_can_id(6, 0, 0, dm1_pf, dm1_ps, da) + with sock._serial_lock: + sock._serial_buffer.append( + bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8)) + ) + results = {} + for da in target_das: + results[da] = j1939_scan_dm(sock, target_da=da, dms=["DM1"], + sniff_time=2.0) + found_das = [da for da in target_das if results[da]["DM1"].supported] + assert len(found_das) == len(target_das), \ + "Expected all DAs found, got: {}".format([hex(d) for d in found_das]) + cleanup_testsockets() + +test_dm_multi_da_stale() + + ++ Factory (reconnect) API + += j1939_scan_dm: callable factory works for DM scanner +def test_dm_factory(): + pgn = J1939_DM_PGNS["DM1"] + dm1_pf = (pgn >> 8) & 0xFF + dm1_ps = pgn & 0xFF + sock = TestSocket(CAN) + resp_id = j1939_to_can_id(6, 0, 0, dm1_pf, dm1_ps, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + def _factory(): + return sock + results = j1939_scan_dm(_factory(), target_da=0x42, dms=["DM1"], sniff_time=0.5, reconnect_handler=_factory) + assert "DM1" in results + assert results["DM1"].supported, "Factory DM scan should find DM1 supported" + cleanup_testsockets() + +test_dm_factory() + += scan_dm: callable factory works for DM probe +def test_dm_pgn_factory(): + pgn = J1939_DM_PGNS["DM5"] + dm5_pf = (pgn >> 8) & 0xFF + dm5_ps = pgn & 0xFF + sock = TestSocket(CAN) + resp_id = j1939_to_can_id(6, 0, 0, dm5_pf, dm5_ps, 0x10) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + def _factory(): + return sock + results = j1939_scan_dm(_factory(), target_da=0x10, dms=["DM5"], + sniff_time=0.5, reconnect_handler=_factory) + result = results["DM5"] + assert result.supported, "Factory DM PGN probe should find DM5" + assert result.name == "DM5" + cleanup_testsockets() + +test_dm_pgn_factory() + + ++ reconnect_handler retry logic + += scan_dm: reconnect_handler retries on failure and succeeds +def test_reconnect_retry_success(): + fail_count = [0] + def failing_reconnect(): + fail_count[0] += 1 + if fail_count[0] < 3: + raise OSError("simulated reconnect failure") + return TestSocket(CAN) + sock = TestSocket(CAN) + results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2"], + reconnect_handler=failing_reconnect, + reconnect_retries=5, retry_delay=0.005, sniff_time=0.02) + assert "DM1" in results and "DM2" in results + assert fail_count[0] == 3, "Expected 3 attempts (2 fail + 1 success), got {}".format(fail_count[0]) + cleanup_testsockets() + +test_reconnect_retry_success() + += scan_dm: reconnect_handler raises after exhausting retries +def test_reconnect_retry_exhausted(): + def always_fail(): + raise OSError("always fails") + sock = TestSocket(CAN) + raised = False + try: + j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2"], + reconnect_handler=always_fail, + reconnect_retries=2, retry_delay=0.005, sniff_time=0.02) + except OSError: + raised = True + assert raised, "Should raise after exhausting retries" + cleanup_testsockets() + +test_reconnect_retry_exhausted() + += scan_dm: reconnect_retries=1 means single attempt (no retry) +def test_reconnect_retries_one(): + call_count = [0] + def counting_reconnect(): + call_count[0] += 1 + if call_count[0] == 1: + raise OSError("fail") + return TestSocket(CAN) + sock = TestSocket(CAN) + raised = False + try: + j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2"], + reconnect_handler=counting_reconnect, + reconnect_retries=1, retry_delay=0.005, sniff_time=0.02) + except OSError: + raised = True + assert raised, "reconnect_retries=1 means single attempt, should raise" + assert call_count[0] == 1 + cleanup_testsockets() + +test_reconnect_retries_one() + += scan_dm: reconnect retry uses stop_event.wait for sleep +def test_reconnect_retry_uses_stop_event(): + from threading import Event + evt = Event() + fail_count = [0] + def failing_reconnect(): + fail_count[0] += 1 + if fail_count[0] < 2: + raise OSError("simulated failure") + return TestSocket(CAN) + sock = TestSocket(CAN) + results = j1939_scan_dm(sock, target_da=0x00, dms=["DM1", "DM2"], + reconnect_handler=failing_reconnect, + reconnect_retries=5, retry_delay=0.005, sniff_time=0.02, + stop_event=evt) + assert fail_count[0] == 2 + cleanup_testsockets() + +test_reconnect_retry_uses_stop_event() + + ++ Multi-packet J1939-TP DM responses + += Imports for J1939-TP DM tests +from scapy.contrib.j1939 import J1939_PGN_TP_CM +J1939_TP_CM_PF = (J1939_PGN_TP_CM >> 8) & 0xFF +from scapy.contrib.j1939 import ( + can_id_to_j1939, + j1939_to_can_id, + J1939_TP_CTRL_BAM, + J1939_TP_CTRL_RTS, +) + += scan_dm: multi-packet BAM response for DM1 (2 Active DTCs = 10 bytes) +sock = TestSocket(CAN) +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=10, num_packets=2, pgn=J1939_DM_PGNS["DM1"])) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.1)["DM1"] +assert res.supported is True, "DM1 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM1 (2 Active DTCs = 10 bytes) +sock = TestSocket(CAN) +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=10, num_packets=2, max_packets=0xFF, pgn=J1939_DM_PGNS["DM1"])) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.1)["DM1"] +assert res.supported is True, "DM1 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet BAM response for DM2 (Previously Active DTCs) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM2"] +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=14, num_packets=2, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM2"], sniff_time=0.1)["DM2"] +assert res.supported is True, "DM2 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM2 (Previously Active DTCs) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM2"] +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=14, num_packets=2, max_packets=0xFF, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM2"], sniff_time=0.1)["DM2"] +assert res.supported is True, "DM2 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet BAM response for DM4 (Freeze Frame Parameters) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM4"] +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=25, num_packets=4, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM4"], sniff_time=0.1)["DM4"] +assert res.supported is True, "DM4 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM4 (Freeze Frame Parameters) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM4"] +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=25, num_packets=4, max_packets=0xFF, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM4"], sniff_time=0.1)["DM4"] +assert res.supported is True, "DM4 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet BAM response for DM16 (Binary Data Transfer) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM16"] +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=64, num_packets=10, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM16"], sniff_time=0.1)["DM16"] +assert res.supported is True, "DM16 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM16 (Binary Data Transfer) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM16"] +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=64, num_packets=10, max_packets=0xFF, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM16"], sniff_time=0.1)["DM16"] +assert res.supported is True, "DM16 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet BAM response for DM19 (Calibration Information) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM19"] +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=40, num_packets=6, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM19"], sniff_time=0.1)["DM19"] +assert res.supported is True, "DM19 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM19 (Calibration Information) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM19"] +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=40, num_packets=6, max_packets=0xFF, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM19"], sniff_time=0.1)["DM19"] +assert res.supported is True, "DM19 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet BAM response for DM24 (SPN Support) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM24"] +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=80, num_packets=12, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM24"], sniff_time=0.1)["DM24"] +assert res.supported is True, "DM24 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM24 (SPN Support) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM24"] +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=80, num_packets=12, max_packets=0xFF, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM24"], sniff_time=0.1)["DM24"] +assert res.supported is True, "DM24 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet BAM response for DM25 (Expanded Freeze Frame) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM25"] +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=35, num_packets=5, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM25"], sniff_time=0.1)["DM25"] +assert res.supported is True, "DM25 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM25 (Expanded Freeze Frame) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM25"] +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=35, num_packets=5, max_packets=0xFF, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM25"], sniff_time=0.1)["DM25"] +assert res.supported is True, "DM25 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet BAM response for DM28 (Permanent DTCs) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM28"] +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=10, num_packets=2, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM28"], sniff_time=0.1)["DM28"] +assert res.supported is True, "DM28 BAM response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += scan_dm: multi-packet RTS response for DM28 (Permanent DTCs) +sock = TestSocket(CAN) +pgn = J1939_DM_PGNS["DM28"] +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=10, num_packets=2, max_packets=0xFF, pgn=pgn)) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM28"], sniff_time=0.1)["DM28"] +assert res.supported is True, "DM28 RTS response should be detected as supported" +assert res.error is None +assert res.packet is not None +cleanup_testsockets() + += j1939_scan_dm: detects multi-packet TP BAM and RTS responses in combined scan +def test_scan_dm_tp_combined(): + import threading + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + def simulate_ecu(): + while True: + pkts = monitor.sniff(count=1, timeout=0.5) + if not pkts: + break + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f["pdu_format"], f["pdu_specific"], f["src"] + if pf == J1939_PF_REQUEST: + req_pgn = p.data[0] | (p.data[1] << 8) | (p.data[2] << 16) + if req_pgn == J1939_DM_PGNS["DM1"]: + bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x20) + bam_d = bytes(J1939_TP_CM_BAM(total_size=10, num_packets=2, pgn=req_pgn)) + sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_d))) + elif req_pgn == J1939_DM_PGNS["DM19"]: + rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, sa, 0x20) + rts_d = bytes(J1939_TP_CM_RTS(total_size=40, num_packets=6, max_packets=0xFF, pgn=req_pgn)) + sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_d))) + t = threading.Thread(target=simulate_ecu) + t.start() + results = j1939_scan_dm(sock, target_da=0x20, dms=["DM1", "DM19"], sniff_time=0.2) + t.join(timeout=2.0) + assert results["DM1"].supported, "DM1 BAM should be supported" + assert results["DM19"].supported, "DM19 RTS should be supported" + cleanup_testsockets() + +test_scan_dm_tp_combined() + += scan_dm: TP.CM announcing different PGN is ignored +sock = TestSocket(CAN) +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=14, num_packets=2, pgn=J1939_DM_PGNS["DM2"])) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.05)["DM1"] +assert res.supported is False +assert res.error == "Timeout" +cleanup_testsockets() + += scan_dm: TP.CM from different SA is ignored +sock = TestSocket(CAN) +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x30) +bam_data = bytes(J1939_TP_CM_BAM(total_size=10, num_packets=2, pgn=J1939_DM_PGNS["DM1"])) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.05)["DM1"] +assert res.supported is False +assert res.error == "Timeout" +cleanup_testsockets() + += scan_dm: RTS directed to different DA is ignored +sock = TestSocket(CAN) +rts_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0x55, 0x10) +rts_data = bytes(J1939_TP_CM_RTS(total_size=10, num_packets=2, max_packets=0xFF, pgn=J1939_DM_PGNS["DM1"])) +sock.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], src_addr=0xF9, sniff_time=0.05)["DM1"] +assert res.supported is False +assert res.error == "Timeout" +cleanup_testsockets() + += scan_dm: BAM with non-global destination address is ignored +sock = TestSocket(CAN) +bad_bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x10) +bam_data = bytes(J1939_TP_CM_BAM(total_size=10, num_packets=2, pgn=J1939_DM_PGNS["DM1"])) +sock.ins.send(bytes(CAN(identifier=bad_bam_id, flags="extended", data=bam_data))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.05)["DM1"] +assert res.supported is False +assert res.error == "Timeout" +cleanup_testsockets() + += scan_dm: truncated TP.CM (< 8 bytes) is ignored +sock = TestSocket(CAN) +bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) +sock.ins.send(bytes(CAN(identifier=bam_id, flags="extended", data=bytes([J1939_TP_CTRL_BAM, 10, 0, 2])))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.05)["DM1"] +assert res.supported is False +assert res.error == "Timeout" +cleanup_testsockets() + += dm_scan: early exit on multiple responses and pre-set stop_event +from threading import Event +sock = TestSocket(CAN) +resp_id = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x10) +# Send two identical response frames to exercise if result: return +sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b"\x00\x00\x11\x22\x33\x44"))) +sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b"\x00\x00\x11\x22\x33\x44"))) +res = j1939_scan_dm(sock, target_da=0x10, dms=["DM1"], sniff_time=0.05)["DM1"] +assert res.supported is True +cleanup_testsockets() + +# Exercise if stop_event is not None and stop_event.is_set(): return +sock2 = TestSocket(CAN) +evt = Event() +evt.set() +sock2.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b"\x00\x00\x11\x22\x33\x44"))) +res2 = j1939_scan_dm(sock2, target_da=0x10, dms=["DM1"], sniff_time=0.05, stop_event=evt)["DM1"] +assert res2.supported is False +cleanup_testsockets() + += dm_scan: filter configuration error detection and no flood of warnings +from unittest.mock import patch +from scapy.contrib.j1939 import log_j1939 +sock_dm = TestSocket(CAN) +warns_dm = [] +with patch.object(log_j1939, "warning", side_effect=lambda msg, *args: warns_dm.append(msg % args if args else msg)): + for _ in range(5): + noise_can = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x99), flags="extended", data=b"\x00" * 8) + sock_dm.ins.send(bytes(noise_can)) + res = j1939_scan_dm(sock_dm, target_da=0x10, dms=["DM1"], sniff_time=0.05)["DM1"] + +assert len(warns_dm) == 1, "Expected exactly 1 warning despite multiple noise frames in dm_scan, got %d" % len(warns_dm) +assert "0x10" in warns_dm[0] +cleanup_testsockets() +True + ++ J1939 ECU Answering Machines & DM Scanner Comparisons + += Definition of J1939 ECU Answering Machines +import struct +import threading +import time +from scapy.ansmachine import AnsweringMachine +from scapy.contrib.automotive.j1939.j1939_dm_scanner import J1939_DM_PGNS, J1939_PGN_VIN +from scapy.contrib.j1939 import ( + can_id_to_j1939, + j1939_to_can_id, + J1939, + J1939Request, + J1939_GLOBAL_ADDRESS, + J1939_PGN_TP_CM, + J1939_TP_CM_BAM, + J1939_TP_CM_RTS, + J1939_TP_CTRL_CTS, + log_j1939, +) +from scapy.layers.can import CAN +from scapy.packet import Packet +_CAN_EXTENDED_FLAG = 0x4 + +class J1939_ECU_AnsweringMachine(AnsweringMachine): + """J1939 ECU simulator answering machine.""" + function_name = "j1939_ecu" + filter = None + def __init__( + self, + ecu_addr=0x20, + supported_dms=None, + send_nack=True, + tp_mode="none", + response_delay=0.0, + **kargs + ): + self.ecu_addr = ecu_addr + self.supported_dms = supported_dms if supported_dms is not None else {} + self.send_nack = send_nack + self.tp_mode = tp_mode + self.response_delay = response_delay + super().__init__(**kargs) + # + def is_request(self, req): + if isinstance(req, CAN): + if not (req.flags & _CAN_EXTENDED_FLAG): + return False + f = can_id_to_j1939(req.identifier); pf, ps = f["pdu_format"], f["pdu_specific"] + if pf == J1939_PF_REQUEST and ps in (self.ecu_addr, J1939_GLOBAL_ADDRESS): + return bool(len(req.data) >= 3) + if ( + pf == (J1939_PGN_TP_CM >> 8) + and ps in (self.ecu_addr, J1939_GLOBAL_ADDRESS) + and len(req.data) >= 8 + and req.data[0] == J1939_TP_CTRL_CTS + ): + return True + return False + # + if isinstance(req, J1939Request): + return bool(req.dst in (self.ecu_addr, J1939_GLOBAL_ADDRESS)) + # + if isinstance(req, J1939): + if req.pgn == 0xEA00 and req.dst in (self.ecu_addr, J1939_GLOBAL_ADDRESS): + return True + if ( + req.pgn == J1939_PGN_TP_CM + and req.dst in (self.ecu_addr, J1939_GLOBAL_ADDRESS) + ): + data = getattr(req, "data", None) or bytes(req.payload) + if len(data) >= 8 and data[0] == J1939_TP_CTRL_CTS: + return True + # + return False + # + def make_reply(self, req): + if self.response_delay > 0.0: + time.sleep(self.response_delay) + # + sa = J1939_GLOBAL_ADDRESS + req_pgn = 0 + # + if isinstance(req, CAN): + f = can_id_to_j1939(req.identifier); pf, ps, sa = f["pdu_format"], f["pdu_specific"], f["src"] + data = bytes(req.data) + if ( + pf == (J1939_PGN_TP_CM >> 8) + and len(data) >= 8 + and data[0] == J1939_TP_CTRL_CTS + ): + num_pkts = data[1] + next_pkt = data[2] + cts_pgn = data[5] | (data[6] << 8) | (data[7] << 16) + if cts_pgn in self.supported_dms: + payload = self.supported_dms[cts_pgn] + total_pkts = (len(payload) + 6) // 7 + dt_id = j1939_to_can_id(7, 0, 0, 0xEB, sa, self.ecu_addr) + dt_pkts = [] + for seq in range( + next_pkt, min(total_pkts + 1, next_pkt + num_pkts) + ): + offset = (seq - 1) * 7 + chunk = payload[offset:offset + 7] + chunk += b"\xff" * (7 - len(chunk)) + dt_pkts.append( + CAN( + identifier=dt_id, + flags="extended", + data=bytes([seq]) + chunk, + ) + ) + return dt_pkts + return None + if len(data) >= 3: + req_pgn = data[0] | (data[1] << 8) | (data[2] << 16) + elif isinstance(req, J1939Request): + sa = req.src + req_pgn = req.req_pgn + elif isinstance(req, J1939): + sa = req.src + if req.pgn == J1939_PGN_TP_CM: + data = getattr(req, "data", None) or bytes(req.payload) + if len(data) >= 8 and data[0] == J1939_TP_CTRL_CTS: + num_pkts = data[1] + next_pkt = data[2] + cts_pgn = data[5] | (data[6] << 8) | (data[7] << 16) + if cts_pgn in self.supported_dms: + payload = self.supported_dms[cts_pgn] + total_pkts = (len(payload) + 6) // 7 + dt_id = j1939_to_can_id(7, 0, 0, 0xEB, sa, self.ecu_addr) + dt_pkts = [] + for seq in range( + next_pkt, min(total_pkts + 1, next_pkt + num_pkts) + ): + offset = (seq - 1) * 7 + chunk = payload[offset:offset + 7] + chunk += b"\xff" * (7 - len(chunk)) + dt_pkts.append( + CAN( + identifier=dt_id, + flags="extended", + data=bytes([seq]) + chunk, + ) + ) + return dt_pkts + return None + other_data = getattr(req, "data", None) or bytes(req.payload) + if len(other_data) >= 3: + req_pgn = other_data[0] | (other_data[1] << 8) | (other_data[2] << 16) + # + if not req_pgn: + return None + # + if req_pgn in self.supported_dms: + payload = self.supported_dms[req_pgn] + if len(payload) > 8 and self.tp_mode == "rts": + num_pkts = (len(payload) + 6) // 7 + rts_id = j1939_to_can_id(7, 0, 0, 0xEC, sa, self.ecu_addr) + rts_d = bytes( + J1939_TP_CM_RTS( + total_size=len(payload), + num_packets=num_pkts, + max_packets=0xFF, + pgn=req_pgn, + ) + ) + return CAN(identifier=rts_id, flags="extended", data=rts_d) + if len(payload) > 8 and self.tp_mode == "bam": + num_pkts = (len(payload) + 6) // 7 + bam_id = j1939_to_can_id(7, 0, 0, 0xEC, J1939_GLOBAL_ADDRESS, self.ecu_addr) + bam_d = bytes( + J1939_TP_CM_BAM( + total_size=len(payload), + num_packets=num_pkts, + pgn=req_pgn, + ) + ) + return CAN(identifier=bam_id, flags="extended", data=bam_d) + # + pf = (req_pgn >> 8) & 0xFF + ps = sa if pf < 0xF0 else (req_pgn & 0xFF) + resp_id = j1939_to_can_id(6, 0, 0, pf, ps, self.ecu_addr) + return CAN(identifier=resp_id, flags="extended", data=payload[:8]) + # + if self.send_nack: + nack_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, sa, self.ecu_addr) + nack_data = bytes( + [J1939_ACK_CTRL_NACK, 0xFF, 0xFF, 0xFF, 0xFF] + ) + struct.pack(" NACK +req_unsupported = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEA, 0x20, 0xF9), flags="extended", data=b"\xcb\xfe\x00") +reply_nack = am.make_reply(req_unsupported) +assert reply_nack is not None +assert reply_nack.data[0] == 0x01 +assert reply_nack.data[5:8] == b"\xcb\xfe\x00" + += J1939_ECU_HighDM_AM supports only high DM and NACKs earlier DMs +high_am = J1939_ECU_HighDM_AM(ecu_addr=0x20, high_dm="DM50") +req_dm1 = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEA, 0x20, 0xF9), flags="extended", data=b"\xca\xfe\x00") +reply_dm1 = high_am.make_reply(req_dm1) +assert reply_dm1 is not None +assert reply_dm1.data[0] == 0x01 # NACK + +# DM50 request (0xFD56 -> LE bytes 0x56, 0xFD, 0x00) +req_dm50 = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEA, 0x20, 0xF9), flags="extended", data=b"\x56\xfd\x00") +reply_dm50 = high_am.make_reply(req_dm50) +assert reply_dm50 is not None +assert reply_dm50.data == b"\x00\x00\x11\x22\x33\x44\x55\x66" + += J1939_ECU_Timeout_AM returns None for unsupported requests +timeout_am = J1939_ECU_Timeout_AM(ecu_addr=0x20, supported_dm="DM1") +reply_supported = timeout_am.make_reply(req_dm1) +assert reply_supported is not None +reply_unsupported = timeout_am.make_reply(req_dm50) +assert reply_unsupported is None + +# Baseline test-only .sr1() scanner and performance benchmark are commented out +# to prevent excessive test runtime in CI. Uncomment for manual benchmarking. +# def test_scan_dm_sr1(sock, target_da, dms=None, src_addr=0xF9, sniff_time=0.1): ... + += J1939_ECU_HighDM_AM scanned with in-tree scanner +with TestSocket(CAN) as tester_sock, TestSocket(CAN) as ecu_sock: + tester_sock.pair(ecu_sock) + am = J1939_ECU_HighDM_AM(ecu_addr=0x20, high_dm="DM50") + t, stop_evt = am.start_bg(ecu_sock) + try: + res_intree = j1939_scan_dm(tester_sock, target_da=0x20, dms=["DM1", "DM50"], sniff_time=0.1) + assert res_intree["DM1"].supported is False + assert res_intree["DM1"].error == "NACK" + assert res_intree["DM50"].supported is True + finally: + stop_evt.set() + t.join(timeout=1.0) + cleanup_testsockets() + += J1939_ECU_Timeout_AM scanned with in-tree scanner +with TestSocket(CAN) as tester_sock, TestSocket(CAN) as ecu_sock: + tester_sock.pair(ecu_sock) + am = J1939_ECU_Timeout_AM(ecu_addr=0x20, supported_dm="DM1") + t, stop_evt = am.start_bg(ecu_sock) + try: + res_intree = j1939_scan_dm(tester_sock, target_da=0x20, dms=["DM1", "DM2"], sniff_time=0.1) + assert res_intree["DM1"].supported is True + assert res_intree["DM2"].supported is False + assert res_intree["DM2"].error == "Timeout" + finally: + stop_evt.set() + t.join(timeout=1.0) + cleanup_testsockets() + += J1939_ECU_MultiPacket_AM scanned with in-tree scanner +with TestSocket(CAN) as tester_sock, TestSocket(CAN) as ecu_sock: + tester_sock.pair(ecu_sock) + am = J1939_ECU_MultiPacket_AM(ecu_addr=0x20) + t, stop_evt = am.start_bg(ecu_sock) + try: + res_intree = j1939_scan_dm(tester_sock, target_da=0x20, dms=["DM1", "DM2"], sniff_time=0.1) + assert res_intree["DM1"].supported is True + assert res_intree["DM2"].supported is False + assert res_intree["DM2"].error == "NACK" + finally: + stop_evt.set() + t.join(timeout=1.0) + cleanup_testsockets() + +# = Runtime performance comparison: in-tree scanner vs simple .sr1() scanner +# ~ slow_test scanner +# (Performance benchmark commented out to avoid runtime overhead in CI) +# import time +# with TestSocket(CAN) as tester_sock, TestSocket(CAN) as ecu_sock: +# tester_sock.pair(ecu_sock) +# am = J1939_ECU_HighDM_AM(ecu_addr=0x20, high_dm="DM50") +# t, stop_evt = am.start_bg(ecu_sock) +# dms_to_scan = ["DM1", "DM2", "DM3", "DM4", "DM50"] +# try: +# t0 = time.monotonic() +# res_intree = j1939_scan_dm(tester_sock, target_da=0x20, dms=dms_to_scan, sniff_time=0.1) +# t_intree = time.monotonic() - t0 +# t0 = time.monotonic() +# res_sr1 = test_scan_dm_sr1(tester_sock, target_da=0x20, dms=dms_to_scan, sniff_time=0.1) +# t_sr1 = time.monotonic() - t0 +# assert res_intree["DM50"].supported is True +# assert res_sr1["DM50"].supported is True +# assert t_intree < t_sr1 +# finally: +# stop_evt.set() +# t.join(timeout=1.0) +# cleanup_testsockets() + + ++ General PGN Request Scanner and J1939_ECU_VIN_AM + += J1939_ECU_VIN_AM make_reply directly +vin_am = J1939_ECU_VIN_AM(ecu_addr=0x20, vin="1M8GDM9A_KP042788*") +req_vin = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEA, 0x20, 0xF9), flags="extended", data=b"\xe4\xfe\x00") +rep = vin_am.make_reply(req_vin) +assert rep is not None +f = can_id_to_j1939(rep.identifier); pf, ps, sa = f["pdu_format"], f["pdu_specific"], f["src"] +assert pf == 0xEC +assert sa == 0x20 +assert rep.data[0] == 0x10 +tp_pgn = rep.data[5] | (rep.data[6] << 8) | (rep.data[7] << 16) +assert tp_pgn == 0xFEE4 + += J1939_ECU_VIN_AM single-frame make_reply +vin_am_short = J1939_ECU_VIN_AM(ecu_addr=0x20, vin=b"12345678", tp_mode="none") +rep_short = vin_am_short.make_reply(req_vin) +assert rep_short is not None +f = can_id_to_j1939(rep_short.identifier); pf, ps, sa = f["pdu_format"], f["pdu_specific"], f["src"] +assert pf == 0xFE +assert ps == 0xE4 +assert rep_short.data == b"12345678" + += J1939_ECU_VIN_AM single-PGN query via J1939Socket .sr1() +from scapy.contrib.j1939 import J1939Socket +with TestSocket(CAN) as tester_can, TestSocket(CAN) as ecu_sock: + tester_can.pair(ecu_sock) + am = J1939_ECU_VIN_AM(ecu_addr=0x20, vin="1M8GDM9A_KP042788*") + t, stop_evt = am.start_bg(ecu_sock) + try: + tester_sock = J1939Socket(tester_can, src_addr=0xF9, include_tp_cm=True) + # Query VIN PGN using standard .sr1() + req = J1939(pgn=0xEA00, dst=0x20) / J1939Request(req_pgn=J1939_PGN_VIN) + ans = tester_sock.sr1(req, timeout=0.2, verbose=False) + assert ans is not None + tp_cm = J1939_TP_CM(ans.data) if getattr(ans, "data", None) else ans + assert tp_cm.pgn == J1939_PGN_VIN + + # Query unsupported PGN -> returns NACK + req_unsupp = J1939(pgn=0xEA00, dst=0x20) / J1939Request(req_pgn=0xFECC) + ans_unsupp = tester_sock.sr1(req_unsupp, timeout=0.2, verbose=False) + assert ans_unsupp is not None + assert ans_unsupp.pgn == J1939_PGN_ACK + finally: + stop_evt.set() + t.join(timeout=1.0) + cleanup_testsockets() + += J1939_ECU_VIN_AM scanned with j1939_scan_pgns (multi-PGN dict and list) +with TestSocket(CAN) as tester_sock, TestSocket(CAN) as ecu_sock: + tester_sock.pair(ecu_sock) + am = J1939_ECU_VIN_AM(ecu_addr=0x20, vin="1M8GDM9A_KP042788*") + t, stop_evt = am.start_bg(ecu_sock) + try: + # Dict mapping + res_dict = j1939_scan_pgns( + tester_sock, target_da=0x20, + pgns={"VIN": J1939_PGN_VIN, "DM1": 0xFECA}, + sniff_time=0.1, + ) + assert res_dict["VIN"].supported is True + assert res_dict["VIN"].pgn == J1939_PGN_VIN + assert res_dict["DM1"].supported is False + assert res_dict["DM1"].error == "NACK" + + # List mapping + res_list = j1939_scan_pgns( + tester_sock, target_da=0x20, + pgns=[J1939_PGN_VIN, 0xFECA], + sniff_time=0.1, + ) + assert res_list[J1939_PGN_VIN].supported is True + assert res_list[0xFECA].supported is False + assert res_list[0xFECA].error == "NACK" + finally: + stop_evt.set() + t.join(timeout=1.0) + cleanup_testsockets() + += J1939_ECU_VIN_AM single-frame detected by j1939_scan_pgns +with TestSocket(CAN) as tester_sock, TestSocket(CAN) as ecu_sock: + tester_sock.pair(ecu_sock) + am = J1939_ECU_VIN_AM(ecu_addr=0x20, vin=b"VIN12345", tp_mode="none") + t, stop_evt = am.start_bg(ecu_sock) + try: + res = j1939_scan_pgns(tester_sock, target_da=0x20, pgns={"VIN": J1939_PGN_VIN}, sniff_time=0.1)["VIN"] + assert res.supported is True + assert res.pgn == J1939_PGN_VIN + assert res.packet is not None + assert res.packet.data == b"VIN12345" + finally: + stop_evt.set() + t.join(timeout=1.0) + cleanup_testsockets() + ++ J1939_DM_Scanner Automotive Framework Classes +~ automotive_comm + += J1939_DM_Scanner and J1939_PGN_Enumerator direct execution +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_dm_scanner import ( + J1939_DM_Scanner, + J1939_PGN_Enumerator, +) +sock = TestSocket(CAN) +enumerator = J1939_PGN_Enumerator() +scanner = J1939_DM_Scanner(sock, test_cases=[enumerator], target_da=0x20, pgns=[0xFECA], sniff_time=0.01) +scanner.scan() +assert scanner.scan_completed +assert 0xFECA in enumerator.pgn_results +assert enumerator.pgn_results[0xFECA].error == "Timeout" +cleanup_testsockets() + += J1939PgnScanResult equality and representation +from scapy.contrib.automotive.j1939.j1939_dm_scanner import J1939PgnScanResult +res1 = J1939PgnScanResult(0xFECA, True, name="DM1") +assert res1 != "not_a_result" +assert res1 != 123 +res2 = J1939PgnScanResult(0xFECA, True, name="DM1") +assert res1 == res2 + += J1939_PGN_Enumerator ServiceEnumerator methods +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_dm_scanner import ( + J1939_DM_Enumerator, + J1939_DM_PGNS, + J1939_PGN_Enumerator, + J1939_DM_Scanner, +) +from scapy.contrib.automotive.j1939.j1939_scanner import J1939_ACK_CTRL_NACK +from scapy.contrib.j1939 import J1939Ack +enum = J1939_PGN_Enumerator() +ack_pkt = J1939Ack(ctrl=J1939_ACK_CTRL_NACK, pgn=0xFECA) +assert enum._get_negative_response_code(ack_pkt) == J1939_ACK_CTRL_NACK +assert enum._get_negative_response_desc(J1939_ACK_CTRL_NACK) == "NACK" +assert enum._get_negative_response_desc(0x02) == "2" +assert enum._get_negative_response_label(ack_pkt) == "NACK" + +reqs_dict = list(enum._get_initial_requests(pgns={"DM1": 0xFECA}, target_da=0x20, src_addr=0xF9)) +assert len(reqs_dict) == 1 +assert reqs_dict[0].req_pgn == 0xFECA + +reqs_list = list(enum._get_initial_requests(pgns=[0xFECA], target_da=0x20, src_addr=0xF9)) +assert len(reqs_list) == 1 +assert reqs_list[0].req_pgn == 0xFECA + +dm_enum = J1939_DM_Enumerator() +reqs_dm = list(dm_enum._get_initial_requests(target_da=0x20, src_addr=0xF9)) +assert len(reqs_dm) == len(J1939_DM_PGNS) + +dummy_sock = TestSocket(CAN) +dm_scanner = J1939_DM_Scanner(dummy_sock) +assert dm_scanner.default_test_case_clss == [J1939_DM_Enumerator] +cleanup_testsockets() + += J1939_PGN_Enumerator stop_event abort in loop +from threading import Event +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_dm_scanner import j1939_scan_pgns +sock = TestSocket(CAN) +evt = Event() +evt.set() +res_aborted = j1939_scan_pgns(sock, target_da=0x20, pgns=[0xFECA, 0xFECB], stop_event=evt) +assert res_aborted[0xFECA].error == "Aborted" +assert res_aborted[0xFECB].error == "Aborted" +cleanup_testsockets() + += J1939_PGN_Enumerator multi-probe with reconnect_handler +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_dm_scanner import j1939_scan_pgns +sock = TestSocket(CAN) +socks_created = [] +def reconnect(): + s = TestSocket(CAN) + socks_created.append(s) + return s + +res_recon = j1939_scan_pgns( + sock, + target_da=0x20, + pgns=[0xFECA, 0xFECB, 0xFECC], + sniff_time=0.01, + reconnect_handler=reconnect, + retry_delay=0.001, +) +assert len(res_recon) == 3 +assert res_recon[0xFECA].error == "Timeout" +assert res_recon[0xFECB].error == "Timeout" +assert res_recon[0xFECC].error == "Timeout" +assert len(socks_created) >= 2 +cleanup_testsockets() + += J1939_PGN_Enumerator raw byte ACK fallback and RTS abort handling +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import J1939_ACK_CTRL_NACK +from scapy.contrib.j1939 import ( + j1939_to_can_id, + J1939_TP_CM_RTS, + J1939_PGN_ACK, + J1939_PGN_TP_CM, +) +from scapy.contrib.automotive.j1939.j1939_dm_scanner import j1939_scan_pgns + +sock_ack = TestSocket(CAN) +ack_id = j1939_to_can_id(6, 0, 0, (J1939_PGN_ACK >> 8) & 0xFF, 0xF9, 0x20) +ack_payload = bytes([J1939_ACK_CTRL_NACK, 0xFF, 0xFF, 0xFF, 0xFF, 0xCA, 0xFE, 0x00]) +sock_ack.ins.send(bytes(CAN(identifier=ack_id, flags="extended", data=ack_payload))) +res_raw_ack = j1939_scan_pgns(sock_ack, target_da=0x20, pgns=[0xFECA], sniff_time=0.05) +assert res_raw_ack[0xFECA].supported is False +assert res_raw_ack[0xFECA].error == "NACK" +cleanup_testsockets() + +sock_rts = TestSocket(CAN) +rts_id = j1939_to_can_id(7, 0, 0, (J1939_PGN_TP_CM >> 8) & 0xFF, 0xF9, 0x20) +rts_data = bytes(J1939_TP_CM_RTS(total_size=10, num_packets=2, max_packets=0xFF, pgn=0xFECA)) +sock_rts.ins.send(bytes(CAN(identifier=rts_id, flags="extended", data=rts_data))) +res_rts = j1939_scan_pgns(sock_rts, target_da=0x20, pgns=[0xFECA], sniff_time=0.05) +assert res_rts[0xFECA].supported is True +cleanup_testsockets() + + diff --git a/test/contrib/automotive/j1939_name.uts b/test/contrib/automotive/j1939_name.uts new file mode 100644 index 00000000000..45f383c2ee6 --- /dev/null +++ b/test/contrib/automotive/j1939_name.uts @@ -0,0 +1,207 @@ +% Regression tests for J1939 64-bit NAME (J1939-81) +~ automotive_comm + ++ Configuration +~ conf + += Imports +from scapy.contrib.automotive.j1939 import ( + J1939Name, + J1939_INDUSTRY_GROUPS, + J1939_INDUSTRY_SPECIFIC_FUNCTIONS, + J1939_INDUSTRY_SPECIFIC_VEHICLE_SYSTEMS, + J1939_MANUFACTURERS, + J1939_PRE_ASSIGNED_FUNCTIONS, + j1939_format_name_function, + j1939_format_name_industry_group, + j1939_format_name_manufacturer, + j1939_format_name_vehicle_system, +) + += J1939 registries have expected entries +assert 1 in J1939_INDUSTRY_GROUPS +assert 0 in J1939_PRE_ASSIGNED_FUNCTIONS +assert J1939_PRE_ASSIGNED_FUNCTIONS[0] == "Engine" +assert 1 in J1939_INDUSTRY_SPECIFIC_FUNCTIONS +assert 1 in J1939_INDUSTRY_SPECIFIC_VEHICLE_SYSTEMS +assert 161 in J1939_MANUFACTURERS +assert 10 in J1939_PRE_ASSIGNED_FUNCTIONS +assert J1939_PRE_ASSIGNED_FUNCTIONS[10] == "Brakes - Steer Axle" +assert 81 in J1939_PRE_ASSIGNED_FUNCTIONS +assert 82 not in J1939_PRE_ASSIGNED_FUNCTIONS +assert j1939_format_name_function(82) == "Pre-Assigned / Reserved Function (82)" +assert j1939_format_name_function(85) == "Pre-Assigned / Reserved Function (85)" + + ++ J1939Name Packet tests + += J1939Name: default size is 8 bytes +pkt = J1939Name() +assert len(bytes(pkt)) == 8 + += J1939Name: round trip build and dissect +pkt = J1939Name( + arbitrary_address_capable=1, + industry_group=1, + vehicle_system_instance=2, + vehicle_system=3, + reserved=0, + function=0, + function_instance=1, + ecu_instance=2, + manufacturer_code=161, + identity_number=42, +) +raw = bytes(pkt) +assert len(raw) == 8 +decoded = J1939Name(raw) +assert decoded.arbitrary_address_capable == 1 +assert decoded.industry_group == 1 +assert decoded.vehicle_system_instance == 2 +assert decoded.vehicle_system == 3 +assert decoded.reserved == 0 +assert decoded.function == 0 +assert decoded.function_instance == 1 +assert decoded.ecu_instance == 2 +assert decoded.manufacturer_code == 161 +assert decoded.identity_number == 42 + += J1939Name: format helpers and descriptions +pkt = J1939Name( + arbitrary_address_capable=1, + industry_group=1, + vehicle_system=1, + function=0, + manufacturer_code=161, + identity_number=100, +) +assert j1939_format_name_function(pkt) == "Engine" +assert j1939_format_name_function(pkt.function, pkt.industry_group) == "Engine" +assert "Volvo" in j1939_format_name_manufacturer(pkt) +assert "Volvo" in j1939_format_name_manufacturer(pkt.manufacturer_code) +assert "On-Highway" in j1939_format_name_industry_group(pkt) +assert "On-Highway" in j1939_format_name_industry_group(pkt.industry_group) +assert j1939_format_name_function(10) == "Brakes - Steer Axle" +assert j1939_format_name_industry_group(1) == "On-Highway Equipment (Trucks, Buses, Coaches)" +assert j1939_format_name_industry_group(99) == "99" +assert j1939_format_name_manufacturer(161) == "Volvo Lastvagnar AB" +assert j1939_format_name_manufacturer(9999) == "9999" +assert isinstance(j1939_format_name_vehicle_system(pkt), str) +assert isinstance(j1939_format_name_vehicle_system(pkt.vehicle_system, pkt.industry_group), str) +assert isinstance(pkt.raw_value(), int) +assert "On-Highway" in pkt.sprintf("%J1939Name.industry_group%") +assert pkt.sprintf("%J1939Name.manufacturer_code%") == "Volvo Lastvagnar AB" + += J1939Name: summary and mysummary +assert "Engine" in pkt.mysummary() +assert "Engine" in pkt.summary() + += J1939Name: show output +output = pkt.show(dump=True) +assert "arbitrary_address_capable" in output +assert "manufacturer_code" in output +assert "identity_number" in output + += J1939Name: function descriptions (pre-assigned, industry-specific, error, not available) +pkt_ind = J1939Name(function=130, industry_group=1) +assert "Function 130" in j1939_format_name_function(pkt_ind) or pkt_ind.function == 130 + +pkt_err = J1939Name(function=254) +assert j1939_format_name_function(pkt_err) == "Error State" + +pkt_na = J1939Name(function=255) +assert j1939_format_name_function(pkt_na) == "Not Available" + += Socket integration: wrap J1939Name in J1939 frame +from scapy.contrib.j1939 import J1939, J1939_PGN_ADDRESS_CLAIMED +name_pkt = J1939Name(identity_number=42, manufacturer_code=161) +frame = J1939(pgn=J1939_PGN_ADDRESS_CLAIMED, data=bytes(name_pkt)) +parsed = J1939Name(frame.data) +assert parsed.identity_number == 42 +assert parsed.manufacturer_code == 161 + + += J1939Name: constructor from pre-converted byte formats +from scapy.layers.can import CAN + +val = 0x9000000000000001 +res_int = J1939Name(val.to_bytes(8, "little")) +res_hex = J1939Name(bytes.fromhex("0100000000000090")) +res_hex_0x = J1939Name(bytes.fromhex("0x0100000000000090".replace("0x", ""))) +res_bytes = J1939Name(b"\x01\x00\x00\x00\x00\x00\x00\x90") +can_pkt = CAN(data=b"\x01\x00\x00\x00\x00\x00\x00\x90") +res_can = J1939Name(bytes(can_pkt.data)) +assert res_int.raw_value() == res_hex.raw_value() == res_hex_0x.raw_value() == res_bytes.raw_value() == res_can.raw_value() +assert res_int.identity_number == 1 +assert res_int.arbitrary_address_capable == 1 + + ++ j1939_name_arbitration tests + += j1939_name_arbitration: lower numerical value wins +def j1939_name_arbitration(name1, name2): + pkt1 = name1 if isinstance(name1, J1939Name) else J1939Name(name1) + pkt2 = name2 if isinstance(name2, J1939Name) else J1939Name(name2) + val1 = pkt1.raw_value() + val2 = pkt2.raw_value() + if val1 == val2: + return {"winner": None, "loser": None, "collision": True} + if val1 < val2: + winner, loser = "ECU A", "ECU B" + win_pkt, lose_pkt = pkt1, pkt2 + else: + winner, loser = "ECU B", "ECU A" + win_pkt, lose_pkt = pkt2, pkt1 + return { + "winner": winner, + "loser": loser, + "win_name": win_pkt, + "lose_name": lose_pkt, + "collision": False, + } + +simulate_arbitration = j1939_name_arbitration + +name_a = b"\x01\x00\x00\x00\x00\x00\x00\x10" +name_b = b"\x02\x00\x00\x00\x00\x00\x00\x10" +res = j1939_name_arbitration(name_a, name_b) +assert res["winner"] == "ECU A" +assert res["loser"] == "ECU B" +assert res["collision"] is False +assert isinstance(res["win_name"], J1939Name) +assert isinstance(res["lose_name"], J1939Name) + += j1939_name_arbitration: collision detection +res = j1939_name_arbitration(name_a, name_a) +assert res["collision"] is True +assert res["winner"] is None + += j1939_name_arbitration: ECU B wins and arbitrary address capable loser +name_a = b"\x02\x00\x00\x00\x00\x00\x00\x90" # Bit 63 = 1 +name_b = b"\x01\x00\x00\x00\x00\x00\x00\x90" # Bit 63 = 1, lower value +res = j1939_name_arbitration(name_a, name_b) +assert res["winner"] == "ECU B" +assert res["loser"] == "ECU A" + + += J1939Name dissects truncated and short frames gracefully +from scapy.config import conf +_old_dbg = conf.debug_dissector +try: + conf.debug_dissector = True + _j_name_short = J1939(b"X", pgn=J1939_PGN_ADDRESS_CLAIMED, dst=0xFF) + assert not _j_name_short.haslayer(J1939Name) + assert _j_name_short.data == b"X" + _j_name_ok = J1939(b"\x00" * 8, pgn=J1939_PGN_ADDRESS_CLAIMED, dst=0xFF) + assert _j_name_ok.haslayer(J1939Name) +finally: + conf.debug_dissector = _old_dbg + += J1939Name payload dissection and stacking +from scapy.packet import Raw +name_raw = J1939Name(bytes(J1939Name()) + b"trailing_payload") +assert name_raw.haslayer(Raw) +assert name_raw[Raw].load == b"trailing_payload" + +True + diff --git a/test/contrib/automotive/j1939_scanner.uts b/test/contrib/automotive/j1939_scanner.uts new file mode 100644 index 00000000000..8f8374ce12e --- /dev/null +++ b/test/contrib/automotive/j1939_scanner.uts @@ -0,0 +1,3429 @@ +% Regression tests for J1939 CA Scanner +~ automotive_comm scanner + ++ Configuration +~ conf + += Imports +from scapy.layers.can import CAN +from scapy.contrib.j1939 import ( + J1939, + J1939Request, + J1939_GLOBAL_ADDRESS, + J1939_NULL_ADDRESS, + J1939_PGN_ACK, + J1939_PGN_ADDRESS_CLAIMED, + J1939_PGN_DIAG_A, + J1939_PGN_DIAG_B, + J1939_PGN_REQUEST, + J1939_PGN_TP_CM, + J1939_TP_CM_RTS, + J1939_TP_CTRL_ABORT, + J1939_TP_CTRL_BAM, + J1939_TP_CTRL_CTS, + J1939_TP_CTRL_RTS, + can_id_to_j1939, + j1939_to_can_id, +) +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_ACK_CTRL_ACCESS_DENIED, + J1939_ACK_CTRL_CANNOT_RESPOND, + J1939_ACK_CTRL_NACK, + J1939_DEFAULT_BITRATE, + J1939_DEFAULT_BUSLOAD, + J1939_DIAGADAPTERS_ADDRESSES, + J1939_PGN_ECU_ID, + J1939_PGN_XCP, + J1939_UDS_TESTER_PRESENT_REQS, + J1939_XCP_CONNECT_REQ, + J1939_SCAN_METHODS, + J1939_XCP_POSITIVE_RESPONSE, + J1939_XCP_SRC_ADDRS, + J1939ScanResult, + j1939_inter_probe_delay, + j1939_sa_filter, + j1939_scan, + j1939_scan_addr_claim, + j1939_scan_ecu_id, + j1939_scan_passive, + j1939_scan_rts_probe, + j1939_scan_uds, + j1939_scan_unicast, + j1939_scan_xcp, +) +from scapy.error import Scapy_Exception +from test.testsocket import TestSocket, SlowTestSocket, cleanup_testsockets + +J1939_PF_ACK = (J1939_PGN_ACK >> 8) & 0xFF +J1939_PF_ADDRESS_CLAIMED = (J1939_PGN_ADDRESS_CLAIMED >> 8) & 0xFF +J1939_PF_DIAG_A = (J1939_PGN_DIAG_A >> 8) & 0xFF +J1939_PF_DIAG_B = (J1939_PGN_DIAG_B >> 8) & 0xFF +J1939_PF_REQUEST = (J1939_PGN_REQUEST >> 8) & 0xFF +J1939_PF_XCP = (J1939_PGN_XCP >> 8) & 0xFF +J1939_TP_CM_PF = (J1939_PGN_TP_CM >> 8) & 0xFF + += Redirect logging +import logging +from scapy.error import log_runtime +from io import StringIO +log_stream = StringIO() +handler = logging.StreamHandler(log_stream) +log_runtime.addHandler(handler) +j1939_logger = logging.getLogger("scapy.contrib.automotive.j1939") +j1939_logger.addHandler(handler) + + ++ Scanner constants + += J1939_PGN_ECU_ID is 64965 (0xFDC5) +assert J1939_PGN_ECU_ID == 64965 +assert J1939_PGN_ECU_ID == 0xFDC5 + += J1939_SCAN_METHODS contains all six technique names +assert set(J1939_SCAN_METHODS) == {"addr_claim", "ecu_id", "unicast", "rts_probe", "uds", "xcp"} + += J1939_DIAGADAPTERS_ADDRESSES is [0xF1..0xFD] (13 diagnostic source addresses) +assert J1939_DIAGADAPTERS_ADDRESSES == list(range(0xF1, 0xFE)) +assert len(J1939_DIAGADAPTERS_ADDRESSES) == 13 + += J1939_XCP_SRC_ADDRS is the expanded list of diagnostic source addresses +assert J1939_XCP_SRC_ADDRS == ([0x3F, 0x5A] + list(range(0x01, 0x10)) + [0xAC] + list(range(0xF1, 0xFE))) +assert len(J1939_XCP_SRC_ADDRS) == 31 + += J1939_PF_XCP is 0xEF (XCP Proprietary A PF byte) +assert J1939_PF_XCP == 0xEF + += J1939Request encodes J1939_PGN_ADDRESS_CLAIMED correctly +# PGN 60928 = 0xEE00: LE 3 bytes = \x00 \xEE \x00 +payload = bytes(J1939Request(req_pgn=J1939_PGN_ADDRESS_CLAIMED)) +assert payload == b'\x00\xee\x00', "Got {}".format(payload.hex()) + += J1939Request encodes J1939_PGN_ECU_ID correctly +# PGN 64965 = 0xFDC5: LE 3 bytes = \xC5 \xFD \x00 +payload = bytes(J1939Request(req_pgn=J1939_PGN_ECU_ID)) +assert payload == b'\xc5\xfd\x00', "Got {}".format(payload.hex()) + + ++ Technique 1 – Global Address Claim Request + += addr_claim: sends a broadcast Request for J1939_PGN_ADDRESS_CLAIMED +def test_addr_claim_probe_frame(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_addr_claim(tx_sock, listen_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1, "Expected 1 probe frame, got {}".format(len(pkts)) + probe = pkts[0] + f = can_id_to_j1939(probe.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + assert probe.flags & 0x4, "Expected extended CAN frame" + assert pf == J1939_PF_REQUEST, "PF should be 0xEA (Request)" + assert ps == J1939_GLOBAL_ADDRESS, "DA should be 0xFF (global)" + assert sa == 0xF9, "SA should be 0xF9" + assert bytes(probe.data) == bytes(J1939Request(req_pgn=J1939_PGN_ADDRESS_CLAIMED)) + cleanup_testsockets() + +test_addr_claim_probe_frame() + += addr_claim: receives Address Claimed reply and returns SA +sock = TestSocket(CAN) +# Inject a fake Address Claimed reply from SA=0x10 +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x10) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x01\x02\x03\x04\x05\x06\x07\x08'))) +found = j1939_scan_addr_claim(sock, listen_time=0.1) +assert 0x10 in found, "Expected SA=0x10, got: {}".format([hex(k) for k in found]) +assert isinstance(found[0x10], list) +assert len(found[0x10]) == 1 +cleanup_testsockets() + += addr_claim: multiple replies from different SAs are all captured +def test_addr_claim_multiple(): + sock = TestSocket(CAN) + for sa_val in [0x10, 0x20, 0x30]: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, sa_val) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + found = j1939_scan_addr_claim(sock, listen_time=0.2) + assert set(found.keys()) == {0x10, 0x20, 0x30}, \ + "Expected three SAs, got: {}".format([hex(k) for k in found]) + assert all(isinstance(v, list) and len(v) == 1 for v in found.values()) + cleanup_testsockets() + +test_addr_claim_multiple() + += addr_claim: non-extended (11-bit) frames are ignored +sock = TestSocket(CAN) +# 11-bit frame has flags=0 (no extended bit) +non_ext_can_id = 0x040 # some 11-bit id +sock.ins.send(bytes(CAN(identifier=non_ext_can_id, data=b'\x01\x02\x03'))) +found = j1939_scan_addr_claim(sock, listen_time=0.1) +assert len(found) == 0, "Should not detect 11-bit CAN frames" +cleanup_testsockets() + += addr_claim: returns empty dict when no responses +sock = TestSocket(CAN) +found = j1939_scan_addr_claim(sock, listen_time=0.05) +assert found == {}, "Expected empty result" +cleanup_testsockets() + + ++ Technique 2 – Global ECU ID Request + += ecu_id: sends a broadcast Request for J1939_PGN_ECU_ID +def test_ecu_id_probe_frame(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_ecu_id(tx_sock, listen_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1 + probe = pkts[0] + f = can_id_to_j1939(probe.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + assert probe.flags & 0x4, "Expected extended CAN frame" + assert pf == J1939_PF_REQUEST, "PF should be Request (0xEA)" + assert ps == J1939_GLOBAL_ADDRESS, "DA should be global (0xFF)" + assert bytes(probe.data) == bytes(J1939Request(req_pgn=J1939_PGN_ECU_ID)) + cleanup_testsockets() + +test_ecu_id_probe_frame() + += ecu_id: detects BAM announce header for J1939_PGN_ECU_ID +sock = TestSocket(CAN) +ecu_pgn_le = bytes(J1939Request(req_pgn=J1939_PGN_ECU_ID)) +bam_can_id = j1939_to_can_id(6, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x20) +# BAM payload: [ctrl=0x20][size LE2][num_pkts][0xFF][pgn 3 bytes LE] +bam_payload = bytes([0x20, 0x0A, 0x00, 0x02, 0xFF]) + ecu_pgn_le +sock.ins.send(bytes(CAN(identifier=bam_can_id, flags="extended", + data=bam_payload))) +found = j1939_scan_ecu_id(sock, listen_time=0.1) +assert 0x20 in found, "Expected SA=0x20" +assert isinstance(found[0x20], list) +assert len(found[0x20]) == 1 +cleanup_testsockets() + += ecu_id: multiple responders to broadcast request +sock = TestSocket(CAN) +ecu_pgn_le = bytes(J1939Request(req_pgn=J1939_PGN_ECU_ID)) +bam_20 = j1939_to_can_id(6, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x20) +bam_21 = j1939_to_can_id(6, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x21) +bam_payload = bytes([0x20, 0x0A, 0x00, 0x02, 0xFF]) + ecu_pgn_le +sock.ins.send(bytes(CAN(identifier=bam_20, flags="extended", data=bam_payload))) +sock.ins.send(bytes(CAN(identifier=bam_21, flags="extended", data=bam_payload))) +found = j1939_scan_ecu_id(sock, listen_time=0.1) +assert set(found.keys()) == {0x20, 0x21} +cleanup_testsockets() + + += ecu_id: ignores BAM for a different PGN +sock = TestSocket(CAN) +other_pgn_le = bytes(J1939Request(req_pgn=J1939_PGN_ADDRESS_CLAIMED)) # different PGN +bam_can_id = j1939_to_can_id(6, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x22) +bam_payload = bytes([0x20, 0x09, 0x00, 0x02, 0xFF]) + other_pgn_le +sock.ins.send(bytes(CAN(identifier=bam_can_id, flags="extended", + data=bam_payload))) +found = j1939_scan_ecu_id(sock, listen_time=0.1) +assert len(found) == 0, "Should not match BAM for a different PGN" +cleanup_testsockets() + += ecu_id: ignores non-TP.CM frames +sock = TestSocket(CAN) +# Inject an Address Claimed frame (not a TP.CM) +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x25) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +found = j1939_scan_ecu_id(sock, listen_time=0.1) +assert len(found) == 0, "ecu_id should ignore non-TP.CM frames" +cleanup_testsockets() + += addr_claim: firewall simulation - only SA=0xAC can elicit response +def test_addr_claim_firewall(): + import threading + import time + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + + def simulate_ecu(): + # Listen for requests and only reply if SA is 0xAC + while True: + pkts = monitor.sniff(count=1, timeout=0.5) + if not pkts: break + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST and ps == J1939_GLOBAL_ADDRESS and sa == 0xAC: + # ECU at 0x10 responds + resp = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x10) + sock.ins.send(bytes(CAN(identifier=resp, flags="extended", data=b'\x00'*8))) + + t = threading.Thread(target=simulate_ecu) + t.start() + + # Probe from multiple SAs including 0xAC + found = j1939_scan_addr_claim(sock, src_addrs=[0xF1, 0xAC, 0xF2], listen_time=0.1) + t.join() + + assert 0x10 in found, "ECU 0x10 should be found via SA 0xAC" + # Since the scanner is iterative, it should have recorded 0xAC as the successful SA + assert found[0x10][0].scanner_src == 0xAC, "Expected successful SA 0xAC, got: {}".format(found[0x10][0].scanner_src) + cleanup_testsockets() + +test_addr_claim_firewall() + += ecu_id: firewall simulation - only SA=0xAC can elicit response +def test_ecu_id_firewall(): + import threading + import time + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + ecu_pgn_le = bytes(J1939Request(req_pgn=J1939_PGN_ECU_ID)) + + def simulate_ecu(): + while True: + pkts = monitor.sniff(count=1, timeout=0.5) + if not pkts: break + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST and ps == J1939_GLOBAL_ADDRESS and sa == 0xAC: + # ECU at 0x20 responds with BAM header + resp = j1939_to_can_id(6, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x20) + payload = bytes([0x20, 0x0A, 0x00, 0x02, 0xFF]) + ecu_pgn_le + sock.ins.send(bytes(CAN(identifier=resp, flags="extended", data=payload))) + + t = threading.Thread(target=simulate_ecu) + t.start() + + found = j1939_scan_ecu_id(sock, src_addrs=[0xF1, 0xAC, 0xF2], listen_time=0.1) + t.join() + + assert 0x20 in found, "ECU 0x20 should be found via SA 0xAC" + assert found[0x20][0].scanner_src == 0xAC, "Expected successful SA 0xAC, got: {}".format(found[0x20][0].scanner_src) + cleanup_testsockets() + +test_ecu_id_firewall() + + ++ Technique 3 – Unicast Ping Sweep + += unicast: sends a Request to each DA in scan_range +def test_unicast_probe_frames(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_unicast(tx_sock, scan_range=[0x01, 0x02, 0x03], + sniff_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=3, timeout=0.5) + assert len(pkts) == 3, "Expected 3 probe frames" + das = set() + for pkt in pkts: + f = can_id_to_j1939(pkt.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + assert pf == J1939_PF_REQUEST, "PF should be Request" + das.add(ps) + assert das == {0x01, 0x02, 0x03}, "DA values should match scan_range" + cleanup_testsockets() + +test_unicast_probe_frames() + += unicast: detects reply from the probed SA directed to 0xF9 +sock = TestSocket(CAN) +# Response from SA=0x30 (Address Claimed from that node) directed to 0xF9 +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, 0xF9, 0x30) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +found = j1939_scan_unicast(sock, scan_range=[0x30], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x30 in found, "Expected SA=0x30 in results" +assert isinstance(found[0x30], list) +assert len(found[0x30]) == 1 +cleanup_testsockets() + += unicast: ignores echoes of Request probes (PF=0xEA) +sock = TestSocket(CAN) +# Simulated echo: Request from 0xF9 to 0xF9 (PF=0xEA, PS=0xF9, SA=0xF9) +# This frame has sa == _da if we are probing 0xF9, but pf == 0xEA +echo_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_REQUEST, 0xF9, 0xF9) +sock.ins.send(bytes(CAN(identifier=echo_can_id, flags="extended", + data=b'\x00\xee\x00'))) +found = j1939_scan_unicast(sock, scan_range=[0xF9], sniff_time=0.1, src_addrs=[0xF9]) +assert 0xF9 not in found, "Scanner must ignore echoes of its own Request probes" +cleanup_testsockets() + += unicast: accepts broadcast Address Claimed response (PS=0xFF) to unicast probe +sock = TestSocket(CAN) +# Response from SA=0x30 directed to Global Address (0xFF) +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x30) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +found = j1939_scan_unicast(sock, scan_range=[0x30], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x30 in found, "Expected SA=0x30 via broadcast Address Claimed hit" +cleanup_testsockets() + += unicast: does not report SA that is not in scan_range +sock = TestSocket(CAN) +# Inject response from SA=0x55 while we only probe 0x30, directed to 0xF9 +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, 0xF9, 0x55) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +found = j1939_scan_unicast(sock, scan_range=[0x30], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x55 not in found, "SA=0x55 is not in scan_range" +cleanup_testsockets() + += unicast: payload of probe is Request for J1939_PGN_ADDRESS_CLAIMED +def test_unicast_probe_payload(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_unicast(tx_sock, scan_range=[0x42], sniff_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1 + assert bytes(pkts[0].data) == bytes(J1939Request(req_pgn=J1939_PGN_ADDRESS_CLAIMED)) + cleanup_testsockets() + +test_unicast_probe_payload() + += unicast: returns empty dict when no responses +sock = TestSocket(CAN) +found = j1939_scan_unicast(sock, scan_range=[0x10, 0x11], sniff_time=0.02, src_addrs=[0xF9]) +assert found == {} +cleanup_testsockets() + += unicast: accepts broadcast (DA=0xFF) address claim response +sock = TestSocket(CAN) +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x42) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", data=b'\x00' * 8))) +found = j1939_scan_unicast(sock, scan_range=[0x42], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x42 in found +assert len(found[0x42]) == 1 +cleanup_testsockets() + + + ++ Technique 4 – TP.CM RTS Probing + += rts_probe: sends a TP.CM_RTS frame to each DA in scan_range +def test_rts_probe_frames(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_rts_probe(tx_sock, scan_range=[0x05, 0x06], sniff_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=2, timeout=0.5) + assert len(pkts) == 2, "Expected 2 RTS probe frames" + for pkt in pkts: + f = can_id_to_j1939(pkt.identifier); pf = f['pdu_format'] + assert pf == J1939_TP_CM_PF, "PF should be TP.CM (0xEC)" + assert bytes(pkt.data)[0] == 0x10, "First byte should be J1939_TP_CTRL_RTS (0x10)" + cleanup_testsockets() + +test_rts_probe_frames() + += rts_probe: detects CTS reply from probed node +sock = TestSocket(CAN) +# CTS response from SA=0x40, to SA=0xF9 (our probe SA) +cts_can_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x40) +sock.ins.send(bytes(CAN(identifier=cts_can_id, flags="extended", + data=bytes([J1939_TP_CTRL_CTS, 0x02, 0x01, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +found = j1939_scan_rts_probe(sock, scan_range=[0x40], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x40 in found, "Expected SA=0x40 via CTS reply" +assert isinstance(found[0x40], list) +assert len(found[0x40]) == 1 +cleanup_testsockets() + += rts_probe: detects Conn_Abort reply from probed node +sock = TestSocket(CAN) +# Conn_Abort response (SA=0x41 sent an abort) directed to 0xF9 +abort_can_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x41) +sock.ins.send(bytes(CAN(identifier=abort_can_id, flags="extended", + data=bytes([J1939_TP_CTRL_ABORT, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +found = j1939_scan_rts_probe(sock, scan_range=[0x41], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x41 in found, "Expected SA=0x41 via Conn_Abort reply" +assert isinstance(found[0x41], list) +assert len(found[0x41]) == 1 +cleanup_testsockets() + += rts_probe: detects NACK on Acknowledgment PGN from probed node +sock = TestSocket(CAN) +# NACK response (SA=0x42, ctrl=0x01 NACK) directed to scanner SA 0xF9 +nack_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, 0xF9, 0x42) +sock.ins.send(bytes(CAN(identifier=nack_can_id, flags="extended", + data=bytes([J1939_ACK_CTRL_NACK, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +found = j1939_scan_rts_probe(sock, scan_range=[0x42], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x42 in found, "Expected SA=0x42 via NACK reply on ACK PGN" +assert isinstance(found[0x42], list) +assert len(found[0x42]) == 1 +cleanup_testsockets() + += rts_probe: detects Access Denied on Acknowledgment PGN from probed node +sock = TestSocket(CAN) +# Access Denied response (SA=0x43, ctrl=0x02) directed to scanner SA 0xF9 +ack_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, 0xF9, 0x43) +sock.ins.send(bytes(CAN(identifier=ack_can_id, flags="extended", + data=bytes([J1939_ACK_CTRL_ACCESS_DENIED, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +found = j1939_scan_rts_probe(sock, scan_range=[0x43], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x43 in found, "Expected SA=0x43 via Access Denied reply on ACK PGN" +assert len(found[0x43]) == 1 +cleanup_testsockets() + += rts_probe: detects Cannot Respond on Acknowledgment PGN from probed node +sock = TestSocket(CAN) +# Cannot Respond (SA=0x44, ctrl=0x03) directed to scanner SA 0xF9 +ack_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, 0xF9, 0x44) +sock.ins.send(bytes(CAN(identifier=ack_can_id, flags="extended", + data=bytes([J1939_ACK_CTRL_CANNOT_RESPOND, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +found = j1939_scan_rts_probe(sock, scan_range=[0x44], sniff_time=0.1, src_addrs=[0xF9]) +assert 0x44 in found, "Expected SA=0x44 via Cannot Respond reply on ACK PGN" +assert len(found[0x44]) == 1 +cleanup_testsockets() + += rts_probe: ignores positive ACK (ctrl=0x00) on Acknowledgment PGN +sock = TestSocket(CAN) +# Positive ACK (ctrl=0x00) should NOT be treated as presence confirmation +ack_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, 0xF9, 0x45) +sock.ins.send(bytes(CAN(identifier=ack_can_id, flags="extended", + data=bytes([0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +found = j1939_scan_rts_probe(sock, scan_range=[0x45], sniff_time=0.1, src_addrs=[0xF9]) +assert len(found) == 0, "Positive ACK should not trigger RTS probe detection" +cleanup_testsockets() + += rts_probe: ignores non-TP.CM / non-ACK responses +sock = TestSocket(CAN) +# An Address Claimed frame from SA=0x45 should NOT trigger detection +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, 0xF9, 0x45) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +found = j1939_scan_rts_probe(sock, scan_range=[0x45], sniff_time=0.1, src_addrs=[0xF9]) +assert len(found) == 0, "rts_probe should only respond to TP.CM or ACK frames" +cleanup_testsockets() + += rts_probe: RTS payload has correct format (8 bytes, ctrl=0x10) +def test_rts_probe_payload_format(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_rts_probe(tx_sock, scan_range=[0x50], sniff_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1 + rts_pkt = J1939_TP_CM_RTS(bytes(pkts[0].data)) + assert rts_pkt.ctrl == 0x10, "Byte 0 must be J1939_TP_CTRL_RTS (0x10)" + assert rts_pkt.total_size == 9, "Message size should be 9" + assert rts_pkt.num_packets == 2, "Total packets should be 2" + assert rts_pkt.pgn == 0x0000FF, "PGN should be 0x0000FF" + cleanup_testsockets() + +test_rts_probe_payload_format() + += rts_probe: returns empty dict when no responses +sock = TestSocket(CAN) +found = j1939_scan_rts_probe(sock, scan_range=[0x10, 0x11], sniff_time=0.02, src_addrs=[0xF9]) +assert found == {} +cleanup_testsockets() + + ++ Top-level j1939_scan combinator + += j1939_scan: raises ValueError for unknown method name +def test_scan_invalid_method(): + sock = TestSocket(CAN) + try: + j1939_scan(sock, methods=["invalid_method"]) + assert False, "Expected ValueError" + except ValueError as e: + assert "invalid_method" in str(e) + cleanup_testsockets() + +test_scan_invalid_method() + += j1939_scan: merges results from multiple methods; addr_claim is first discoverer +# addr_claim finds SA=0x10 first; unicast also gets a spurious 0x10 response +sock = TestSocket(CAN) +# Response for addr_claim (SA=0x10) +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x10) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +# noise_ids=set() bypasses the passive pre-scan, so the pre-injected response +# frame is available for the active addr_claim method to receive. +found = j1939_scan(sock, scan_range=[0x10], methods=["addr_claim", "unicast"], + broadcast_listen_time=0.1, sniff_time=0.02, noise_ids=set()) +assert 0x10 in found, "SA=0x10 should be found" +# First method that found it should be addr_claim +assert found[0x10]["methods"][0] == "addr_claim", \ + "Expected addr_claim but got {}".format(found[0x10]["methods"][0]) +assert isinstance(found[0x10]["packets"], list) +assert len(found[0x10]["packets"]) == 1 +assert isinstance(found[0x10]["packets"][0], list) +cleanup_testsockets() + += j1939_scan: result dict has 'methods' and 'packets' keys +sock = TestSocket(CAN) +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x11) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +# noise_ids=set() bypasses the passive pre-scan so the pre-injected response is available. +found = j1939_scan(sock, methods=["addr_claim"], broadcast_listen_time=0.1, noise_ids=set()) +assert 0x11 in found +assert "methods" in found[0x11], "Expected 'methods' key" +assert "packets" in found[0x11], "Expected 'packets' key" +assert isinstance(found[0x11]["packets"], list), "'packets' must be a list" +assert found[0x11]["methods"] == ["addr_claim"] +assert len(found[0x11]["packets"]) == 1, "Single detection: packets list must have 1 entry" +assert isinstance(found[0x11]["packets"][0], list) +cleanup_testsockets() + += j1939_scan: stop_event halts scan immediately +def test_scan_stop_event(): + from threading import Event + ev = Event() + ev.set() # already set -> should return immediately without any probes + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + found = j1939_scan(sock, methods=["addr_claim", "unicast"], + scan_range=range(0xFE), broadcast_listen_time=0.1, + stop_event=ev) + # stop_event was set before any method ran; no probes should have been sent + probes = monitor.sniff(count=1, timeout=0.1) + assert len(probes) == 0, "No probes should be sent when stop_event is set" + cleanup_testsockets() + +test_scan_stop_event() + += j1939_scan: single-method call (unicast only) +sock = TestSocket(CAN) +# Use 0xF9 as destination for Address Claimed response to match scanner default src_addr +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, 0xF9, 0x30) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) +found = j1939_scan(sock, methods=["unicast"], scan_range=[0x30], sniff_time=0.1, + noise_ids=set(), src_addrs=[0xF9]) +assert 0x30 in found +assert found[0x30]["methods"] == ["unicast"] +assert isinstance(found[0x30]["packets"], list) +assert len(found[0x30]["packets"]) == 1 +assert isinstance(found[0x30]["packets"][0], list) +cleanup_testsockets() + += j1939_scan: rts_probe NACK on ACK PGN is detected and merged +sock = TestSocket(CAN) +# NACK response (SA=0x31, ctrl=0x01 NACK) directed to scanner SA 0xF9 +nack_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ACK, 0xF9, 0x31) +sock.ins.send(bytes(CAN(identifier=nack_can_id, flags="extended", + data=bytes([J1939_ACK_CTRL_NACK, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +found = j1939_scan(sock, methods=["rts_probe"], scan_range=[0x31], sniff_time=0.1, + noise_ids=set(), src_addrs=[0xF9]) +assert 0x31 in found, "Expected SA=0x31 via NACK on ACK PGN through j1939_scan" +assert found[0x31]["methods"] == ["rts_probe"] +assert isinstance(found[0x31]["packets"], list) +assert len(found[0x31]["packets"]) == 1 +cleanup_testsockets() + + ++ Passive Scan + += passive: collects observed SAs from bus traffic +def test_passive_collects_sas(): + sock = TestSocket(CAN) + for sa_val in [0x10, 0x20, 0x30]: + noise_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, sa_val) + sock.ins.send(bytes(CAN(identifier=noise_can_id, flags="extended", + data=b'\x00' * 8))) + noise_ids = j1939_scan_passive(sock, listen_time=0.1) + assert noise_ids == {0x10, 0x20, 0x30}, \ + "Expected {{0x10, 0x20, 0x30}}, got: {}".format(noise_ids) + cleanup_testsockets() + +test_passive_collects_sas() + += passive: ignores non-extended (11-bit) frames +def test_passive_ignores_11bit(): + sock = TestSocket(CAN) + sock.ins.send(bytes(CAN(identifier=0x040, data=b'\x00' * 4))) + noise_ids = j1939_scan_passive(sock, listen_time=0.1) + assert len(noise_ids) == 0, "Should not collect 11-bit frame SA" + cleanup_testsockets() + +test_passive_ignores_11bit() + += passive: returns empty set when no traffic +sock = TestSocket(CAN) +noise_ids = j1939_scan_passive(sock, listen_time=0.05) +assert noise_ids == set(), "Expected empty set, got: {}".format(noise_ids) +cleanup_testsockets() + += passive: multiple different frames give distinct SAs +def test_passive_multiple_frames(): + sock = TestSocket(CAN) + # Three separate SA-DA flows + flows = [(0xA0, 0x01), (0xB0, 0x02), (0xC0, 0x03)] + for sa_val, da_val in flows: + can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, da_val, sa_val) + sock.ins.send(bytes(CAN(identifier=can_id, flags="extended", + data=b'\x00' * 8))) + noise_ids = j1939_scan_passive(sock, listen_time=0.1) + expected = {sa for sa, _ in flows} + assert noise_ids == expected, \ + "Expected {}, got: {}".format({hex(s) for s in expected}, + {hex(s) for s in noise_ids}) + cleanup_testsockets() + +test_passive_multiple_frames() + + ++ Unicast – noise filtering + += unicast: 3 pre-existing SA-DA flows are not reported (main noise test) +def test_unicast_noise_three_flows(): + # Step 1: simulate 3 pre-existing SA-DA traffic flows using passive scan + sock = TestSocket(CAN) + noise_sas = [0x10, 0x20, 0x30] + for sa_val in noise_sas: + noise_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, sa_val) + sock.ins.send(bytes(CAN(identifier=noise_can_id, flags="extended", + data=b'\x00' * 8))) + noise_ids = j1939_scan_passive(sock, listen_time=0.1) + assert noise_ids == set(noise_sas), \ + "Passive scan should collect noise SAs, got: {}".format(noise_ids) + # Step 2: inject response frames for SAME SAs and for new SA=0x40 not in noise, directed to 0xF9 + for sa_val in noise_sas: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, 0xF9, sa_val) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + new_sa = 0x40 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, 0xF9, new_sa) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + # Step 3: unicast sweep with noise filtering + found = j1939_scan_unicast(sock, scan_range=[0x10, 0x20, 0x30, 0x40], + noise_ids=noise_ids, sniff_time=0.1, src_addrs=[0xF9]) + # Pre-existing SAs must NOT be reported + for sa_val in noise_sas: + assert sa_val not in found, \ + "SA=0x{:02X} is noise and must not be reported".format(sa_val) + # New SA must be reported + assert new_sa in found, "SA=0x{:02X} (not noise) should be found".format(new_sa) + cleanup_testsockets() + +test_unicast_noise_three_flows() + += unicast: noise SAs are not probed (no probe frames sent for noise DAs) +def test_unicast_noise_no_probe_sent(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + # noise_ids = {0x01, 0x02}, scan_range = [0x01, 0x02, 0x03] + j1939_scan_unicast(tx_sock, scan_range=[0x01, 0x02, 0x03], + noise_ids={0x01, 0x02}, sniff_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=5, timeout=0.3) + # Only DA=0x03 should have been probed (1 probe frame) + assert len(pkts) == 1, "Expected 1 probe (only DA=0x03), got {}".format(len(pkts)) + f = can_id_to_j1939(pkts[0].identifier); pf, ps = f['pdu_format'], f['pdu_specific'] + assert pf == J1939_PF_REQUEST + assert ps == 0x03, "Probe DA should be 0x03, got 0x{:02X}".format(ps) + cleanup_testsockets() + +test_unicast_noise_no_probe_sent() + += unicast: force=True probes noise SAs despite noise_ids +def test_unicast_force_probes_noise(): + sock = TestSocket(CAN) + # Inject response from SA=0x10 (which is in noise_ids) directed to 0xF9 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, 0xF9, 0x10) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + found = j1939_scan_unicast(sock, scan_range=[0x10], noise_ids={0x10}, + force=True, sniff_time=0.1, src_addrs=[0xF9]) + assert 0x10 in found, "force=True should report SA=0x10 even though it is in noise_ids" + cleanup_testsockets() + +test_unicast_force_probes_noise() + + ++ addr_claim – noise filtering + += addr_claim: noise SAs are filtered from broadcast results +def test_addr_claim_noise_filtering(): + class FilterSocket(TestSocket): + def send(self, pkt): + super(FilterSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST: + for sa_val in [0x10, 0x11]: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, sa_val) + self.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + sock = FilterSocket(CAN) + found = j1939_scan_addr_claim(sock, listen_time=0.1, noise_ids={0x10}) + assert 0x10 not in found, "SA=0x10 is noise and must be suppressed" + assert 0x11 in found, "SA=0x11 (not noise) should be found" + cleanup_testsockets() + +test_addr_claim_noise_filtering() + += addr_claim: force=True reports noise SAs +def test_addr_claim_force(): + class ForceSocket(TestSocket): + def send(self, pkt): + super(ForceSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x15) + self.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + sock = ForceSocket(CAN) + found = j1939_scan_addr_claim(sock, listen_time=0.1, noise_ids={0x15}, force=True) + assert 0x15 in found, "force=True must report SA=0x15 even though it is in noise_ids" + cleanup_testsockets() + +test_addr_claim_force() + + ++ ecu_id – noise filtering + += ecu_id: noise SAs are filtered from broadcast results +def test_ecu_id_noise_filtering(): + sock = TestSocket(CAN) + ecu_pgn_le = bytes(J1939Request(req_pgn=J1939_PGN_ECU_ID)) + # SA=0x20 is noise; SA=0x21 is new + for sa_val in [0x20, 0x21]: + bam_can_id = j1939_to_can_id(6, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, sa_val) + bam_payload = bytes([0x20, 0x0A, 0x00, 0x02, 0xFF]) + ecu_pgn_le + sock.ins.send(bytes(CAN(identifier=bam_can_id, flags="extended", + data=bam_payload))) + found = j1939_scan_ecu_id(sock, src_addrs=[0xF9], listen_time=0.2, noise_ids={0x20}) + assert 0x20 not in found, "SA=0x20 is noise and must be suppressed" + assert 0x21 in found, "SA=0x21 (not noise) should be found" + cleanup_testsockets() + +test_ecu_id_noise_filtering() + += ecu_id: force=True reports noise SAs +def test_ecu_id_force(): + sock = TestSocket(CAN) + ecu_pgn_le = bytes(J1939Request(req_pgn=J1939_PGN_ECU_ID)) + bam_can_id = j1939_to_can_id(6, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x22) + bam_payload = bytes([0x20, 0x0A, 0x00, 0x02, 0xFF]) + ecu_pgn_le + sock.ins.send(bytes(CAN(identifier=bam_can_id, flags="extended", + data=bam_payload))) + found = j1939_scan_ecu_id(sock, listen_time=0.1, noise_ids={0x22}, force=True) + assert 0x22 in found, "force=True must report SA=0x22 even though it is in noise_ids" + cleanup_testsockets() + +test_ecu_id_force() + + ++ rts_probe – noise filtering + += rts_probe: noise SAs are not probed +def test_rts_probe_noise_no_probe(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + # noise_ids = {0x50}, scan_range = [0x50, 0x51] + j1939_scan_rts_probe(tx_sock, scan_range=[0x50, 0x51], + noise_ids={0x50}, sniff_time=0.0, + src_addrs=[0xF9]) + pkts = monitor.sniff(count=5, timeout=0.3) + # Only DA=0x51 should have received an RTS probe + assert len(pkts) == 1, "Expected 1 RTS probe (DA=0x51 only), got {}".format(len(pkts)) + f = can_id_to_j1939(pkts[0].identifier); pf, ps = f['pdu_format'], f['pdu_specific'] + assert pf == J1939_TP_CM_PF + assert ps == 0x51, "RTS probe DA should be 0x51, got 0x{:02X}".format(ps) + cleanup_testsockets() + +test_rts_probe_noise_no_probe() + += rts_probe: force=True probes noise SAs +def test_rts_probe_force(): + sock = TestSocket(CAN) + # CTS from SA=0x60 (which is in noise_ids) directed to 0xF9 + cts_can_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x60) + sock.ins.send(bytes(CAN(identifier=cts_can_id, flags="extended", + data=bytes([J1939_TP_CTRL_CTS, 0x02, 0x01, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) + found = j1939_scan_rts_probe(sock, scan_range=[0x60], noise_ids={0x60}, + force=True, sniff_time=0.1, src_addrs=[0xF9]) + assert 0x60 in found, "force=True should report SA=0x60 even though it is in noise_ids" + cleanup_testsockets() + +test_rts_probe_force() + + ++ j1939_scan – noise_ids integration + += j1939_scan: explicit noise_ids filters results from all methods +def test_j1939_scan_explicit_noise_ids(): + sock = TestSocket(CAN) + # Inject addr_claim response from SA=0x70 (noise) and SA=0x71 (new) + for sa_val in [0x70, 0x71]: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, sa_val) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + # Pass explicit noise_ids (bypasses passive pre-scan) + found = j1939_scan(sock, methods=["addr_claim"], broadcast_listen_time=0.1, + noise_ids={0x70}) + assert 0x70 not in found, "SA=0x70 is in explicit noise_ids and must be suppressed" + assert 0x71 in found, "SA=0x71 (not noise) should be found" + cleanup_testsockets() + +test_j1939_scan_explicit_noise_ids() + += j1939_scan: force=True bypasses noise filtering across all methods +def test_j1939_scan_force(): + sock = TestSocket(CAN) + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x72) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + found = j1939_scan(sock, methods=["addr_claim"], broadcast_listen_time=0.1, + noise_ids={0x72}, force=True) + assert 0x72 in found, "force=True must report SA=0x72 even though it is in noise_ids" + cleanup_testsockets() + +test_j1939_scan_force() + += j1939_scan: auto passive pre-scan (noise_listen_time) suppresses pre-existing SAs +def test_j1939_scan_auto_passive(): + # Inject noise frames first (will be consumed by the passive pre-scan) + sock = TestSocket(CAN) + for sa_val in [0x80, 0x81, 0x82]: + noise_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, sa_val) + sock.ins.send(bytes(CAN(identifier=noise_can_id, flags="extended", + data=b'\x00' * 8))) + # Call j1939_scan with a very short noise_listen_time so the passive pre-scan + # reads the pre-injected noise frames; the subsequent active scan sees an empty bus. + found = j1939_scan(sock, methods=["addr_claim"], broadcast_listen_time=0.05, + noise_listen_time=0.05) + # The noise SAs should not appear in results + for sa_val in [0x80, 0x81, 0x82]: + assert sa_val not in found, \ + "SA=0x{:02X} was noise; auto passive should have suppressed it".format(sa_val) + cleanup_testsockets() + +test_j1939_scan_auto_passive() + + ++ j1939_scan – multi-method accumulation + += j1939_scan: SA detected by two methods accumulates both in methods list +def test_multi_method_accumulation(): + class MultiMethodSocket(TestSocket): + def send(self, pkt): + super(MultiMethodSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST: + if ps == J1939_GLOBAL_ADDRESS: + resp = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x15) + self.ins.send(bytes(CAN(identifier=resp, flags="extended", + data=b'\x00' * 8))) + elif ps == 0x15: + resp = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, sa, 0x15) + self.ins.send(bytes(CAN(identifier=resp, flags="extended", + data=b'\x00' * 8))) + sock = MultiMethodSocket(CAN) + found = j1939_scan(sock, scan_range=[0x15], + methods=["addr_claim", "unicast"], + broadcast_listen_time=0.1, sniff_time=0.1, + noise_ids=set(), src_addrs=[0xF9]) + assert 0x15 in found + assert "addr_claim" in found[0x15]["methods"], \ + "addr_claim should be in methods: {}".format(found[0x15]["methods"]) + assert "unicast" in found[0x15]["methods"], \ + "unicast should be in methods: {}".format(found[0x15]["methods"]) + assert found[0x15]["methods"][0] == "addr_claim", \ + "First detection should be addr_claim" + assert len(found[0x15]["packets"]) == 2 + assert isinstance(found[0x15]["packets"][0], list) + assert isinstance(found[0x15]["packets"][1], list) + # Check src_addrs - [[0xF9]] for addr_claim (broadcast), [[0xF9]] for unicast (physical) + assert found[0x15]["src_addrs"] == [[0xF9], [0xF9]], \ + "Expected [[0xF9], [0xF9]], got: {}".format(found[0x15]["src_addrs"]) + cleanup_testsockets() + +test_multi_method_accumulation() + += j1939_scan: methods list has no duplicates when SA detected once +def test_single_detection_methods_list(): + sock = TestSocket(CAN) + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x16) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + found = j1939_scan(sock, methods=["addr_claim"], + broadcast_listen_time=0.1, noise_ids=set()) + assert 0x16 in found + assert found[0x16]["methods"] == ["addr_claim"], \ + "Single detection should give ['addr_claim'], got: {}".format( + found[0x16]["methods"]) + cleanup_testsockets() + +test_single_detection_methods_list() + += j1939_scan: two different SAs detected by different methods have separate lists +def test_two_sas_different_methods(): + class TwoSAsSocket(TestSocket): + def send(self, pkt): + super(TwoSAsSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST: + if ps == J1939_GLOBAL_ADDRESS: + resp17 = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x17) + self.ins.send(bytes(CAN(identifier=resp17, flags="extended", + data=b'\x00' * 8))) + elif ps == 0x18: + resp18 = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, sa, 0x18) + self.ins.send(bytes(CAN(identifier=resp18, flags="extended", + data=b'\x00' * 8))) + sock = TwoSAsSocket(CAN) + found = j1939_scan(sock, scan_range=[0x18], + methods=["addr_claim", "unicast"], + broadcast_listen_time=0.1, sniff_time=0.1, + noise_ids=set(), src_addrs=[0xF9]) + assert 0x17 in found + assert 0x18 in found + assert found[0x17]["methods"] == ["addr_claim"], \ + "SA=0x17 methods: {}".format(found[0x17]["methods"]) + assert found[0x18]["methods"] == ["unicast"], \ + "SA=0x18 methods: {}".format(found[0x18]["methods"]) + cleanup_testsockets() + +test_two_sas_different_methods() + + ++ j1939_scan – src_addrs and packets + += addr_claim: default src_addrs sends one probe per address in J1939_DIAGADAPTERS_ADDRESSES +def test_addr_claim_multi_src_addrs(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_addr_claim(tx_sock, listen_time=0.0) + pkts = monitor.sniff(count=len(J1939_DIAGADAPTERS_ADDRESSES), timeout=0.5) + assert len(pkts) == len(J1939_DIAGADAPTERS_ADDRESSES), \ + "Expected {} probe frames, got {}".format( + len(J1939_DIAGADAPTERS_ADDRESSES), len(pkts)) + sas = [can_id_to_j1939(p.identifier)["src"] for p in pkts] + assert sorted(sas) == sorted(J1939_DIAGADAPTERS_ADDRESSES), \ + "Probe SAs should be J1939_DIAGADAPTERS_ADDRESSES, got: {}".format( + [hex(s) for s in sas]) + cleanup_testsockets() + +test_addr_claim_multi_src_addrs() + += uds: default src_addrs sends 2*len(J1939_DIAGADAPTERS_ADDRESSES) probes per DA +def test_uds_multi_src_addrs_count(): + # With the new functional then physical scan, if no responses are received: + # 1 broadcast per src_addr (functional) + 1 unicast per src_addr (physical) + # Total = 2 * len(src_addrs) + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + expected = 2 * len(J1939_DIAGADAPTERS_ADDRESSES) + j1939_scan_uds(tx_sock, scan_range=[0x50], sniff_time=0.0, + broadcast_listen_time=0.01, + noise_ids=set()) + pkts = monitor.sniff(count=expected, timeout=0.5) + assert len(pkts) == expected, \ + "Expected {} probes (2 * {} SAs), got {}".format( + expected, len(J1939_DIAGADAPTERS_ADDRESSES), len(pkts)) + probe_sas = {can_id_to_j1939(p.identifier)["src"] for p in pkts} + assert probe_sas == set(J1939_DIAGADAPTERS_ADDRESSES), \ + "Probe SAs must cover all J1939_DIAGADAPTERS_ADDRESSES" + cleanup_testsockets() + +test_uds_multi_src_addrs_count() + += j1939_scan: packets list is parallel to methods list (one entry per method) +def test_packets_list_parallel_to_methods(): + class ParallelSocket(TestSocket): + def send(self, pkt): + super(ParallelSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST: + if ps == J1939_GLOBAL_ADDRESS: + resp = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x19) + self.ins.send(bytes(CAN(identifier=resp, flags="extended", + data=b'\x00' * 8))) + elif ps == 0x19: + resp = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, sa, 0x19) + self.ins.send(bytes(CAN(identifier=resp, flags="extended", + data=b'\x00' * 8))) + sock = ParallelSocket(CAN) + found = j1939_scan(sock, scan_range=[0x19], + methods=["addr_claim", "unicast"], + broadcast_listen_time=0.1, sniff_time=0.1, + noise_ids=set(), src_addrs=[0xF9]) + assert 0x19 in found + methods = found[0x19]["methods"] + packets = found[0x19]["packets"] + assert isinstance(packets, list), "'packets' must be a list" + assert len(packets) == len(methods), \ + "packets and methods must have the same length" + assert methods[0] == "addr_claim" + assert methods[1] == "unicast" + assert isinstance(packets[0], list) + assert isinstance(packets[1], list) + cleanup_testsockets() + +test_packets_list_parallel_to_methods() + + +~ automotive_comm + += J1939_DEFAULT_BITRATE is 250000 and J1939_DEFAULT_BUSLOAD is 0.05 +assert J1939_DEFAULT_BITRATE == 250000 +assert J1939_DEFAULT_BUSLOAD == 0.05 + += j1939_inter_probe_delay: no extra sleep when sniff_time covers the budget +# 250 kbps, 5 % busload, tx=3-byte request (91 bits), rx=8-byte response (131 bits) +# budget_cycle = (91+131) / (250000 * 0.05) = 222 / 12500 = 0.01776 s +# sniff_time=0.1 >> 0.01776 -> delay = 0 +d = j1939_inter_probe_delay(250000, 0.05, 3, 8, 0.1) +assert d == 0.0, "Expected 0, got {}".format(d) + += j1939_inter_probe_delay: positive delay when busload is very low +# 250 kbps, 0.1 % busload, tx=3 bytes, rx=8 bytes, sniff_time=0 +# budget_cycle = 222 / (250000 * 0.001) = 0.888 s +d = j1939_inter_probe_delay(250000, 0.001, 3, 8, 0.0) +expected = (91 + 131) / (250000 * 0.001) +assert abs(d - expected) < 1e-9, "{} != {}".format(d, expected) + += j1939_inter_probe_delay: higher busload yields smaller delay +d_low = j1939_inter_probe_delay(250000, 0.05, 8, 8, 0.0) +d_high = j1939_inter_probe_delay(250000, 0.50, 8, 8, 0.0) +assert d_low > d_high, "Lower busload must give longer delay" + += j1939_inter_probe_delay: raises ValueError for busload <= 0 +def test_pacing_invalid_busload(): + try: + j1939_inter_probe_delay(250000, 0.0, 3, 8, 0.1) + assert False, "Expected ValueError" + except ValueError as e: + assert "busload" in str(e).lower(), str(e) + +test_pacing_invalid_busload() + += j1939_inter_probe_delay: raises ValueError for negative busload +def test_pacing_negative_busload(): + try: + j1939_inter_probe_delay(250000, -0.1, 3, 8, 0.1) + assert False, "Expected ValueError" + except ValueError as e: + assert "busload" in str(e).lower(), str(e) + +test_pacing_negative_busload() + += j1939_inter_probe_delay: busload=1.0 accepted and yields minimal delay +d = j1939_inter_probe_delay(250000, 1.0, 3, 8, 0.0) +expected = (91 + 131) / (250000 * 1.0) +assert abs(d - expected) < 1e-9 + += unicast: bitrate and busload params accepted without error +sock = TestSocket(CAN) +found = j1939_scan_unicast(sock, scan_range=[], bitrate=250000, busload=0.05, + sniff_time=0.02) +assert found == {} +cleanup_testsockets() + += rts_probe: bitrate and busload params accepted without error +sock = TestSocket(CAN) +found = j1939_scan_rts_probe(sock, scan_range=[], bitrate=250000, busload=0.05, + sniff_time=0.02) +assert found == {} +cleanup_testsockets() + += j1939_scan: bitrate and busload params accepted without error +def test_j1939_scan_pacing_params(): + sock = TestSocket(CAN) + found = j1939_scan(sock, methods=["unicast"], scan_range=[], + bitrate=250000, busload=0.05, noise_ids=set(), + sniff_time=0.02) + assert found == {} + cleanup_testsockets() + +test_j1939_scan_pacing_params() + + ++ Technique 5 – UDS TesterPresent Probe + += J1939_PGN_DIAG_A is 0xDA00, J1939_PF_DIAG_A is 0xDA; J1939_PGN_DIAG_B is 0xDB00, J1939_PF_DIAG_B is 0xDB +assert J1939_PGN_DIAG_A == 0xDA00 +assert J1939_PF_DIAG_A == 0xDA +assert J1939_PGN_DIAG_B == 0xDB00 +assert J1939_PF_DIAG_B == 0xDB + += uds: sends Functional (broadcast PF|0x01) and Physical (unicast PF) probe frames +def test_uds_probe_frames(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + # scan_range=[0x20] with 1 src_addr should send 4 probes total + # Functional: 3E00 and 3E01 to 0xFF (PF=0xDB) + # Physical: 3E00 and 3E01 to 0x20 (PF=0xDA) + j1939_scan_uds(tx_sock, scan_range=[0x20], sniff_time=0.0, + noise_ids=set(), src_addrs=[0xF9]) + pkts = monitor.sniff(count=4, timeout=0.2) + assert len(pkts) == 4, "Expected 4 probe frames, got {}".format(len(pkts)) + + # Check payloads + payloads = [bytes(p.data) for p in pkts] + assert b"\x02\x3e\x00\xff\xff\xff\xff\xff" in payloads + assert b"\x02\x3e\x01\xff\xff\xff\xff\xff" in payloads + + # Check targets + can_ids = [p.identifier for p in pkts] + # Two functional (PF=0xDB, PS=0xFF) + func_can_ids = [cid for cid in can_ids if ((cid >> 8) & 0xFFFF) == (0xDB00 | J1939_GLOBAL_ADDRESS)] + assert len(func_can_ids) == 2 + # Two physical (PF=0xDA, PS=0x20) + phys_can_ids = [cid for cid in can_ids if ((cid >> 8) & 0xFFFF) == (0xDA00 | 0x20)] + assert len(phys_can_ids) == 2 + + cleanup_testsockets() + +test_uds_probe_frames() + += uds: records SA when UDS positive response (02 7E 00) is received (Physical) +def test_uds_positive_response(): + sock = TestSocket(CAN) + # Inject a fake UDS TesterPresent positive response from SA=0x30 + # directed to scanner src_addr=0xF9 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, 0xF9, 0x30) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00' + b'\xff' * 5))) + found = j1939_scan_uds(sock, scan_range=[0x30], sniff_time=0.1, + noise_ids=set(), skip_functional=True, + src_addrs=[0xF9]) + assert 0x30 in found, "Expected SA=0x30, got: {}".format( + [hex(k) for k in found]) + assert isinstance(found[0x30], list) + assert len(found[0x30]) == 1 + cleanup_testsockets() + +test_uds_positive_response() + + += uds: records SA when UDS positive response (02 7E 01) is received (Physical) +def test_uds_positive_response_3e01(): + sock = TestSocket(CAN) + # Inject a fake UDS TesterPresent positive response (3E 01) from SA=0x31 + # directed to scanner src_addr=0xF9 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, 0xF9, 0x31) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x01' + b'\xff' * 5))) + found = j1939_scan_uds(sock, scan_range=[0x31], sniff_time=0.1, + noise_ids=set(), skip_functional=True, + src_addrs=[0xF9]) + assert 0x31 in found, "Expected SA=0x31, got: {}".format( + [hex(k) for k in found]) + assert len(found[0x31]) == 1 + cleanup_testsockets() + +test_uds_positive_response_3e01() + + += uds: records SA when UDS negative response (03 7F 3E) is received (Physical) +def test_uds_negative_response(): + sock = TestSocket(CAN) + # Inject a fake UDS TesterPresent negative response (NRC 0x12) from SA=0x32 + # directed to scanner src_addr=0xF9 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, 0xF9, 0x32) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x03\x7f\x3e\x12' + b'\xff' * 4))) + found = j1939_scan_uds(sock, scan_range=[0x32], sniff_time=0.1, + noise_ids=set(), skip_functional=True, + src_addrs=[0xF9]) + assert 0x32 in found, "Expected SA=0x32 (Negative Response), got: {}".format( + [hex(k) for k in found]) + assert len(found[0x32]) == 1 + cleanup_testsockets() + # + sock2 = TestSocket(CAN) + sock2.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x03\x7f\x3e\x99' + b'\xff' * 4))) + found2 = j1939_scan_uds(sock2, scan_range=[0x32], sniff_time=0.1, + noise_ids=set(), skip_functional=True, + src_addrs=[0xF9]) + assert 0x32 in found2, "Any NRC (e.g. 0x99) should confirm response to probe" + cleanup_testsockets() + +test_uds_negative_response() + += uds: records SA when UDS positive response is from Functional PGN (0xDB00) +def test_uds_positive_response_pgn_db(): + sock = TestSocket(CAN) + # Response from SA=0x3A to Functional probe back to scanner SA J1939_DIAGADAPTERS_ADDRESSES[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_B, J1939_DIAGADAPTERS_ADDRESSES[0], 0x3A) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + found = j1939_scan_uds(sock, scan_range=[0x3A], sniff_time=0.1, + broadcast_listen_time=0.02, + src_addrs=[J1939_DIAGADAPTERS_ADDRESSES[0]], + noise_ids=set()) + assert 0x3A in found, \ + "Expected SA=0x3A (Functional response), got: {}".format( + [hex(k) for k in found]) + assert isinstance(found[0x3A], list) + assert len(found[0x3A]) == 1 + cleanup_testsockets() + +test_uds_positive_response_pgn_db() + += uds: both functional and physical responses are captured +def test_uds_both_functional_and_physical(): + class DualUdsSocket(TestSocket): + def __init__(self, *args, **kwargs): + super(DualUdsSocket, self).__init__(*args, **kwargs) + self.replied_f = False + def send(self, pkt): + super(DualUdsSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_DIAG_B and not self.replied_f: + self.replied_f = True + resp_f = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_B, sa, 0x55) + self.ins.send(bytes(CAN(identifier=resp_f, flags="extended", + data=b'\x02\x7e\x00'))) + elif pf == J1939_PF_DIAG_A and ps == 0x55: + resp_p = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, sa, 0x55) + self.ins.send(bytes(CAN(identifier=resp_p, flags="extended", + data=b'\x02\x7e\x00'))) + sock = DualUdsSocket(CAN) + found = j1939_scan_uds(sock, scan_range=[0x55], sniff_time=0.1, + broadcast_listen_time=0.1, + noise_ids=set(), src_addrs=[0xF9]) + assert 0x55 in found + # Should have captured both responses + assert len(found[0x55]) == 2 + # Check PFs + pfs = {can_id_to_j1939(p.packet.to_can_id())["pdu_format"] for p in found[0x55]} + assert pfs == {J1939_PF_DIAG_A, J1939_PF_DIAG_B} + cleanup_testsockets() + +test_uds_both_functional_and_physical() + += uds: skip_functional=True avoids broadcast probes +def test_uds_skip_functional(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_uds(tx_sock, scan_range=[0x20], sniff_time=0.0, + skip_functional=True, + noise_ids=set(), src_addrs=[0xF9]) + pkts = monitor.sniff(count=10, timeout=0.2) + # Should only see 2 probe frames (the physical unicast ones for 3E00 and 3E01) + assert len(pkts) == 2, "Expected 2 probes (physical), got {}".format(len(pkts)) + for p in pkts: + f = can_id_to_j1939(p.identifier); pf, ps = f['pdu_format'], f['pdu_specific'] + assert pf == J1939_PF_DIAG_A + cleanup_testsockets() + +test_uds_skip_functional() + += uds: custom diag_pgn uses expected PF and PF|0x01 +def test_uds_custom_diag_pgn(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + custom_pgn = 0xD0 + j1939_scan_uds(tx_sock, scan_range=[0x20], sniff_time=0.0, + diag_pgn=custom_pgn, + noise_ids=set(), src_addrs=[0xF9]) + pkts = monitor.sniff(count=4, timeout=0.2) + assert len(pkts) == 4 + + # Functional probes + func_pfs = [can_id_to_j1939(p.identifier)["pdu_format"] for p in pkts[:2]] + assert all(pf == custom_pgn | 0x01 for pf in func_pfs) + # Physical probes + phys_pfs = [can_id_to_j1939(p.identifier)["pdu_format"] for p in pkts[2:]] + assert all(pf == custom_pgn for pf in phys_pfs) + cleanup_testsockets() + +test_uds_custom_diag_pgn() + += uds: ignores frames with wrong UDS response SID +def test_uds_wrong_response_ignored(): + sock = TestSocket(CAN) + # Inject a frame from SA=0x31 with incorrect UDS response bytes + # back to scanner SA J1939_DIAGADAPTERS_ADDRESSES[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, J1939_DIAGADAPTERS_ADDRESSES[0], 0x31) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x3e\x00'))) # request, not response + found = j1939_scan_uds(sock, scan_range=[0x31], sniff_time=0.1, + broadcast_listen_time=0.02, + src_addrs=[J1939_DIAGADAPTERS_ADDRESSES[0]], + noise_ids=set()) + assert 0x31 not in found, \ + "SA=0x31 returned wrong payload and must NOT be recorded" + cleanup_testsockets() + +test_uds_wrong_response_ignored() + += uds: noise_ids suppresses probing +def test_uds_noise_suppression(): + sock = TestSocket(CAN) + # back to scanner SA J1939_DIAGADAPTERS_ADDRESSES[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, J1939_DIAGADAPTERS_ADDRESSES[0], 0x32) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + # SA=0x32 in noise_ids and force=False -> must be skipped + found = j1939_scan_uds(sock, scan_range=[0x32], sniff_time=0.1, + noise_ids={0x32}, force=False, skip_functional=True) + assert 0x32 not in found, \ + "SA=0x32 is in noise_ids and must be suppressed" + cleanup_testsockets() + +test_uds_noise_suppression() + += uds: force=True bypasses noise_ids +def test_uds_force(): + sock = TestSocket(CAN) + # back to scanner SA J1939_DIAGADAPTERS_ADDRESSES[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, J1939_DIAGADAPTERS_ADDRESSES[0], 0x33) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + found = j1939_scan_uds(sock, scan_range=[0x33], sniff_time=0.1, + noise_ids={0x33}, force=True, skip_functional=True) + assert 0x33 in found, "force=True must probe SA=0x33 despite noise_ids" + cleanup_testsockets() + +test_uds_force() + += uds: multiple SAs with positive responses are all captured +def test_uds_multiple_responses(): + _SCAN_DAS = [0x34, 0x35, 0x36] + class MultiUdsSocket(TestSocket): + def send(self, pkt): + super(MultiUdsSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_DIAG_A and ps in _SCAN_DAS: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, sa, ps) + self.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + sock = MultiUdsSocket(CAN) + found = j1939_scan_uds(sock, scan_range=_SCAN_DAS, + sniff_time=0.1, noise_ids=set(), + src_addrs=[0xF9], + skip_functional=True) + for sa_val in _SCAN_DAS: + assert sa_val in found, \ + "Expected SA=0x{:02X} in results, got {}".format( + sa_val, [hex(k) for k in found]) + cleanup_testsockets() + +test_uds_multiple_responses() + += uds: stop_event aborts scan early +def test_uds_stop_event(): + from threading import Event + sock = TestSocket(CAN) + stop = Event() + stop.set() + found = j1939_scan_uds(sock, scan_range=range(0x00, 0xFF), + sniff_time=0.0, stop_event=stop, skip_functional=True) + assert found == {}, "stop_event set: no probes should be sent" + cleanup_testsockets() + +test_uds_stop_event() + += j1939_scan: uds technique is invoked and finds UDS-responding CAs +def test_j1939_scan_uds_technique(): + sock = TestSocket(CAN) + # back to scanner SA J1939_DIAGADAPTERS_ADDRESSES[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, J1939_DIAGADAPTERS_ADDRESSES[0], 0x40) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + found = j1939_scan(sock, methods=["uds"], scan_range=[0x40], + sniff_time=0.1, noise_ids=set(), skip_functional=True) + assert 0x40 in found, \ + "SA=0x40 should be found by uds method, got: {}".format( + [hex(k) for k in found]) + assert found[0x40]["methods"] == ["uds"], \ + "methods should be ['uds'], got: {}".format(found[0x40]["methods"]) + assert isinstance(found[0x40]["packets"], list) + assert len(found[0x40]["packets"]) == 1 + assert isinstance(found[0x40]["packets"][0], list) + cleanup_testsockets() + +test_j1939_scan_uds_technique() + += j1939_scan_uds: 7F 3E negative response confirms UDS support +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_scan_uds +from scapy.contrib.automotive.uds import UDS, UDS_NR +from scapy.contrib.j1939 import j1939_to_can_id +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets + +# Physical probe response: 7F 3E 22 (conditionsNotCorrect) confirms endpoint supports UDS +sock_phys = TestSocket(CAN) +resp_can_id_phys = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, 0xF1, 0x40) +sock_phys.ins.send(bytes(CAN(identifier=resp_can_id_phys, flags="extended", + data=b"\x03\x7f\x3e\x22\xff\xff\xff\xff"))) +found_phys = j1939_scan_uds(sock_phys, scan_range=[0x40], src_addrs=[0xF1], + sniff_time=0.1, skip_functional=True) +assert 0x40 in found_phys +cleanup_testsockets() + +# Functional broadcast probe response: 7F 3E 12 (subFunctionNotSupported) confirms endpoint supports UDS +sock_func = TestSocket(CAN) +resp_can_id_func = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_B, 0xF1, 0x50) +sock_func.ins.send(bytes(CAN(identifier=resp_can_id_func, flags="extended", + data=b"\x7f\x3e\x12\x00\x00\x00\x00\x00"))) +found_func = j1939_scan_uds(sock_func, scan_range=[0x50], src_addrs=[0xF1], + broadcast_listen_time=0.1, sniff_time=0.01) +assert 0x50 in found_func +cleanup_testsockets() + +True + += j1939_scan: SA found by addr_claim and uds accumulates both methods and packets +def test_j1939_scan_addr_claim_and_uds(): + class DualMethodSocket(TestSocket): + def send(self, pkt): + super(DualMethodSocket, self).send(pkt) + can_id = getattr(pkt, "identifier", None) + if can_id is not None: + f = can_id_to_j1939(can_id); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST: + resp = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x41) + self.ins.send(bytes(CAN(identifier=resp, flags="extended", + data=b'\x00' * 8))) + elif pf == J1939_PF_DIAG_A and ps == 0x41: + resp = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, sa, 0x41) + self.ins.send(bytes(CAN(identifier=resp, flags="extended", + data=b'\x02\x7e\x00'))) + sock = DualMethodSocket(CAN) + found = j1939_scan(sock, methods=["addr_claim", "uds"], + scan_range=[0x41], + broadcast_listen_time=0.1, sniff_time=0.1, + noise_ids=set(), src_addrs=[0xF9], + skip_functional=True) + assert 0x41 in found + assert "addr_claim" in found[0x41]["methods"] + assert "uds" in found[0x41]["methods"] + assert found[0x41]["methods"][0] == "addr_claim" + assert len(found[0x41]["packets"]) == 2, \ + "Two methods found SA=0x41; packets list must have 2 entries" + assert isinstance(found[0x41]["packets"][0], list) + assert isinstance(found[0x41]["packets"][1], list) + # Check src_addrs - [[0xF9]] for addr_claim (broadcast), [[0xF9]] for unicast (physical) + assert found[0x41]["src_addrs"] == [[0xF9], [0xF9]], \ + "Expected [[0xF9], [0xF9]], got: {}".format(found[0x41]["src_addrs"]) + cleanup_testsockets() + +test_j1939_scan_addr_claim_and_uds() + += uds: captures all responding scanner source addresses in range +def test_uds_captures_all_responding_src_addrs(): + sock = TestSocket(CAN) + _TARGET_DA = 0x45 + _SRC_ADDRS = list(range(0xF1, 0xFB)) + for sa in _SRC_ADDRS: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, sa, _TARGET_DA) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + found = j1939_scan_uds(sock, scan_range=[_TARGET_DA], + src_addrs=range(0xF1, 0xFB), + sniff_time=0.2, noise_ids=set(), + skip_functional=True) + assert _TARGET_DA in found + captured_sas = sorted({ + p.scanner_src for p in found[_TARGET_DA] + }) + assert captured_sas == _SRC_ADDRS, \ + "Expected all SAs 0xF1..0xFA, got: {}".format([hex(x) for x in captured_sas]) + # Also verify that p.packet holds the raw J1939 frame + decoded_sas = sorted({ + can_id_to_j1939(p.packet.to_can_id())["pdu_specific"] for p in found[_TARGET_DA] + }) + assert decoded_sas == _SRC_ADDRS + cleanup_testsockets() + +test_uds_captures_all_responding_src_addrs() + += j1939_scan: uds method discovers full range of responding scanner source addresses +def test_j1939_scan_uds_range_src_addrs(): + sock = TestSocket(CAN) + _TARGET_DA = 0x46 + _SRC_ADDRS = list(range(0xF1, 0xFB)) + for sa in _SRC_ADDRS: + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, sa, _TARGET_DA) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + found = j1939_scan(sock, methods=["uds"], scan_range=[_TARGET_DA], + src_addrs=range(0xF1, 0xFB), + sniff_time=0.2, noise_ids=set(), skip_functional=True) + assert _TARGET_DA in found, "Target DA should be found" + assert "uds" in found[_TARGET_DA]["methods"] + discovered_src_addrs = found[_TARGET_DA]["src_addrs"][0] + assert sorted(discovered_src_addrs) == _SRC_ADDRS, \ + "Expected all SAs 0xF1..0xFA in src_addrs, got: {}".format( + [hex(x) for x in discovered_src_addrs]) + cleanup_testsockets() + +test_j1939_scan_uds_range_src_addrs() + += j1939_scan: bitrate is read from socket.bitrate attribute when available +def test_j1939_scan_bitrate_from_socket(): + sock = TestSocket(CAN) + # Attach a bitrate attribute to the socket to simulate a CANSocket + sock.bitrate = 500000 + found = j1939_scan(sock, methods=["unicast"], scan_range=[], + noise_ids=set(), sniff_time=0.02) + assert found == {} + cleanup_testsockets() + +test_j1939_scan_bitrate_from_socket() + += uds: bitrate and busload params accepted without error +sock = TestSocket(CAN) +found = j1939_scan_uds(sock, scan_range=[], bitrate=250000, busload=0.05, + broadcast_listen_time=0.01, sniff_time=0.02) +assert found == {} +cleanup_testsockets() + ++ XCP scanner tests + += xcp: J1939_XCP_CONNECT_REQ has correct format (command byte 0xFF, mode 0x00, padded) +assert J1939_XCP_CONNECT_REQ == b'\xff\x00\xff\xff\xff\xff\xff\xff' +assert len(J1939_XCP_CONNECT_REQ) == 8 +assert J1939_XCP_CONNECT_REQ[0] == 0xFF +assert J1939_XCP_CONNECT_REQ[1] == 0x00 +assert J1939_XCP_POSITIVE_RESPONSE == 0xFF + += xcp: probe frame sent with correct PF and DA +def test_xcp_probe_frames(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + j1939_scan_xcp(tx_sock, scan_range=[0x20], sniff_time=0.0, + noise_ids=set(), src_addrs=[0xF9]) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1, \ + "Expected 1 XCP probe frame, got {}".format(len(pkts)) + f = can_id_to_j1939(pkts[0].identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + assert pf == J1939_PF_XCP, \ + "XCP probe should use Physical PF=0xEF, got 0x{:02X}".format(pf) + assert ps == 0x20, \ + "DA should be 0x20, got 0x{:02X}".format(ps) + assert bytes(pkts[0].data) == J1939_XCP_CONNECT_REQ, \ + "XCP probe payload mismatch" + cleanup_testsockets() + +test_xcp_probe_frames() + += xcp: records SA when XCP positive response (byte 0 == 0xFF) is received +def test_xcp_positive_response(): + sock = TestSocket(CAN) + # ECU at SA=0x35 responds back to scanner SA J1939_XCP_SRC_ADDRS[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, J1939_XCP_SRC_ADDRS[0], 0x35) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xff\x00\x00\x00\x00\x00\x00\x00'))) + found = j1939_scan_xcp(sock, scan_range=[0x35], sniff_time=0.1, + noise_ids=set()) + assert 0x35 in found, \ + "Expected SA=0x35 via XCP, got: {}".format([hex(k) for k in found]) + assert isinstance(found[0x35], list) + assert len(found[0x35]) == 1 + cleanup_testsockets() + +test_xcp_positive_response() + += xcp: ignores frames where byte 0 is not 0xFF (not a positive response) +def test_xcp_wrong_response_ignored(): + sock = TestSocket(CAN) + # 0xFE = XCP negative response (ERR_*) back to scanner SA J1939_XCP_SRC_ADDRS[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, J1939_XCP_SRC_ADDRS[0], 0x36) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xfe\x10\x00\x00\x00\x00\x00\x00'))) + found = j1939_scan_xcp(sock, scan_range=[0x36], sniff_time=0.1, + noise_ids=set()) + assert 0x36 not in found, \ + "SA=0x36 returned XCP negative response and must NOT be recorded" + cleanup_testsockets() + +test_xcp_wrong_response_ignored() + += xcp: ignores echoes of CONNECT probes +sock = TestSocket(CAN) +# Simulated echo: CONNECT from 0xF1 to 0xF1 (PF=0xEF, PS=0xF1, SA=0xF1) +# This frame has sa == _da if we are probing 0xF1, and ps in src_addrs, +# and data[0] == 0xFF. It must be ignored. +echo_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, 0xF1, 0xF1) +sock.ins.send(bytes(CAN(identifier=echo_can_id, flags="extended", + data=J1939_XCP_CONNECT_REQ))) +found = j1939_scan_xcp(sock, scan_range=[0xF1], sniff_time=0.1, src_addrs=[0xF1]) +assert 0xF1 not in found, "Scanner must ignore echoes of its own XCP CONNECT probes" +cleanup_testsockets() + += xcp: noise_ids suppresses probing +def test_xcp_noise_suppression(): + sock = TestSocket(CAN) + # Response back to scanner SA J1939_XCP_SRC_ADDRS[0] + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, J1939_XCP_SRC_ADDRS[0], 0x37) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xff\x00\x00\x00\x00\x00\x00\x00'))) + found = j1939_scan_xcp(sock, scan_range=[0x37], sniff_time=0.1, + noise_ids={0x37}) + assert 0x37 not in found, \ + "SA=0x37 is in noise_ids and must be suppressed" + cleanup_testsockets() + +test_xcp_noise_suppression() + += xcp: custom diag_pgn uses that PF for probes +def test_xcp_custom_diag_pgn(): + with TestSocket(CAN) as tx_sock, TestSocket(CAN) as monitor: + tx_sock.pair(monitor) + custom_pgn = 0xEF + j1939_scan_xcp(tx_sock, scan_range=[0x20], sniff_time=0.0, + diag_pgn=custom_pgn, + noise_ids=set(), src_addrs=[0xF9]) + pkts = monitor.sniff(count=1, timeout=0.2) + assert len(pkts) == 1 + f = can_id_to_j1939(pkts[0].identifier); pf = f['pdu_format'] + assert pf == custom_pgn, \ + "Expected PF=0x{:02X}, got 0x{:02X}".format(custom_pgn, pf) + cleanup_testsockets() + +test_xcp_custom_diag_pgn() + += j1939_scan: xcp technique is invoked and finds XCP-responding CAs +def test_j1939_scan_xcp_technique(): + sock = TestSocket(CAN) + # Response simulates ECU 0x42 answering back to scanner SA 0xF9 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, 0xF9, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xff\x00\x00\x00\x00\x00\x00\x00'))) + found = j1939_scan(sock, methods=["xcp"], scan_range=[0x42], + sniff_time=0.1, noise_ids=set(), + src_addrs=[0xF9]) + assert 0x42 in found, \ + "SA=0x42 should be found by xcp method, got: {}".format( + [hex(k) for k in found]) + assert found[0x42]["methods"] == ["xcp"], \ + "methods should be ['xcp'], got: {}".format(found[0x42]["methods"]) + assert isinstance(found[0x42]["packets"], list) + assert len(found[0x42]["packets"]) == 1 + assert isinstance(found[0x42]["packets"][0], list) + assert "src_addrs" in found[0x42], "'src_addrs' key missing from result" + cleanup_testsockets() + +test_j1939_scan_xcp_technique() + += j1939_scan: src_addrs key present in results for all techniques +def test_j1939_scan_src_addrs_key_present(): + sock = TestSocket(CAN) + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x43) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x00' * 8))) + found = j1939_scan(sock, methods=["addr_claim"], + broadcast_listen_time=0.1, noise_ids=set()) + assert 0x43 in found + assert "src_addrs" in found[0x43], "'src_addrs' key missing from result" + assert len(found[0x43]["src_addrs"]) == len(found[0x43]["methods"]) + cleanup_testsockets() + +test_j1939_scan_src_addrs_key_present() + += J1939ScanResult instantiation and fields +p = J1939(src=0x10, dst=0x20) +res = J1939ScanResult(packet=p, scanner_src=0xF9) +assert res.packet == p +assert res.scanner_src == 0xF9 +res_default = J1939ScanResult(packet=p) +assert res_default.packet == p +assert res_default.scanner_src is None + += j1939_scan: results key present and contains J1939ScanResult objects +sock = TestSocket(CAN) +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x47) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", data=b'\x00' * 8))) +found = j1939_scan(sock, methods=["addr_claim"], src_addrs=[0xF9], + broadcast_listen_time=0.1, noise_ids=set()) +assert 0x47 in found +assert "results" in found[0x47] +assert isinstance(found[0x47]["results"], list) +assert len(found[0x47]["results"]) == 1 +assert isinstance(found[0x47]["results"][0][0], J1939ScanResult) +res_obj = found[0x47]["results"][0][0] +assert res_obj.packet.src == 0x47 +assert res_obj.scanner_src == 0xF9 +assert not hasattr(res_obj.packet, "src_addrs") +cleanup_testsockets() + += j1939_scan_addr_claim: returns J1939ScanResult without mutating packet +sock = TestSocket(CAN) +resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x48) +sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", data=b'\x00' * 8))) +found = j1939_scan_addr_claim(sock, src_addrs=[0xF9], listen_time=0.1, noise_ids=set()) +assert 0x48 in found +assert isinstance(found[0x48][0], J1939ScanResult) +assert found[0x48][0].scanner_src == 0xF9 +assert not hasattr(found[0x48][0].packet, "src_addrs") +cleanup_testsockets() + += j1939_scan: uds result carries scanner src_addr that produced the response +def test_j1939_scan_uds_src_addr_recorded(): + sock = TestSocket(CAN) + # UDS response from ECU 0x44 back to scanner src_addr=0xF1 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, 0xF1, 0x44) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00'))) + found = j1939_scan(sock, methods=["uds"], scan_range=[0x44], + sniff_time=0.1, noise_ids=set(), skip_functional=True, + src_addrs=[0xF1]) + assert 0x44 in found + uds_idx = found[0x44]["methods"].index("uds") + assert found[0x44]["src_addrs"][uds_idx] == [0xF1], \ + "Expected src_addr=[0xF1], got: 0x{:02X}".format( + found[0x44]["src_addrs"][uds_idx]) + cleanup_testsockets() + +test_j1939_scan_uds_src_addr_recorded() + += j1939_scan: xcp result carries scanner src_addr that produced the response +def test_j1939_scan_xcp_src_addr_recorded(): + sock = TestSocket(CAN) + # XCP response from ECU 0x45 back to scanner src_addr=0xB5 + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, 0xB5, 0x45) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\xff\x00\x00\x00\x00\x00\x00\x00'))) + found = j1939_scan(sock, methods=["xcp"], scan_range=[0x45], + sniff_time=0.1, noise_ids=set(), + src_addrs=[0xB5]) + assert 0x45 in found + xcp_idx = found[0x45]["methods"].index("xcp") + assert found[0x45]["src_addrs"][xcp_idx] == [0xB5], \ + "Expected src_addr=[0xB5], got: {}".format( + found[0x45]["src_addrs"][xcp_idx]) + cleanup_testsockets() + +test_j1939_scan_xcp_src_addr_recorded() + += j1939_scan: xcp result carries successful scanner src_addr +def test_j1939_scan_xcp_multi_src_addr_recorded(): + sock = TestSocket(CAN) + # ECU at SA=0x45 responds back to scanner SA 0xB5 + resp1 = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, 0xB5, 0x45) + sock.ins.send(bytes(CAN(identifier=resp1, flags="extended", + data=b'\xff\x00\x00\x00\x00\x00\x00\x00'))) + # ECU at SA=0x45 also responds back to scanner SA 0x3F + resp2 = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, 0x3F, 0x45) + sock.ins.send(bytes(CAN(identifier=resp2, flags="extended", + data=b'\xff\x00\x00\x00\x00\x00\x00\x00'))) + found = j1939_scan(sock, methods=["xcp"], scan_range=[0x45], + sniff_time=0.1, noise_ids=set(), + src_addrs=[0xB5, 0x3F]) + assert 0x45 in found + xcp_idx = found[0x45]["methods"].index("xcp") + src_addrs_result = found[0x45]["src_addrs"][xcp_idx] + assert isinstance(src_addrs_result, list), "src_addrs entry should be a list" + # stop_filter exits after the first response so at least one SA is captured + assert len(src_addrs_result) >= 1, "Expected at least 1 src_addr, got {}".format(src_addrs_result) + assert src_addrs_result[0] in (0xB5, 0x3F), "Expected 0xB5 or 0x3F, got 0x{:02X}".format(src_addrs_result[0]) + cleanup_testsockets() + +test_j1939_scan_xcp_multi_src_addr_recorded() + += j1939_scan: mock ECU responds UDS from SA 0xF1 and XCP from SA 0xB5 on PGN 0xEF/DA 0x33 +def test_j1939_scan_uds_and_xcp_src_addr_discrimination(): + import threading + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + _CUSTOM_PGN = 0xEF + _TARGET_DA = 0x33 + _UDS_SRC = 0xF1 + _XCP_SRC = 0xB5 + stop_mock = threading.Event() + def simulate_ecu(): + while not stop_mock.is_set(): + pkts = monitor.sniff(count=1, timeout=0.1) + if not pkts: + continue + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == _CUSTOM_PGN and ps == _TARGET_DA: + if sa == _UDS_SRC and bytes(p.data) in J1939_UDS_TESTER_PRESENT_REQS: + uds_resp_id = j1939_to_can_id(6, 0, 0, _CUSTOM_PGN, _UDS_SRC, _TARGET_DA) + sock.ins.send(bytes(CAN(identifier=uds_resp_id, flags="extended", data=b'\x02\x7e\x00'))) + elif sa == _XCP_SRC and bytes(p.data) == J1939_XCP_CONNECT_REQ: + xcp_resp_id = j1939_to_can_id(6, 0, 0, _CUSTOM_PGN, _XCP_SRC, _TARGET_DA) + sock.ins.send(bytes(CAN(identifier=xcp_resp_id, flags="extended", data=b'\xff\x00\x00\x00\x00\x00\x00\x00'))) + t = threading.Thread(target=simulate_ecu) + t.start() + found = j1939_scan( + sock, + methods=["uds", "xcp"], + scan_range=[_TARGET_DA], + src_addrs=[_UDS_SRC, _XCP_SRC], + sniff_time=0.1, + noise_ids=set(), + skip_functional=True, + diag_pgn=_CUSTOM_PGN, + ) + stop_mock.set() + t.join(timeout=2.0) + assert _TARGET_DA in found, \ + "ECU at DA=0x{:02X} not found, got: {}".format( + _TARGET_DA, [hex(k) for k in found]) + assert "uds" in found[_TARGET_DA]["methods"], \ + "UDS method missing from result" + assert "xcp" in found[_TARGET_DA]["methods"], \ + "XCP method missing from result" + uds_idx = found[_TARGET_DA]["methods"].index("uds") + xcp_idx = found[_TARGET_DA]["methods"].index("xcp") + assert found[_TARGET_DA]["src_addrs"][uds_idx] == [_UDS_SRC], \ + "UDS: expected scanner SA=[0x{:02X}], got: {}".format( + _UDS_SRC, found[_TARGET_DA]["src_addrs"][uds_idx]) + assert found[_TARGET_DA]["src_addrs"][xcp_idx] == [_XCP_SRC], \ + "XCP: expected scanner SA=[0x{:02X}], got: {}".format( + _XCP_SRC, found[_TARGET_DA]["src_addrs"][xcp_idx]) + cleanup_testsockets() + +test_j1939_scan_uds_and_xcp_src_addr_discrimination() + += xcp: bitrate and busload params accepted without error +sock = TestSocket(CAN) +found = j1939_scan_xcp(sock, scan_range=[], bitrate=250000, busload=0.05, + sniff_time=0.02) +assert found == {} +cleanup_testsockets() + + ++ Send-then-sniff race condition regression tests +~ conf + += unicast: immediate ECU reply is captured (sniff-before-send regression) +def test_unicast_immediate_reply(): + import threading + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + def simulate_ecu(): + while True: + pkts = monitor.sniff(count=1, timeout=1.0) + if not pkts: + break + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_REQUEST: + resp_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, ps) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + t = threading.Thread(target=simulate_ecu) + t.start() + found = j1939_scan_unicast(sock, scan_range=[0x42], sniff_time=0.3, src_addrs=[0xF9]) + t.join(timeout=2.0) + assert 0x42 in found, "Immediate ECU reply must be captured, got: {}".format([hex(k) for k in found]) + cleanup_testsockets() + +test_unicast_immediate_reply() + += rts_probe: immediate ECU reply is captured (sniff-before-send regression) +def test_rts_probe_immediate_reply(): + import threading + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + def simulate_ecu(): + while True: + pkts = monitor.sniff(count=1, timeout=1.0) + if not pkts: + break + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_TP_CM_PF: + cts_data = bytes([J1939_TP_CTRL_CTS, 0x01, 0x01, 0xFF, 0xFF, 0xFF, 0x00, 0x00]) + resp_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, sa, ps) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=cts_data))) + t = threading.Thread(target=simulate_ecu) + t.start() + found = j1939_scan_rts_probe(sock, scan_range=[0x42], sniff_time=0.3, src_addrs=[0xF9]) + t.join(timeout=2.0) + assert 0x42 in found, "Immediate CTS reply must be captured, got: {}".format([hex(k) for k in found]) + cleanup_testsockets() + +test_rts_probe_immediate_reply() + += uds: immediate ECU reply is captured (sniff-before-send regression) +def test_uds_immediate_reply(): + import threading + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + def simulate_ecu(): + while True: + pkts = monitor.sniff(count=1, timeout=1.0) + if not pkts: + break + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_DIAG_A and ps != J1939_GLOBAL_ADDRESS: + resp_data = b'\x02\x7e\x00' + b'\xff' * 5 + resp_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, sa, ps) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=resp_data))) + t = threading.Thread(target=simulate_ecu) + t.start() + found = j1939_scan_uds(sock, scan_range=[0x42], sniff_time=0.3, + skip_functional=True, src_addrs=[0xF9]) + t.join(timeout=2.0) + assert 0x42 in found, "Immediate UDS reply must be captured, got: {}".format([hex(k) for k in found]) + cleanup_testsockets() + +test_uds_immediate_reply() + += xcp: immediate ECU reply is captured (sniff-before-send regression) +def test_xcp_immediate_reply(): + import threading + with TestSocket(CAN) as sock, TestSocket(CAN) as monitor: + sock.pair(monitor) + def simulate_ecu(): + while True: + pkts = monitor.sniff(count=1, timeout=1.0) + if not pkts: + break + p = pkts[0] + f = can_id_to_j1939(p.identifier); pf, ps, sa = f['pdu_format'], f['pdu_specific'], f['src'] + if pf == J1939_PF_XCP: + resp_data = bytes([J1939_XCP_POSITIVE_RESPONSE]) + b'\x00' * 7 + resp_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, sa, ps) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=resp_data))) + t = threading.Thread(target=simulate_ecu) + t.start() + found = j1939_scan_xcp(sock, scan_range=[0x42], sniff_time=0.3, + src_addrs=[0x3F]) + t.join(timeout=2.0) + assert 0x42 in found, "Immediate XCP reply must be captured, got: {}".format([hex(k) for k in found]) + cleanup_testsockets() + +test_xcp_immediate_reply() + + ++ Early exit (stop_filter) regression tests +~ conf + += unicast: sniff exits early when response found (stop_filter) +def test_unicast_early_exit(): + import time + sock = TestSocket(CAN) + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", data=b'\x00' * 8))) + t0 = time.monotonic() + found = j1939_scan_unicast(sock, scan_range=[0x42], sniff_time=5.0, src_addrs=[0xF9]) + elapsed = time.monotonic() - t0 + assert 0x42 in found, "Expected SA=0x42, got: {}".format([hex(k) for k in found]) + assert elapsed < 2.0, "Sniff should exit early, took {:.1f}s (max 2.0s)".format(elapsed) + cleanup_testsockets() + +test_unicast_early_exit() + += rts_probe: sniff exits early when response found (stop_filter) +def test_rts_probe_early_exit(): + import time + sock = TestSocket(CAN) + cts_data = bytes([J1939_TP_CTRL_CTS, 0x01, 0x01, 0xFF, 0xFF, 0xFF, 0x00, 0x00]) + resp_can_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", data=cts_data))) + t0 = time.monotonic() + found = j1939_scan_rts_probe(sock, scan_range=[0x42], sniff_time=5.0, src_addrs=[0xF9]) + elapsed = time.monotonic() - t0 + assert 0x42 in found, "Expected SA=0x42, got: {}".format([hex(k) for k in found]) + assert elapsed < 2.0, "Sniff should exit early, took {:.1f}s (max 2.0s)".format(elapsed) + cleanup_testsockets() + +test_rts_probe_early_exit() + += uds: sniff exits early when response found (stop_filter) +def test_uds_early_exit(): + import time + sock = TestSocket(CAN) + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_DIAG_A, 0xF9, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=b'\x02\x7e\x00' + b'\xff' * 5))) + t0 = time.monotonic() + found = j1939_scan_uds(sock, scan_range=[0x42], sniff_time=5.0, + skip_functional=True, src_addrs=[0xF9]) + elapsed = time.monotonic() - t0 + assert 0x42 in found, "Expected SA=0x42, got: {}".format([hex(k) for k in found]) + assert elapsed < 2.0, "Sniff should exit early, took {:.1f}s (max 2.0s)".format(elapsed) + cleanup_testsockets() + +test_uds_early_exit() + += xcp: sniff exits early when response found (stop_filter) +def test_xcp_early_exit(): + import time + sock = TestSocket(CAN) + resp_can_id = j1939_to_can_id(6, 0, 0, J1939_PF_XCP, 0x3F, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_can_id, flags="extended", + data=bytes([J1939_XCP_POSITIVE_RESPONSE]) + b'\x00' * 7))) + t0 = time.monotonic() + found = j1939_scan_xcp(sock, scan_range=[0x42], sniff_time=5.0, src_addrs=[0x3F]) + elapsed = time.monotonic() - t0 + assert 0x42 in found, "Expected SA=0x42, got: {}".format([hex(k) for k in found]) + assert elapsed < 2.0, "Sniff should exit early, took {:.1f}s (max 2.0s)".format(elapsed) + cleanup_testsockets() + +test_xcp_early_exit() + += unicast: multiple DAs found despite stale traffic (kernel buffer flush) +~ slow_test +def test_unicast_stale_frames(): + import time + from test.testsocket import SlowTestSocket, cleanup_testsockets + from scapy.layers.can import CAN + from scapy.contrib.automotive.j1939.j1939_scanner import j1939_scan_unicast + from scapy.contrib.j1939 import ( + j1939_to_can_id, + J1939_PGN_ADDRESS_CLAIMED, + J1939_GLOBAL_ADDRESS, + ) + pf_claim = (J1939_PGN_ADDRESS_CLAIMED >> 8) & 0xFF + sock = SlowTestSocket(CAN, frame_delay=0.0002, mux_throttle=0.001) + target_das = [0x10, 0x20, 0x30] + for da in target_das: + stale_id = j1939_to_can_id(6, 0, 0, 0xFE, 0x00, 0xEE) + for _ in range(30): + with sock._serial_lock: + sock._serial_buffer.append( + bytes(CAN(identifier=stale_id, flags="extended", data=b'\xCC' * 8)) + ) + resp_id = j1939_to_can_id(6, 0, 0, pf_claim, J1939_GLOBAL_ADDRESS, da) + with sock._serial_lock: + sock._serial_buffer.append( + bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8)) + ) + found = j1939_scan_unicast(sock, scan_range=target_das, + src_addrs=[0xF9], sniff_time=2.0) + found_das = [da for da in target_das if da in found] + assert len(found_das) == len(target_das), \ + "Expected all DAs found despite stale traffic, got: {}".format( + [hex(d) for d in found_das]) + cleanup_testsockets() + +test_unicast_stale_frames() + + +# Socketcan filter helpers + += j1939_sa_filter: returns correct socketcan filter for target SA + +f = j1939_sa_filter(0x42) +assert len(f) == 1 +assert f[0]["can_id"] == 0x80000042, "got 0x{:08X}".format(f[0]["can_id"]) +assert f[0]["can_mask"] == 0x800000FF, "got 0x{:08X}".format(f[0]["can_mask"]) + += j1939_sa_filter: edge cases SA=0x00 and SA=0xFF + +f0 = j1939_sa_filter(0x00) +assert f0[0]["can_id"] == 0x80000000 +assert f0[0]["can_mask"] == 0x800000FF +fFF = j1939_sa_filter(0xFF) +assert fFF[0]["can_id"] == 0x800000FF +assert fFF[0]["can_mask"] == 0x800000FF + +# Factory (reconnect_handler) API + += unicast: reconnect_handler factory is only called when socket is not working + +created_socks = [] +def _rec_factory(): + s = TestSocket(CAN) + created_socks.append(s) + return s + +main_sock = TestSocket(CAN) +main_sock.close() +j1939_scan_unicast(main_sock, scan_range=[0x10, 0x20], src_addrs=[0xF9], + sniff_time=0.01, reconnect_handler=_rec_factory) +assert len(created_socks) == 2, "Expected 2 sockets created (1 per DA)" +assert all(s.closed for s in created_socks), "All per-iteration sockets should be closed" +cleanup_testsockets() + +open_sock = TestSocket(CAN) +created_socks_open = [] +def _rec_factory_open(): + s = TestSocket(CAN) + created_socks_open.append(s) + return s + +j1939_scan_unicast(open_sock, scan_range=[0x10, 0x20], src_addrs=[0xF9], + sniff_time=0.01, reconnect_handler=_rec_factory_open) +assert len(created_socks_open) == 0, "reconnect_handler should not be called when socket is open" +assert not open_sock.closed, "Main socket should not be closed" +cleanup_testsockets() +True + += unicast: reconnect_handler=None reuses caller socket and leaves it open + +main_sock = TestSocket(CAN) +j1939_scan_unicast(main_sock, scan_range=[0x10, 0x20], src_addrs=[0xF9], + sniff_time=0.01) +assert not main_sock.closed, "Main socket should not be closed" +cleanup_testsockets() +True + += unicast: reconnect_handler factory produces same results as direct socket +def test_unicast_factory(): + def _factory(): + return TestSocket(CAN) + sock = _factory() + resp_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + found_direct = j1939_scan_unicast(sock, scan_range=[0x42], + src_addrs=[0xF9], sniff_time=0.1) + cleanup_testsockets() + factory_sock = _factory() + factory_sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + def _factory_with_data(): + return factory_sock + dummy_sock = TestSocket(CAN) + dummy_sock.close() + found_factory = j1939_scan_unicast(dummy_sock, scan_range=[0x42], + src_addrs=[0xF9], sniff_time=0.1, + reconnect_handler=_factory_with_data) + assert set(found_direct.keys()) == set(found_factory.keys()), \ + "Factory should find same SAs: direct={} factory={}".format( + list(found_direct.keys()), list(found_factory.keys())) + cleanup_testsockets() + +test_unicast_factory() +True + += dm_pgn: reconnect handler works for DM scanner +def test_dm_pgn_factory(): + from scapy.contrib.automotive.j1939.j1939_dm_scanner import ( + j1939_scan_dm, J1939_DM_PGNS, + ) + pgn = J1939_DM_PGNS["DM1"] + dm1_pf = (pgn >> 8) & 0xFF + dm1_ps = pgn & 0xFF + sock = TestSocket(CAN) + resp_id = j1939_to_can_id(6, 0, 0, dm1_pf, dm1_ps, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + def _factory(): + return sock + result = j1939_scan_dm(_factory(), target_da=0x42, dms=["DM1"], + sniff_time=0.5, reconnect_handler=_factory) + assert "DM1" in result and result["DM1"].supported, "Reconnect should find DM1 supported" + assert result["DM1"].name == "DM1" + cleanup_testsockets() + +test_dm_pgn_factory() +True + += addr_claim: reconnect_handler factory works for broadcast scan +def test_addr_claim_factory(): + sock = TestSocket(CAN) + resp_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x42) + sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) + def _factory(): + return sock + dummy_sock = TestSocket(CAN) + dummy_sock.close() + found = j1939_scan_addr_claim(dummy_sock, src_addrs=[0xF9], listen_time=0.5, reconnect_handler=_factory) + assert 0x42 in found, "Factory addr_claim should find SA=0x42" + cleanup_testsockets() + +test_addr_claim_factory() +True + + +# j1939_scan result structure + += j1939_scan: returns dict of results +sock = TestSocket(CAN) +resp_id = j1939_to_can_id(6, 0, 0, J1939_PF_ADDRESS_CLAIMED, J1939_GLOBAL_ADDRESS, 0x42) +sock.ins.send(bytes(CAN(identifier=resp_id, flags="extended", data=b'\x00' * 8))) +found = j1939_scan(sock, methods=["addr_claim"], src_addrs=[0xF9], + broadcast_listen_time=0.1, noise_ids=set()) +assert isinstance(found, dict), "Result should be dict" +assert 0x42 in found +cleanup_testsockets() + + +# verbose log level control + += j1939_scan: verbose=True sets log_j1939 to DEBUG +def test_verbose_debug(): + import logging + from scapy.contrib.j1939 import log_j1939 + old_level = log_j1939.level + sock = TestSocket(CAN) + j1939_scan(sock, methods=["addr_claim"], src_addrs=[0xF9], + broadcast_listen_time=0.02, noise_ids=set(), + verbose=True) + assert log_j1939.level == logging.DEBUG, "Expected DEBUG(10), got {}".format(log_j1939.level) + log_j1939.setLevel(old_level) + cleanup_testsockets() + +test_verbose_debug() + += j1939_scan: verbose=False does not change log level +def test_verbose_false(): + import logging + from scapy.contrib.j1939 import log_j1939 + old_level = log_j1939.level + log_j1939.setLevel(logging.WARNING) + sock = TestSocket(CAN) + j1939_scan(sock, methods=["addr_claim"], src_addrs=[0xF9], + broadcast_listen_time=0.02, noise_ids=set(), + verbose=False) + assert log_j1939.level == logging.WARNING, "Expected WARNING(30), got {}".format(log_j1939.level) + log_j1939.setLevel(old_level) + cleanup_testsockets() + +test_verbose_false() + += j1939_scan: methods=None defaults to J1939_SCAN_METHODS and noise_ids/11-bit filtering +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import ( + j1939_scan, +) +sock = TestSocket(CAN) +# 11-bit standard CAN ID (should be ignored) +sock.ins.send(bytes(CAN(identifier=0x123, flags="", data=b"\x01\x02"))) +# 29-bit noise ID (should be ignored) +noise_id = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x10) +sock.ins.send(bytes(CAN(identifier=noise_id, flags="extended", data=b"\x00\x00\x11\x22\x33\x44"))) +# Valid frame from 0x20 +valid_id = j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x20) +sock.ins.send(bytes(CAN(identifier=valid_id, flags="extended", data=b"\x01\x00\x00\x00\x00\x00\x00\x90"))) + +# methods=None tests L1344 +res = j1939_scan( + sock, + methods=None, + scan_range=[0x20], + src_addrs=[0xF9], + noise_ids={noise_id}, + broadcast_listen_time=0.01, + sniff_time=0.01, + verbose=True, +) +assert 0x10 not in res +cleanup_testsockets() + += j1939_scan: pre-set stop_event stops execution across all scan methods +from threading import Event +evt = Event() +evt.set() +sock = TestSocket(CAN) +res = j1939_scan( + sock, + methods=["addr_claim", "ecu_id", "unicast", "rts_probe", "uds", "xcp"], + scan_range=[0x20], + stop_event=evt, + verbose=True, +) +assert len(res) == 0 +cleanup_testsockets() + += Socket filter configuration error detection and warning flood prevention +from unittest.mock import patch +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_check_rx_filter_warning, j1939_sa_filter +from scapy.contrib.j1939 import j1939_to_can_id +from scapy.contrib.j1939 import log_j1939 +from test.testsocket import TestSocket, cleanup_testsockets + +# 1. Unfiltered socket receiving unexpected SA traffic: emits warning once, no flood +unfiltered_sock = TestSocket(CAN) +warn_msgs = [] +with patch.object(log_j1939, "warning", side_effect=lambda msg, *args: warn_msgs.append(msg % args if args else msg)): + # Feed 5 noise packets from unexpected SA=0x99 + for _ in range(5): + noise_can = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x99), flags="extended", data=b"\x00" * 8) + j1939_check_rx_filter_warning(noise_can, 0x10, [unfiltered_sock]) + +assert len(warn_msgs) == 1, "Expected exactly 1 warning despite multiple noise packets, got %d" % len(warn_msgs) +assert "0x10" in warn_msgs[0] +cleanup_testsockets() + +# 2. Socket receiving unexpected frames during scan: detects incorrect socket and emits warning +mismatched_sock = TestSocket(CAN) +warn_msgs_scan = [] +with patch.object(log_j1939, "warning", side_effect=lambda msg, *args: warn_msgs_scan.append(msg % args if args else msg)): + # Feed noise packet from unexpected SA=0x99 + noise_can = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x99), flags="extended", data=b"\x00" * 8) + j1939_check_rx_filter_warning(noise_can, 0x10, [mismatched_sock]) + +assert len(warn_msgs_scan) == 1, "Expected exactly 1 warning across scan, got %d" % len(warn_msgs_scan) +assert "0x10" in warn_msgs_scan[0] +cleanup_testsockets() + +# 3. Socket receiving expected frames: no warnings emitted +matching_sock = TestSocket(CAN) +warn_msgs_ok = [] +with patch.object(log_j1939, "warning", side_effect=lambda msg, *args: warn_msgs_ok.append(msg % args if args else msg)): + expected_can = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x10), flags="extended", data=b"\x00" * 8) + j1939_check_rx_filter_warning(expected_can, 0x10, [matching_sock]) + +assert len(warn_msgs_ok) == 0, "Expected no warnings for matching target SA, got %d" % len(warn_msgs_ok) +cleanup_testsockets() +True + += j1939_scan: socket bitrate detection, invalid bitrate fallback, and probe cleanup +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_scan +from test.testsocket import TestSocket, cleanup_testsockets + +mock_sock = TestSocket(CAN) +mock_sock.bitrate = "invalid_bitrate" +res = j1939_scan(mock_sock, methods=["addr_claim"], src_addrs=[0xF9], + broadcast_listen_time=0.01, noise_ids=set()) +assert isinstance(res, dict) + +def reconnect_with_bitrate(): + s = TestSocket(CAN) + s.bitrate = 500000 + return s + +res2 = j1939_scan(mock_sock, methods=["addr_claim"], src_addrs=[0xF9], + broadcast_listen_time=0.01, noise_ids=set(), + reconnect_handler=reconnect_with_bitrate) +assert isinstance(res2, dict) + +_first_call = True +def reconnect_with_failing_close(): + global _first_call + s = TestSocket(CAN) + s.bitrate = 250000 + if _first_call: + _first_call = False + def bad_close(): + s.close = lambda: None + raise OSError("cannot close probe") + s.close = bad_close + return s + +res3 = j1939_scan(mock_sock, methods=["addr_claim"], src_addrs=[0xF9], + broadcast_listen_time=0.01, noise_ids=set(), + reconnect_handler=reconnect_with_failing_close) +assert isinstance(res3, dict) +cleanup_testsockets() +True + += j1939_scan: verbose logging with noise SAs and multi-method detection +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_scan +from scapy.contrib.j1939 import j1939_to_can_id +from test.testsocket import TestSocket, cleanup_testsockets + +# Test passive noise detected verbose logging (line 1385) +s1 = TestSocket(CAN) +noise_pkt = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x50) +s1.ins.send(bytes(CAN(identifier=noise_pkt, flags="extended", data=b"\x00"*8))) +res1 = j1939_scan(s1, methods=[], noise_listen_time=0.01, verbose=True) +assert len(res1) == 0 +cleanup_testsockets() + +# Test multi-method same SA detection verbose logging (line 1428) +class EchoSocket(TestSocket): + def send(self, pkt): + super().send(pkt) + claim_pkt = j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x40) + self.ins.send(bytes(CAN(identifier=claim_pkt, flags="extended", data=b"\x00"*8))) + +s2 = EchoSocket(CAN) +res2 = j1939_scan(s2, methods=["addr_claim", "unicast"], scan_range=[0x40], + src_addrs=[0xF9], broadcast_listen_time=0.1, sniff_time=0.1, + noise_ids=set(), verbose=True) +assert 0x40 in res2 +assert len(res2[0x40]["methods"]) == 2 +cleanup_testsockets() + += j1939_scan: stop_event aborts between each sequential method +from threading import Event +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_scan +from test.testsocket import TestSocket, cleanup_testsockets + +methods_list = ["addr_claim", "ecu_id", "unicast", "rts_probe", "uds", "xcp"] +for m in methods_list: + evt = Event() + evt.set() + sock = TestSocket(CAN) + res = j1939_scan(sock, methods=[m], scan_range=[0x10], src_addrs=[0xF9], + stop_event=evt, broadcast_listen_time=0.01, sniff_time=0.01, + noise_ids=set()) + assert len(res) == 0 + cleanup_testsockets() + += j1939 scan functions: reconnect_handler factory close_sock and close_rx cleanup +from scapy.contrib.automotive.j1939.j1939_scanner import ( + j1939_scan_passive, + j1939_scan_ecu_id, + j1939_scan_rts_probe, + j1939_scan_uds, + j1939_scan_xcp, +) +from test.testsocket import TestSocket, cleanup_testsockets + +def make_factory(): + return TestSocket(CAN) + +j1939_scan_passive(TestSocket(CAN), listen_time=0.01, reconnect_handler=make_factory) +cleanup_testsockets() + +j1939_scan_ecu_id(TestSocket(CAN), src_addrs=[0xF9], listen_time=0.01, reconnect_handler=make_factory) +cleanup_testsockets() + +j1939_scan_rts_probe(TestSocket(CAN), scan_range=[0x20], src_addrs=[0xF9], sniff_time=0.01, reconnect_handler=make_factory) +cleanup_testsockets() + +j1939_scan_uds(TestSocket(CAN), scan_range=[0x20], src_addrs=[0xF9], broadcast_listen_time=0.01, sniff_time=0.01, reconnect_handler=make_factory) +cleanup_testsockets() + +j1939_scan_xcp(TestSocket(CAN), scan_range=[0x20], src_addrs=[0xF9], sniff_time=0.01, reconnect_handler=make_factory) +cleanup_testsockets() +True + += j1939 scanner: _rx packet filtering for non-extended, loopback, and empty frames +from scapy.contrib.automotive.j1939.j1939_scanner import ( + j1939_scan_passive, + j1939_scan_ecu_id, + j1939_scan_unicast, + j1939_scan_rts_probe, + j1939_scan_uds, + j1939_scan_xcp, + J1939_GLOBAL_ADDRESS, +) +from test.testsocket import TestSocket, cleanup_testsockets + +# ecu_id: non-extended, wrong PS, short data (<8 bytes) +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x123, flags="", data=b"\x00"*8))) +bad_ps = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0x10, 0x20) +s.ins.send(bytes(CAN(identifier=bad_ps, flags="extended", data=bytes([0x20, 10, 0, 2, 0xFF, 0xC5, 0xFD, 0x00])))) +bam_global = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x20) +s.ins.send(bytes(CAN(identifier=bam_global, flags="extended", data=b"\x20\x01\x02"))) +res = j1939_scan_ecu_id(s, src_addrs=[0xF9], listen_time=0.01) +assert len(res) == 0 +cleanup_testsockets() + +# unicast: non-extended frame +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x123, flags="", data=b"\x00"*8))) +res = j1939_scan_unicast(s, scan_range=[0x20], src_addrs=[0xF9], sniff_time=0.01) +assert len(res) == 0 +cleanup_testsockets() + +# rts_probe: non-extended, loopback sa == ps, empty data +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x123, flags="", data=b"\x00"*8))) +loopback_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0xF9) +s.ins.send(bytes(CAN(identifier=loopback_id, flags="extended", data=bytes([0x11, 2, 1, 0xFF, 0xFF, 0xFF, 0x00, 0x00])))) +empty_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, 0xF9, 0x20) +s.ins.send(bytes(CAN(identifier=empty_id, flags="extended", data=b""))) +res = j1939_scan_rts_probe(s, scan_range=[0x20], src_addrs=[0xF9], sniff_time=0.01) +assert len(res) == 0 +cleanup_testsockets() + +# uds functional: non-extended and noise SA +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x123, flags="", data=b"\x00"*8))) +func_id = j1939_to_can_id(6, 0, 0, 0xDB, 0xF9, 0x30) +s.ins.send(bytes(CAN(identifier=func_id, flags="extended", data=b"\x02\x7e\x00\xff\xff\xff\xff\xff"))) +res = j1939_scan_uds(s, scan_range=[0x20], src_addrs=[0xF9], noise_ids={0x30}, + broadcast_listen_time=0.01, sniff_time=0.01) +assert len(res) == 0 +cleanup_testsockets() + +# uds physical: non-extended frame +s_nonext = TestSocket(CAN) +s_nonext.ins.send(bytes(CAN(identifier=0x123, flags="", data=b"\x00"*8))) +res_p = j1939_scan_uds(s_nonext, scan_range=[0x20], src_addrs=[0xF9], skip_functional=True, sniff_time=0.01) +assert len(res_p) == 0 +cleanup_testsockets() + +# xcp: non-extended in physical +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x123, flags="", data=b"\x00"*8))) +res = j1939_scan_xcp(s, scan_range=[0x20], src_addrs=[0xF9], sniff_time=0.01) +assert len(res) == 0 +cleanup_testsockets() + += j1939 scanner: stop_event triggers inside callbacks and loops +from threading import Event +from scapy.contrib.automotive.j1939.j1939_scanner import ( + j1939_scan_passive, + j1939_scan_addr_claim, + j1939_scan_ecu_id, + j1939_scan_unicast, + j1939_scan_rts_probe, + j1939_scan_uds, + j1939_scan_xcp, +) +from test.testsocket import TestSocket, cleanup_testsockets + +# passive: stop_event aborts rx +evt = Event() +evt.set() +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18FECA10, flags="extended", data=b"\x00"*8))) +res = j1939_scan_passive(s, listen_time=0.01, stop_event=evt) +assert len(res) == 0 +cleanup_testsockets() + +evt = Event() +class StopOnSendSocket(TestSocket): + def send(self, pkt): + super().send(pkt) + evt.set() + +# addr_claim: stop_event in rx callback and src_addrs break +s = StopOnSendSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18EEFF20, flags="extended", data=b"\x00"*8))) +j1939_scan_addr_claim(s, src_addrs=[0xF1, 0xF2], listen_time=0.01, stop_event=evt) +cleanup_testsockets() + +# ecu_id: stop_event in rx callback and src_addrs break +evt.clear() +s = StopOnSendSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18ECFF20, flags="extended", data=bytes([0x20, 10, 0, 2, 0xFF, 0xC5, 0xFD, 0x00])))) +j1939_scan_ecu_id(s, src_addrs=[0xF1, 0xF2], listen_time=0.01, stop_event=evt) +cleanup_testsockets() + +# unicast: stop_event in scan_range and src_addrs break +evt.clear() +s = StopOnSendSocket(CAN) +j1939_scan_unicast(s, scan_range=[0x20, 0x21], src_addrs=[0xF1, 0xF2], sniff_time=0.01, stop_event=evt) +cleanup_testsockets() + +# rts_probe: stop_event in scan_range and src_addrs break +evt.clear() +s = StopOnSendSocket(CAN) +j1939_scan_rts_probe(s, scan_range=[0x20, 0x21], src_addrs=[0xF1, 0xF2], sniff_time=0.01, stop_event=evt) +cleanup_testsockets() + +# uds functional: stop_event in functional rx and functional src_addrs break +evt.clear() +s = StopOnSendSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18DBFFF1, flags="extended", data=b"\x02\x7e\x00\xff\xff\xff\xff\xff"))) +j1939_scan_uds(s, scan_range=[0x20], src_addrs=[0xF1, 0xF2], broadcast_listen_time=0.01, sniff_time=0.01, stop_event=evt) +cleanup_testsockets() + +# uds physical: stop_event in physical src_addrs and reqs break +evt.clear() +s = StopOnSendSocket(CAN) +j1939_scan_uds(s, scan_range=[0x20], src_addrs=[0xF1, 0xF2], skip_functional=True, sniff_time=0.01, stop_event=evt) +cleanup_testsockets() + +# xcp: stop_event in scan_range and src_addrs break +evt.clear() +s = StopOnSendSocket(CAN) +j1939_scan_xcp(s, scan_range=[0x20, 0x21], src_addrs=[0xF1, 0xF2], sniff_time=0.01, stop_event=evt) +cleanup_testsockets() +True + ++ J1939 Diagnostic layers — DiagA and DiagB tests + += J1939DiagA and J1939DiagB structure and answers() +from scapy.contrib.j1939 import ( + J1939, + J1939DiagA, + J1939DiagB, + J1939_PGN_DIAG_A, + J1939_PGN_DIAG_B, +) +assert J1939DiagA.PGN == 0xDA00 +assert J1939DiagB.PGN == 0xDB00 + +da_resp = J1939DiagA(data=b"\x02\x7e\x00") +da_req = J1939DiagA(data=b"\x02\x3e\x00") +db_req = J1939DiagB(data=b"\x02\x3e\x00") +db_resp = J1939DiagB(data=b"\x02\x7e\x00") + +# Positive and negative UDS correlation for DiagA and DiagB +assert da_resp.answers(db_req) == 1 +assert da_resp.answers(da_req) == 1 +assert da_resp.answers(da_resp) == 0 +assert db_resp.answers(db_req) == 1 +assert db_resp.answers(da_req) == 1 +assert db_resp.answers(db_resp) == 0 +assert db_req.answers(db_req) == 0 +assert db_req.answers(da_resp) == 0 +assert da_req.answers(da_req) == 0 + +# J1939 stacked packets correlation +req_func = J1939(pgn=0xDB00, src=0x10, dst=0xFF) / J1939DiagB(data=b"\x02\x3e\x00") +resp_phys = J1939(pgn=0xDA00, src=0x20, dst=0x10) / J1939DiagA(data=b"\x02\x7e\x00") +assert resp_phys.answers(req_func) == 1 +assert resp_phys[J1939DiagA].answers(req_func) == 1 +assert resp_phys[J1939DiagA].answers(req_func[J1939DiagB]) == 1 + +req_phys = J1939(pgn=0xDA00, src=0x10, dst=0x20) / J1939DiagA(data=b"\x02\x3e\x00") +assert resp_phys.answers(req_phys) == 1 +assert resp_phys[J1939DiagA].answers(req_phys) == 1 +assert resp_phys[J1939DiagA].answers(req_phys[J1939DiagA]) == 1 + +# Negative response matching on DiagA and DiagB +resp_nr = J1939(pgn=0xDA00, src=0x20, dst=0x10) / J1939DiagA(data=b"\x03\x7f\x3e\x22") +assert resp_nr.answers(req_phys) == 1 +assert resp_nr[J1939DiagA].answers(req_phys) == 1 +assert resp_nr[J1939DiagA].answers(da_req) == 1 +assert resp_nr[J1939DiagA].answers(db_req) == 1 +assert resp_nr[J1939DiagA].answers(resp_nr[J1939DiagA]) == 0 + +db_nr = J1939DiagB(data=b"\x03\x7f\x3e\x22") +assert db_nr.answers(db_req) == 1 +assert db_nr.answers(da_req) == 1 +assert db_nr.answers(db_nr) == 0 + +# DiagnosticSessionControl (0x10) subfunction matching +dsc_req = J1939DiagA(data=b"\x02\x10\x01") +dsc_resp = J1939DiagA(data=b"\x06\x50\x01\x00\x32\x01\xf4") +dsc_resp_bad = J1939DiagA(data=b"\x06\x50\x02\x00\x32\x01\xf4") +dsc_nr = J1939DiagA(data=b"\x03\x7f\x10\x12") +assert dsc_resp.answers(dsc_req) == 1 +assert dsc_resp_bad.answers(dsc_req) == 0 +assert dsc_nr.answers(dsc_req) == 1 +assert dsc_resp.answers(da_req) == 0 + +# ReadDataByIdentifier (0x22) dataIdentifier matching +rdbi_req = J1939DiagB(data=b"\x03\x22\x01\x00") +rdbi_resp = J1939DiagA(data=b"\x05\x62\x01\x00\x12\x34") +rdbi_resp_bad = J1939DiagA(data=b"\x05\x62\x02\x00\x12\x34") +assert rdbi_resp.answers(rdbi_req) == 1 +assert rdbi_resp_bad.answers(rdbi_req) == 0 +assert rdbi_resp.answers(dsc_req) == 0 + +# Direct UDS layer stacking +from scapy.contrib.automotive.uds import UDS +uds_stacked_req = J1939DiagA() / UDS(b"\x3e\x00") +uds_stacked_resp = J1939DiagA() / UDS(b"\x7e\x00") +uds_stacked_wrong = J1939DiagA() / UDS(b"\x62\x00\x00") +assert uds_stacked_resp.answers(uds_stacked_req) == 1 +assert uds_stacked_wrong.answers(uds_stacked_req) == 0 +assert uds_stacked_resp.answers(uds_stacked_resp) == 0 +assert uds_stacked_resp.answers(da_req) == 1 +assert da_resp.answers(uds_stacked_req) == 1 + +# Raw format without length prefix (padded) +raw_req = J1939DiagA(data=b"\x3e\x00\xff\xff\xff\xff\xff\xff") +raw_resp = J1939DiagA(data=b"\x7e\x00\xff\xff\xff\xff\xff\xff") +assert raw_resp.answers(raw_req) == 1 +assert raw_resp.answers(da_req) == 1 +assert da_resp.answers(raw_req) == 1 + +# Response Pending (NRC 0x78) configuration behavior +from scapy.config import conf +nr_pending = J1939DiagA(data=b"\x03\x7f\x3e\x78") +assert nr_pending.answers(da_req) == 0 +conf.contribs.setdefault("UDS", {})["treat-response-pending-as-answer"] = True +try: + assert nr_pending.answers(da_req) == 1 +finally: + conf.contribs["UDS"]["treat-response-pending-as-answer"] = False + +# Payload service identifier verification: mismatched positive response SID +resp_wrong_sid = J1939(pgn=0xDA00, src=0x20, dst=0x10) / J1939DiagA(data=b"\x03\x62\x00\x00") +assert resp_wrong_sid.answers(req_phys) == 0 +assert resp_wrong_sid[J1939DiagA].answers(req_phys) == 0 + +# Payload service identifier verification: negative response to a different service +resp_wrong_nr = J1939(pgn=0xDA00, src=0x20, dst=0x10) / J1939DiagA(data=b"\x03\x7f\x22\x22") +assert resp_wrong_nr.answers(req_phys) == 0 +assert resp_wrong_nr[J1939DiagA].answers(req_phys) == 0 + +# Address verification: unrelated diagnostic traffic between other nodes must NOT match +unrelated_phys = J1939(pgn=0xDA00, src=0x30, dst=0x40) / J1939DiagA(data=b"\x02\x7e\x00") +assert resp_phys.answers(unrelated_phys) == 0 +assert resp_phys[J1939DiagA].answers(unrelated_phys) == 0 +assert unrelated_phys.answers(req_phys) == 0 +assert unrelated_phys[J1939DiagA].answers(req_phys) == 0 +assert unrelated_phys.answers(req_func) == 0 + +# Wrong source address must NOT match directed request +wrong_sa_resp = J1939(pgn=0xDA00, src=0x30, dst=0x10) / J1939DiagA(data=b"\x02\x7e\x00") +assert wrong_sa_resp.answers(req_phys) == 0 +assert wrong_sa_resp[J1939DiagA].answers(req_phys) == 0 + +# Self echo must NOT match +echo_resp = J1939(pgn=0xDA00, src=0x10, dst=0x20) / J1939DiagA(data=b"\x02\x7e\x00") +assert echo_resp.answers(req_phys) == 0 +assert echo_resp[J1939DiagA].answers(req_phys) == 0 + +from scapy.contrib.isotp.isotp_soft_socket import TimeoutScheduler +_ts = TimeoutScheduler._thread +TimeoutScheduler.clear() +if _ts is not None and _ts.is_alive(): + _ts.join(timeout=1.0) + +True + ++ Core Scan Execution Engines tests + += _j1939_scan_broadcast_loop basic operation, matching, noise suppression, and stop_event +from threading import Event +from scapy.contrib.automotive.j1939.j1939_scanner import ( + _j1939_scan_broadcast_loop, + J1939ScanResult, + J1939Request, +) +from scapy.contrib.j1939 import ( + J1939, + J1939_GLOBAL_ADDRESS, +) +from test.testsocket import TestSocket, cleanup_testsockets + +# 1. Matching and result collection +s = TestSocket(CAN) +resp_pkt = J1939(pgn=0xFECA, src=0x20, dst=0xFF, data=b"\x00" * 8) +s.ins.send(bytes(CAN(identifier=0x18FECA20, flags="extended", data=b"\x00" * 8))) + +res = _j1939_scan_broadcast_loop( + sock=s, + src_addrs=[0xF1], + build_probes=lambda sa: [J1939(pgn=0xEA00, dst=J1939_GLOBAL_ADDRESS, src=sa) / J1939Request(req_pgn=0xFECA)], + match_response=lambda rcv: rcv.pgn == 0xFECA, + log_name="test_bcast", + listen_time=0.01, +) +assert 0x20 in res +assert len(res[0x20]) == 1 +assert res[0x20][0].scanner_src == 0xF1 +cleanup_testsockets() + +# 2. Noise suppression +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18FECA20, flags="extended", data=b"\x00" * 8))) +res_noise = _j1939_scan_broadcast_loop( + sock=s, + src_addrs=[0xF1], + build_probes=lambda sa: [J1939(pgn=0xEA00, dst=J1939_GLOBAL_ADDRESS, src=sa) / J1939Request(req_pgn=0xFECA)], + match_response=lambda rcv: rcv.pgn == 0xFECA, + log_name="test_bcast", + noise_ids={0x20}, + listen_time=0.01, +) +assert len(res_noise) == 0 +cleanup_testsockets() + +# 3. stop_event abortion +evt = Event() +evt.set() +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18FECA20, flags="extended", data=b"\x00" * 8))) +res_stop = _j1939_scan_broadcast_loop( + sock=s, + src_addrs=[0xF1, 0xF2], + build_probes=lambda sa: [J1939(pgn=0xEA00, dst=J1939_GLOBAL_ADDRESS, src=sa) / J1939Request(req_pgn=0xFECA)], + match_response=lambda rcv: rcv.pgn == 0xFECA, + log_name="test_bcast", + stop_event=evt, + listen_time=0.01, +) +assert len(res_stop) == 0 +cleanup_testsockets() +True + += _j1939_scan_sweep_loop basic operation, range matching, and stop_event +from threading import Event +from scapy.contrib.automotive.j1939.j1939_scanner import ( + _j1939_scan_sweep_loop, + J1939ScanResult, + J1939Request, +) +from scapy.contrib.j1939 import ( + J1939, +) +from test.testsocket import TestSocket, cleanup_testsockets + +# 1. Matching and response collection +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18EEFFF1, flags="extended", data=b"\x00" * 8))) + +def probe(j_sock, da, sa): + req = J1939(pgn=0xEA00, dst=da, src=sa) / J1939Request(req_pgn=0xEE00) + return j_sock.sr1(req, timeout=0.1, verbose=False) + +res = _j1939_scan_sweep_loop( + sock=s, + scan_range=[0xF1], + src_addrs=[0xF9], + default_src_addrs=[0xF9], + probe_step=probe, + log_name="test_sweep", + sniff_time=0.1, +) +assert 0xF1 in res +assert len(res[0xF1]) == 1 +assert res[0xF1][0].scanner_src == 0xF9 +cleanup_testsockets() + +# 2. Noise suppression +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18EEFFF1, flags="extended", data=b"\x00" * 8))) +res_noise = _j1939_scan_sweep_loop( + sock=s, + scan_range=[0xF1], + src_addrs=[0xF9], + default_src_addrs=[0xF9], + probe_step=probe, + log_name="test_sweep", + noise_ids={0xF1}, + sniff_time=0.01, +) +assert len(res_noise) == 0 +cleanup_testsockets() + +# 3. stop_event +evt = Event() +evt.set() +s = TestSocket(CAN) +s.ins.send(bytes(CAN(identifier=0x18EEFFF1, flags="extended", data=b"\x00" * 8))) +res_stop = _j1939_scan_sweep_loop( + sock=s, + scan_range=[0xF1, 0xF2], + src_addrs=[0xF9], + default_src_addrs=[0xF9], + probe_step=probe, + log_name="test_sweep", + stop_event=evt, + sniff_time=0.01, +) +assert len(res_stop) == 0 +cleanup_testsockets() + + ++ j1939_request_name and j1939_request_names + += j1939_request_name and j1939_request_names: broadcast and unicast +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import ( + j1939_check_rx_filter_warning, + j1939_request_name, + j1939_request_names, +) +from scapy.contrib.automotive.j1939.j1939_name import J1939Name +from scapy.contrib.j1939 import j1939_to_can_id + +# Broadcast request +sock_bc = TestSocket(CAN) +claim_id = j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x20) +name_bytes = b"\x01\x00\x00\x00\x00\x00\x00\x90" +sock_bc.ins.send(bytes(CAN(identifier=claim_id, flags="extended", data=name_bytes))) +names_bc = j1939_request_name(sock_bc, target_da=0xFF, sniff_time=0.05) +assert isinstance(names_bc, dict) +assert 0x20 in names_bc +assert isinstance(names_bc[0x20], J1939Name) +cleanup_testsockets() + +# Unicast request +sock_uni = TestSocket(CAN) +sock_uni.ins.send(bytes(CAN(identifier=claim_id, flags="extended", data=name_bytes))) +name_uni = j1939_request_name(sock_uni, target_da=0x20, sniff_time=0.05) +assert isinstance(name_uni, J1939Name) +cleanup_testsockets() + +# j1939_request_names broadcast (target_das=None) +sock_scan_bc = TestSocket(CAN) +sock_scan_bc.ins.send(bytes(CAN(identifier=claim_id, flags="extended", data=name_bytes))) +scan_res_bc = j1939_request_names(sock_scan_bc, target_das=None, sniff_time=0.05) +assert isinstance(scan_res_bc, dict) +assert 0x20 in scan_res_bc +cleanup_testsockets() + +# j1939_request_names targeted +sock_scan_tgt = TestSocket(CAN) +sock_scan_tgt.ins.send(bytes(CAN(identifier=claim_id, flags="extended", data=name_bytes))) +scan_res_tgt = j1939_request_names(sock_scan_tgt, target_das=[0x20], sniff_time=0.05) +assert 0x20 in scan_res_tgt +assert isinstance(scan_res_tgt[0x20], J1939Name) +cleanup_testsockets() + += j1939_request_name: multiple responders to broadcast request +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_request_name +from scapy.contrib.j1939 import j1939_to_can_id +sock_multi = TestSocket(CAN) +claim_20 = j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x20) +name_20 = b"\x01\x00\x00\x00\x00\x00\x00\x90" +claim_21 = j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x21) +name_21 = b"\x02\x00\x00\x00\x00\x00\x00\x90" +sock_multi.ins.send(bytes(CAN(identifier=claim_20, flags="extended", data=name_20))) +sock_multi.ins.send(bytes(CAN(identifier=claim_21, flags="extended", data=name_21))) +names_multi = j1939_request_name(sock_multi, target_da=0xFF, sniff_time=0.05) +assert isinstance(names_multi, dict) +assert 0x20 in names_multi and 0x21 in names_multi +assert names_multi[0x20].identity_number == 1 +assert names_multi[0x21].identity_number == 2 +cleanup_testsockets() + += j1939_request_name: unicast request accepts broadcast (DA=0xFF) claim response +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_name import J1939Name +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_request_name +from scapy.contrib.j1939 import j1939_to_can_id +sock_uni_bc = TestSocket(CAN) +claim_global_da = j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x25) +name_25 = b"\x05\x00\x00\x00\x00\x00\x00\x90" +sock_uni_bc.ins.send(bytes(CAN(identifier=claim_global_da, flags="extended", data=name_25))) +name_res = j1939_request_name(sock_uni_bc, target_da=0x25, sniff_time=0.05) +assert isinstance(name_res, J1939Name) +assert name_res.identity_number == 5 +cleanup_testsockets() + += j1939_check_rx_filter_warning detects mismatched SA +from unittest.mock import patch +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_check_rx_filter_warning +from scapy.contrib.j1939 import j1939_to_can_id +warns_rx = [] +dummy_sock = TestSocket(CAN) +with patch("scapy.contrib.automotive.j1939.j1939_scanner.log_j1939.warning", side_effect=lambda msg, *args: warns_rx.append(msg % args if args else msg)): + pkt_match = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x20), flags="extended") + j1939_check_rx_filter_warning(pkt_match, 0x20, [dummy_sock]) + assert len(warns_rx) == 0 + pkt_mismatch = CAN(identifier=j1939_to_can_id(6, 0, 0, 0xEE, 0xFF, 0x25), flags="extended") + j1939_check_rx_filter_warning(pkt_mismatch, 0x20, [dummy_sock]) + assert len(warns_rx) == 1 + assert "0x20" in warns_rx[0] + +cleanup_testsockets() + +from scapy.contrib.isotp.isotp_soft_socket import TimeoutScheduler +_ts = TimeoutScheduler._thread +TimeoutScheduler.clear() +if _ts is not None and _ts.is_alive(): + _ts.join(timeout=1.0) + +True + + + ++ J1939 Automotive Scanner Classes +~ automotive_comm + += J1939_Scanner direct execution and state transition +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import J1939_Scanner, J1939_Unicast_TestCase +sock = TestSocket(CAN) +scanner = J1939_Scanner(sock, scan_range=[0x10, 0x20], test_cases=[J1939_Unicast_TestCase]) +scanner.scan() +assert scanner.scan_completed +cleanup_testsockets() + += J1939_Scanner get_results returns merged dictionary +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import J1939_Scanner, J1939_Unicast_TestCase, J1939ScanResult +from scapy.contrib.j1939 import J1939 +sock = TestSocket(CAN) +tc = J1939_Unicast_TestCase() +tc.results = {0x10: [J1939ScanResult(J1939(), scanner_src=0xF1)]} +scanner = J1939_Scanner(sock, scan_range=[0x10], test_cases=[tc]) +res = scanner.get_results() +assert 0x10 in res +assert "methods" in res[0x10] and "packets" in res[0x10] +cleanup_testsockets() + += J1939ScanResult equality and representation +from scapy.contrib.automotive.j1939.j1939_scanner import J1939ScanResult +from scapy.contrib.j1939 import J1939 +r1 = J1939ScanResult(J1939(), scanner_src=0xF1) +assert repr(r1).startswith("J1939ScanResult(") +assert r1 != "not_a_result" +r2 = J1939ScanResult(J1939(), scanner_src=0xF1) +assert r1 == r2 + += J1939_Scanner default_test_case_clss and merging multiple results +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_Scanner, + J1939_AddrClaim_TestCase, + J1939_EcuId_TestCase, + J1939_Unicast_TestCase, + J1939_RtsProbe_TestCase, + J1939_UDS_TestCase, + J1939_XCP_TestCase, + J1939ScanResult, +) +from scapy.contrib.j1939 import J1939 +sock = TestSocket(CAN) +scanner = J1939_Scanner(sock) +assert len(scanner.default_test_case_clss) == 6 + +# Multi-result merging for the same SA +tc1 = J1939_AddrClaim_TestCase() +tc1.results = {0x10: [J1939ScanResult(J1939(), scanner_src=0xF1)]} +tc2 = J1939_Unicast_TestCase() +tc2.results = {0x10: [J1939ScanResult(J1939(), scanner_src=0xF2)]} +scanner_multi = J1939_Scanner(sock, test_cases=[tc1, tc2]) +res_multi = scanner_multi.get_results() +assert 0x10 in res_multi +assert len(res_multi[0x10]["methods"]) == 2 +assert "addr_claim" in res_multi[0x10]["methods"] +assert "unicast" in res_multi[0x10]["methods"] +cleanup_testsockets() + += J1939_CA_TestCase execution via J1939_Scanner +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_Scanner, + J1939_AddrClaim_TestCase, + J1939_EcuId_TestCase, + J1939_RtsProbe_TestCase, + J1939_UDS_TestCase, + J1939_XCP_TestCase, +) +for cls in [ + J1939_AddrClaim_TestCase, + J1939_EcuId_TestCase, + J1939_RtsProbe_TestCase, + J1939_UDS_TestCase, + J1939_XCP_TestCase, +]: + tc = cls() + assert tc.supported_responses == [] + s = TestSocket(CAN) + kwargs = { + "{}_kwargs".format(cls.__name__): { + "broadcast_listen_time": 0.01, + "sniff_time": 0.01, + "scan_range": [0x10], + "src_addrs": [0xF9], + } + } + sc = J1939_Scanner(s, scan_range=[0x10], test_cases=[tc], **kwargs) + sc.scan() + assert sc.scan_completed + cleanup_testsockets() + += j1939_reconnect_with_retry and j1939_get_sock error handling +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import ( + j1939_get_sock, + j1939_reconnect_with_retry, +) + +# j1939_reconnect_with_retry exhaustion +try: + j1939_reconnect_with_retry(lambda: (_ for _ in ()).throw(OSError("fail")), reconnect_retries=1, retry_delay=0.001) + assert False, "Should have raised OSError" +except OSError as ex: + assert "fail" in str(ex) + +# j1939_get_sock close exception logging +class FaultySocket(TestSocket): + should_fail = True + def close(self): + if self.should_fail: + raise OSError("failed to close") + super(FaultySocket, self).close() + +faulty = FaultySocket(CAN) +faulty.closed = True +reconn_sock = FaultySocket(CAN) +with j1939_get_sock(faulty, reconnect_handler=lambda: reconn_sock) as s: + pass + +faulty.should_fail = False +reconn_sock.should_fail = False +cleanup_testsockets() + += rts_probe raw byte fallback and direct ECU_ID match +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import ( + j1939_scan_rts_probe, + j1939_scan_ecu_id, + J1939_PGN_ECU_ID, + J1939_ACK_CTRL_NACK, +) +from scapy.contrib.j1939 import ( + j1939_to_can_id, + J1939_PGN_TP_CM, + J1939_TP_CTRL_CTS, + J1939_PGN_ACK, +) + +# 1. Direct ECU ID match (non-BAM) +s_ecu = TestSocket(CAN) +ecu_id = j1939_to_can_id(6, 0, 0, (J1939_PGN_ECU_ID >> 8) & 0xFF, J1939_PGN_ECU_ID & 0xFF, 0x20) +s_ecu.ins.send(bytes(CAN(identifier=ecu_id, flags="extended", data=b"ECU_DATA*"))) +res_ecu = j1939_scan_ecu_id(s_ecu, src_addrs=[0xF1], listen_time=0.05) +assert 0x20 in res_ecu +cleanup_testsockets() + +# 2. rts_probe raw byte CTS and ACK fallbacks +s_rts_cts = TestSocket(CAN) +cts_id = j1939_to_can_id(7, 0, 0, (J1939_PGN_TP_CM >> 8) & 0xFF, 0xF9, 0x20) +cts_raw = bytes([J1939_TP_CTRL_CTS, 2, 1, 0xFF, 0xFF, 0xFF, 0x00, 0x00]) +s_rts_cts.ins.send(bytes(CAN(identifier=cts_id, flags="extended", data=cts_raw))) +res_cts = j1939_scan_rts_probe(s_rts_cts, scan_range=[0x20], src_addrs=[0xF9], sniff_time=0.05) +assert 0x20 in res_cts +cleanup_testsockets() + +s_rts_ack = TestSocket(CAN) +ack_id = j1939_to_can_id(6, 0, 0, (J1939_PGN_ACK >> 8) & 0xFF, 0xF9, 0x20) +ack_raw = bytes([J1939_ACK_CTRL_NACK, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00]) +s_rts_ack.ins.send(bytes(CAN(identifier=ack_id, flags="extended", data=ack_raw))) +res_ack = j1939_scan_rts_probe(s_rts_ack, scan_range=[0x20], src_addrs=[0xF9], sniff_time=0.05) +assert 0x20 in res_ack +cleanup_testsockets() + += j1939_request_name timeout and inter_probe_delay +from test.testsocket import TestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import j1939_request_name +s = TestSocket(CAN) +res_none = j1939_request_name(s, target_da=0x20, sniff_time=0.01, busload=0.01) +assert res_none is None +cleanup_testsockets() + + ++ J1939_Scanner – Super Slow slcan Interface Tests +~ slow_test + += J1939_Scanner: broadcast test cases (addr_claim, ecu_id) over super slow slcan +from test.testsocket import SlowTestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_Scanner, + J1939_AddrClaim_TestCase, + J1939_EcuId_TestCase, + J1939_PGN_ECU_ID, +) +from scapy.contrib.j1939 import ( + j1939_to_can_id, + J1939_PGN_ADDRESS_CLAIMED, + J1939_GLOBAL_ADDRESS, +) + +slow_sock = SlowTestSocket( + CAN, + frame_delay=0.005, + mux_throttle=0.001, + serial_timeout=0.1, + read_time_limit=0.02, + interface_name="slcan", +) +with slow_sock._serial_lock: + for _ in range(2): + slow_sock._serial_buffer.append(bytes(CAN(identifier=0x18FE0099, flags="extended", data=b"\x01" * 8))) + pf_claim = (J1939_PGN_ADDRESS_CLAIMED >> 8) & 0xFF + claim_id1 = j1939_to_can_id(6, 0, 0, pf_claim, J1939_GLOBAL_ADDRESS, 0x10) + slow_sock._serial_buffer.append(bytes(CAN(identifier=claim_id1, flags="extended", data=b"\x10" * 8))) + claim_id2 = j1939_to_can_id(6, 0, 0, pf_claim, J1939_GLOBAL_ADDRESS, 0x20) + slow_sock._serial_buffer.append(bytes(CAN(identifier=claim_id2, flags="extended", data=b"\x20" * 8))) + +tc_ac = J1939_AddrClaim_TestCase() +sc_ac = J1939_Scanner( + slow_sock, + test_cases=[tc_ac], + J1939_AddrClaim_TestCase_kwargs={"broadcast_listen_time": 1.0, "src_addrs": [0xF9]}, +) +sc_ac.scan() +assert sc_ac.scan_completed +res_ac = sc_ac.get_results() +assert 0x10 in res_ac and 0x20 in res_ac +cleanup_testsockets() + +slow_sock_ecu = SlowTestSocket( + CAN, + frame_delay=0.005, + mux_throttle=0.001, + serial_timeout=0.1, + read_time_limit=0.02, + interface_name="slcan", +) +with slow_sock_ecu._serial_lock: + for _ in range(2): + slow_sock_ecu._serial_buffer.append(bytes(CAN(identifier=0x18FE0099, flags="extended", data=b"\x01" * 8))) + pf_ecu = (J1939_PGN_ECU_ID >> 8) & 0xFF + ps_ecu = J1939_PGN_ECU_ID & 0xFF + ecu_id = j1939_to_can_id(6, 0, 0, pf_ecu, ps_ecu, 0x30) + slow_sock_ecu._serial_buffer.append(bytes(CAN(identifier=ecu_id, flags="extended", data=b"ECUID***"))) + +tc_ei = J1939_EcuId_TestCase() +sc_ei = J1939_Scanner( + slow_sock_ecu, + test_cases=[tc_ei], + J1939_EcuId_TestCase_kwargs={"broadcast_listen_time": 1.0, "src_addrs": [0xF9]}, +) +sc_ei.scan() +assert sc_ei.scan_completed +res_ei = sc_ei.get_results() +assert 0x30 in res_ei +cleanup_testsockets() + += J1939_Scanner: unicast sweep test cases (unicast, rts_probe) over super slow slcan +from test.testsocket import SlowTestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_Scanner, + J1939_Unicast_TestCase, + J1939_RtsProbe_TestCase, +) +from scapy.contrib.j1939 import ( + j1939_to_can_id, + J1939_PGN_ADDRESS_CLAIMED, + J1939_PGN_TP_CM, + J1939_TP_CTRL_CTS, + J1939_GLOBAL_ADDRESS, +) + +slow_sock_uni = SlowTestSocket( + CAN, + frame_delay=0.005, + mux_throttle=0.001, + serial_timeout=0.1, + read_time_limit=0.02, + interface_name="slcan", +) +target_das_uni = [0x15, 0x25] +pf_claim = (J1939_PGN_ADDRESS_CLAIMED >> 8) & 0xFF +with slow_sock_uni._serial_lock: + for da in target_das_uni: + for _ in range(2): + slow_sock_uni._serial_buffer.append(bytes(CAN(identifier=0x18FE0099, flags="extended", data=b"\x01" * 8))) + resp_id = j1939_to_can_id(6, 0, 0, pf_claim, J1939_GLOBAL_ADDRESS, da) + slow_sock_uni._serial_buffer.append(bytes(CAN(identifier=resp_id, flags="extended", data=b"\x00" * 8))) + +tc_uni = J1939_Unicast_TestCase() +sc_uni = J1939_Scanner( + slow_sock_uni, + scan_range=target_das_uni, + test_cases=[tc_uni], + J1939_Unicast_TestCase_kwargs={"sniff_time": 1.0, "src_addrs": [0xF9]}, +) +sc_uni.scan() +assert sc_uni.scan_completed +res_uni = sc_uni.get_results() +assert 0x15 in res_uni and 0x25 in res_uni +cleanup_testsockets() + +slow_sock_rts = SlowTestSocket( + CAN, + frame_delay=0.005, + mux_throttle=0.001, + serial_timeout=0.1, + read_time_limit=0.02, + interface_name="slcan", +) +target_das_rts = [0x30] +pf_tp = (J1939_PGN_TP_CM >> 8) & 0xFF +with slow_sock_rts._serial_lock: + for _ in range(2): + slow_sock_rts._serial_buffer.append(bytes(CAN(identifier=0x18FE0099, flags="extended", data=b"\x01" * 8))) + resp_id = j1939_to_can_id(7, 0, 0, pf_tp, 0xF9, 0x30) + cts_raw = bytes([J1939_TP_CTRL_CTS, 2, 1, 0xFF, 0xFF, 0xFF, 0x00, 0x00]) + slow_sock_rts._serial_buffer.append(bytes(CAN(identifier=resp_id, flags="extended", data=cts_raw))) + +tc_rts = J1939_RtsProbe_TestCase() +sc_rts = J1939_Scanner( + slow_sock_rts, + scan_range=target_das_rts, + test_cases=[tc_rts], + J1939_RtsProbe_TestCase_kwargs={"sniff_time": 1.0, "src_addrs": [0xF9]}, +) +sc_rts.scan() +assert sc_rts.scan_completed +res_rts = sc_rts.get_results() +assert 0x30 in res_rts +cleanup_testsockets() + += J1939_Scanner: diagnostic test cases (uds, xcp) over super slow slcan +from test.testsocket import SlowTestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import ( + J1939_Scanner, + J1939_UDS_TestCase, + J1939_XCP_TestCase, + J1939_XCP_POSITIVE_RESPONSE, +) +from scapy.contrib.j1939 import j1939_to_can_id + +slow_sock_uds = SlowTestSocket( + CAN, + frame_delay=0.005, + mux_throttle=0.001, + serial_timeout=0.1, + read_time_limit=0.02, + interface_name="slcan", +) +target_das_uds = [0x40] +with slow_sock_uds._serial_lock: + for _ in range(2): + slow_sock_uds._serial_buffer.append(bytes(CAN(identifier=0x18FE0099, flags="extended", data=b"\x01" * 8))) + resp_id = j1939_to_can_id(6, 0, 0, 0xDA, 0xF9, 0x40) + slow_sock_uds._serial_buffer.append(bytes(CAN(identifier=resp_id, flags="extended", data=b"\x02\x7e\x00\xff\xff\xff\xff\xff"))) + +tc_uds = J1939_UDS_TestCase() +sc_uds = J1939_Scanner( + slow_sock_uds, + scan_range=target_das_uds, + test_cases=[tc_uds], + J1939_UDS_TestCase_kwargs={"sniff_time": 1.0, "src_addrs": [0xF9], "skip_functional": True}, +) +sc_uds.scan() +assert sc_uds.scan_completed +res_uds = sc_uds.get_results() +assert 0x40 in res_uds +cleanup_testsockets() + +slow_sock_xcp = SlowTestSocket( + CAN, + frame_delay=0.005, + mux_throttle=0.001, + serial_timeout=0.1, + read_time_limit=0.02, + interface_name="slcan", +) +target_das_xcp = [0x50] +with slow_sock_xcp._serial_lock: + for _ in range(2): + slow_sock_xcp._serial_buffer.append(bytes(CAN(identifier=0x18FE0099, flags="extended", data=b"\x01" * 8))) + resp_id = j1939_to_can_id(6, 0, 0, 0xEF, 0x3F, 0x50) + slow_sock_xcp._serial_buffer.append(bytes(CAN(identifier=resp_id, flags="extended", data=bytes([J1939_XCP_POSITIVE_RESPONSE]) + b"\x00" * 7))) + +tc_xcp = J1939_XCP_TestCase() +sc_xcp = J1939_Scanner( + slow_sock_xcp, + scan_range=target_das_xcp, + test_cases=[tc_xcp], + J1939_XCP_TestCase_kwargs={"sniff_time": 1.0, "src_addrs": [0x3F]}, +) +sc_xcp.scan() +assert sc_xcp.scan_completed +res_xcp = sc_xcp.get_results() +assert 0x50 in res_xcp +cleanup_testsockets() + += J1939_Scanner: default full test case suite over super slow slcan +from test.testsocket import SlowTestSocket, cleanup_testsockets +from scapy.layers.can import CAN +from scapy.contrib.automotive.j1939.j1939_scanner import J1939_Scanner + +slow_sock_full = SlowTestSocket( + CAN, + frame_delay=0.005, + mux_throttle=0.001, + serial_timeout=0.1, + read_time_limit=0.02, + interface_name="slcan", +) +common_kwargs = { + "broadcast_listen_time": 0.05, + "sniff_time": 0.05, + "scan_range": [0x10], + "src_addrs": [0xF9], +} +kwargs = { + "{}_kwargs".format(cls.__name__): common_kwargs + for cls in J1939_Scanner(slow_sock_full).default_test_case_clss +} +scanner_full = J1939_Scanner(slow_sock_full, scan_range=[0x10], **kwargs) +scanner_full.scan() +assert scanner_full.scan_completed +cleanup_testsockets() + +from scapy.contrib.isotp.isotp_soft_socket import TimeoutScheduler +_ts = TimeoutScheduler._thread +TimeoutScheduler.clear() +if _ts is not None and _ts.is_alive(): + _ts.join(timeout=1.0) + + diff --git a/test/contrib/automotive/scanner/uds_scanner.uts b/test/contrib/automotive/scanner/uds_scanner.uts index 3c0940e0f1e..928e0d117bd 100644 --- a/test/contrib/automotive/scanner/uds_scanner.uts +++ b/test/contrib/automotive/scanner/uds_scanner.uts @@ -45,10 +45,13 @@ def executeScannerInVirtualEnvironment(supported_responses, enumerators, unstabl answering_machine.state["session"] = 1 sniff(timeout=0.001, opened_socket=[ecu, tester]) def reconnect(): + nonlocal tester try: tester.close() - except Exception: + except (AttributeError, OSError): pass + tester_obj_pipe.clear() + ecu.paired_sockets = [s for s in ecu.paired_sockets if not s.closed and s is not tester] tester = TesterSocket(UDS, tester_obj_pipe) ecu.pair(tester) return tester @@ -1130,7 +1133,10 @@ pkt = UDS_RMBARandomEnumerator._random_memory_addr_pkt() assert pkt.memorySizeLen in [1, 2, 3, 4] assert pkt.memoryAddressLen in [1, 2, 3, 4] -pkt2 = UDS_RMBARandomEnumerator._random_memory_addr_pkt() +for _ in range(10): + pkt2 = UDS_RMBARandomEnumerator._random_memory_addr_pkt() + if pkt != pkt2: + break assert pkt != pkt2 diff --git a/test/contrib/j1939.uts b/test/contrib/j1939.uts index 31b687764f2..35849fb1b91 100644 --- a/test/contrib/j1939.uts +++ b/test/contrib/j1939.uts @@ -17,10 +17,12 @@ from scapy.contrib.j1939 import ( J1939_TP_CM, J1939_TP_CM_RTS, J1939_TP_CM_CTS, J1939_TP_CM_ACK, J1939_TP_CM_BAM, J1939_TP_CM_ABORT, J1939_TP_DT, J1939_BROADCAST_ADDR, + J1939_GLOBAL_ADDRESS, J1939_PGN_TP_CM, J1939_PGN_TP_DT, J1939_TP_CTRL_RTS, J1939_TP_CTRL_CTS, J1939_TP_CTRL_ACK, J1939_TP_CTRL_BAM, J1939_TP_CTRL_ABORT, - can_id_to_j1939, j1939_to_can_id, pgn_from_fields, dst_from_fields, + can_id_to_j1939, j1939_to_can_id, + j1939_pgn_from_fields, pgn_is_pdu1, ) @@ -156,6 +158,10 @@ for nxt in [1, 4, 7, 255]: ############ + Helper function tests += J1939_BROADCAST_ADDR constant value +assert J1939_BROADCAST_ADDR == 0xFF +assert J1939_BROADCAST_ADDR == J1939_GLOBAL_ADDRESS + = pgn_is_pdu1 with PDU1 PGN (PF < 240) assert pgn_is_pdu1(0xEC00) == True assert pgn_is_pdu1(0xEA00) == True @@ -205,41 +211,41 @@ for priority in [0, 3, 6, 7]: assert fields['pdu_specific'] == ps assert fields['src'] == sa -= pgn_from_fields – PDU2 frame (PF >= 240) += j1939_pgn_from_fields – PDU2 frame (PF >= 240) # PF=0xFE (254), PS=0xCA → PGN includes PS -pgn = pgn_from_fields(0, 0xFE, 0xCA) +pgn = j1939_pgn_from_fields(0, 0xFE, 0xCA) assert pgn == 0xFECA -= pgn_from_fields – PDU2 frame with data_page=1 -pgn = pgn_from_fields(1, 0xFE, 0xCA) += j1939_pgn_from_fields – PDU2 frame with data_page=1 +pgn = j1939_pgn_from_fields(1, 0xFE, 0xCA) assert pgn == 0x1FECA -= pgn_from_fields – PDU1 frame (PF < 240) += j1939_pgn_from_fields – PDU1 frame (PF < 240) # PF=0xEC (236), PS=0x00 (destination, not part of PGN) -pgn = pgn_from_fields(0, 0xEC, 0x00) +pgn = j1939_pgn_from_fields(0, 0xEC, 0x00) assert pgn == 0xEC00 -= pgn_from_fields – PDU1 PGN does not include PS -pgn1 = pgn_from_fields(0, 0xEB, 0x00) -pgn2 = pgn_from_fields(0, 0xEB, 0xFF) += j1939_pgn_from_fields – PDU1 PGN does not include PS +pgn1 = j1939_pgn_from_fields(0, 0xEB, 0x00) +pgn2 = j1939_pgn_from_fields(0, 0xEB, 0xFF) assert pgn1 == pgn2, "PDU1 PGN must not depend on pdu_specific" -= dst_from_fields – PDU1 yields destination address -dst = dst_from_fields(0xEC, 0x42) += J1939_CAN.dst – PDU1 yields destination address +dst = J1939_CAN(pdu_format=0xEC, pdu_specific=0x42).dst assert dst == 0x42 -= dst_from_fields – PDU2 yields broadcast -dst = dst_from_fields(0xFE, 0xCA) += J1939_CAN.dst – PDU2 yields broadcast +dst = J1939_CAN(pdu_format=0xFE, pdu_specific=0xCA).dst assert dst == J1939_NO_ADDR # 0xFF -= dst_from_fields – PDU1/PDU2 boundary: PF=0xEF (239) is still PDU1 += J1939_CAN.dst – PDU1/PDU2 boundary: PF=0xEF (239) is still PDU1 # PF=0xEF is the last PDU1 value (< 240); pdu_specific is the destination address -dst = dst_from_fields(0xEF, 0x42) +dst = J1939_CAN(pdu_format=0xEF, pdu_specific=0x42).dst assert dst == 0x42, "PF=0xEF (239) must be PDU1 – PS is destination address" -= dst_from_fields – PDU1/PDU2 boundary: PF=0xF0 (240) is the first PDU2 value += J1939_CAN.dst – PDU1/PDU2 boundary: PF=0xF0 (240) is the first PDU2 value # PF=0xF0 is the first PDU2 value (>= 240); no peer-to-peer destination -dst = dst_from_fields(0xF0, 0x04) +dst = J1939_CAN(pdu_format=0xF0, pdu_specific=0x04).dst assert dst == J1939_NO_ADDR, "PF=0xF0 (240) must be PDU2 – broadcast only" @@ -280,24 +286,24 @@ assert fields['src'] == 0xFF ############ ############ -+ pgn_from_fields additional coverage ++ j1939_pgn_from_fields additional coverage # Inspired by TruckDevil test_j1939_message_pgn_destination_specific_vs_broadcast -= pgn_from_fields – PDU2 with group extension exactly at 0xF0 (TruckDevil: 0x18FEF000 → 0xFEF0) += j1939_pgn_from_fields – PDU2 with group extension exactly at 0xF0 (TruckDevil: 0x18FEF000 → 0xFEF0) # CAN ID 0x18FEF000: priority=6, r=0, dp=0, PF=0xFE (254), PS=0xF0, SA=0x00 # PF >= 240 → PDU2 → PGN includes PS: (0 << 16) | (0xFE << 8) | 0xF0 = 0xFEF0 -pgn = pgn_from_fields(0, 0xFE, 0xF0) +pgn = j1939_pgn_from_fields(0, 0xFE, 0xF0) assert pgn == 0xFEF0, "PDU2 PGN must include group-extension PS; got 0x%05X" % pgn -= pgn_from_fields – PDU1 PGN masks out destination address (TruckDevil: 0x00EC0B00 → 0xEC00) += j1939_pgn_from_fields – PDU1 PGN masks out destination address (TruckDevil: 0x00EC0B00 → 0xEC00) # CAN ID 0x00EC0B00: priority=0, r=0, dp=0, PF=0xEC (236), PS=0x0B, SA=0x00 # PF < 240 → PDU1 → PS is destination address, not part of PGN -pgn = pgn_from_fields(0, 0xEC, 0x0B) +pgn = j1939_pgn_from_fields(0, 0xEC, 0x0B) assert pgn == 0xEC00, "PDU1 PGN must not include destination address; got 0x%05X" % pgn -= pgn_from_fields – EEC1 (Electronic Engine Controller 1, PGN 61444 = 0xF004) += j1939_pgn_from_fields – EEC1 (Electronic Engine Controller 1, PGN 61444 = 0xF004) # J1939 PGN 61444 (0xF004): dp=0, PF=0xF0, PS=0x04 – broadcast -pgn = pgn_from_fields(0, 0xF0, 0x04) +pgn = j1939_pgn_from_fields(0, 0xF0, 0x04) assert pgn == 0xF004, "EEC1 PGN should be 0xF004; got 0x%05X" % pgn @@ -375,9 +381,10 @@ p = J1939(b'\x01', priority=3, pgn=0xFECA, src=0x00, dst=0xFF) assert bytes(p) == b'\x01' = J1939 answers -p = J1939(b'\x01\x02', pgn=0xFECA) -r = J1939(b'\x01\x02', pgn=0xFECA) +p = J1939(b'\x01\x02', pgn=0xFECA, src=0x20, dst=0x10) +r = J1939(b'\x01\x02', pgn=0xFECA, src=0x10, dst=0x20) assert p.answers(r) +assert not J1939(b'\x01\x02', pgn=0xFECA).answers(r) = J1939 does not answer different data p = J1939(b'\x01') @@ -510,6 +517,41 @@ assert p.src == 0x00 assert p.pgn == 0x0000 assert p.dst == 0xFF += J1939_CAN identifier property returns 29-bit CAN ID +p = J1939_CAN(priority=6, pdu_format=0xFE, pdu_specific=0xCA, src=0x00) +assert p.identifier == 0x18FECA00 +assert p.identifier == j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x00) + += J1939_CAN identifier setter updates sub-fields +p = J1939_CAN() +p.identifier = 0x18EA01F1 +assert p.priority == 6 +assert p.reserved == 0 +assert p.data_page == 0 +assert p.pdu_format == 0xEA +assert p.pdu_specific == 0x01 +assert p.src == 0xF1 +assert p.identifier == 0x18EA01F1 + += J1939_CAN compatible with cansocket_python_can.CANSocket.send +def _test_cansocket_compat(): + from unittest.mock import MagicMock + try: + from scapy.contrib.cansocket_python_can import CANSocket + except ImportError: + return True + mock_sock = CANSocket.__new__(CANSocket) + mock_sock.can_iface = MagicMock() + pkt = J1939_CAN(priority=6, pdu_format=0xEA, pdu_specific=0x01, src=0xF1, data=b'\x01') + mock_sock.send(pkt) + assert mock_sock.can_iface.send.called + msg = mock_sock.can_iface.send.call_args[0][0] + assert msg.arbitration_id == 0x18EA01F1 + return True + +_test_cansocket_compat() + + ############ ############ @@ -1084,7 +1126,7 @@ can_receiver_seg.ins.settimeout(3.0) def _send_segmented_tx(): sleep(0.1) - j1939_sender_seg.send(J1939(tx_seg_payload, pgn=tx_seg_pgn, src=tx_seg_src, dst=J1939_BROADCAST_ADDR)) + j1939_sender_seg.send(J1939(tx_seg_payload, pgn=tx_seg_pgn, src=tx_seg_src, dst=J1939_GLOBAL_ADDRESS)) t_seg_tx = threading.Thread(target=_send_segmented_tx) t_seg_tx.start() @@ -1124,7 +1166,7 @@ cm_wire = bytes(J1939_TP_CM_BAM(total_size=len(rx_seg_payload), num_packets=rx_s cm_decoded = J1939_TP_CM.dispatch_hook(cm_wire)(cm_wire) assert isinstance(cm_decoded, J1939_TP_CM_BAM) -cm_can = J1939_CAN(priority=6, data_page=0, pdu_format=0xEC, pdu_specific=J1939_BROADCAST_ADDR, +cm_can = J1939_CAN(priority=6, data_page=0, pdu_format=0xEC, pdu_specific=J1939_GLOBAL_ADDRESS, src=rx_seg_src, data=bytes(cm_decoded)) dt_can_frames = [] @@ -1134,7 +1176,7 @@ for seq in range(1, rx_seg_packets + 1): if len(chunk) < 7: chunk += b'\xFF' * (7 - len(chunk)) dt_can_frames.append( - J1939_CAN(priority=7, data_page=0, pdu_format=0xEB, pdu_specific=J1939_BROADCAST_ADDR, + J1939_CAN(priority=7, data_page=0, pdu_format=0xEB, pdu_specific=J1939_GLOBAL_ADDRESS, src=rx_seg_src, data=bytes(J1939_TP_DT(seq_num=seq, data=chunk))) ) @@ -1823,7 +1865,7 @@ assert '3' in s, "priority 3 missing: %r" % s = J1939.mysummary with broadcast addresses from scapy.contrib.j1939 import J1939 -p = J1939(b'\x11', pgn=0xFECA, src=J1939_IDLE_ADDR, dst=J1939_BROADCAST_ADDR, priority=7) +p = J1939(b'\x11', pgn=0xFECA, src=J1939_IDLE_ADDR, dst=J1939_GLOBAL_ADDRESS, priority=7) s = p.mysummary() assert isinstance(s, str) # IDLE_ADDR=0xFE=254, BROADCAST_ADDR=0xFF=255 @@ -4981,8 +5023,816 @@ with USBTestSocket(CAN, hw_fifo_size=16) as usb_cans, TestSocket(CAN) as stim: "close drain must free adapter FIFO for next socket" assert _usb_pkts[0].data == _usb_cd_payload += J1939Socket – dynamic backend dispatch based on conf +from unittest.mock import patch +from scapy.config import conf +from scapy.consts import LINUX +from scapy.contrib.j1939 import J1939Socket, J1939SoftSocket +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets + +# Default / False: dispatches to J1939SoftSocket +with TestSocket(CAN) as s: + sock = J1939Socket(s, src_addr=0xF1) + assert isinstance(sock, J1939SoftSocket) + sock.close() + +cleanup_testsockets() + +# If configured after import, dispatches to NativeJ1939Socket (on Linux) +if LINUX: + orig = conf.contribs.get('J1939', {}).copy() + try: + conf.contribs.setdefault('J1939', {})['use-can-j1939-kernel-module'] = True + with patch("scapy.contrib.j1939.NativeJ1939Socket") as mock_native: + mock_native.return_value = "mock_native" + res = J1939Socket("vcan0") + assert res == "mock_native" + mock_native.assert_called_once() + finally: + conf.contribs['J1939'] = orig + +True + += J1939Socket – sr1 transmits correct CAN ID on underlying CAN socket +import struct +import threading +from scapy.contrib.j1939 import J1939, J1939Socket, can_id_to_j1939 +from scapy.layers.can import CAN +from test.testsocket import TestSocket, cleanup_testsockets + +with TestSocket(CAN) as s, TestSocket(CAN) as peer: + s.pair(peer) + with J1939Socket(s, src_addr=0xF1) as sock: + req_data = struct.pack("> 8) & 0xFF + +def test_sr1_single_frame(): + with TestSocket(CAN) as can_sock, TestSocket(CAN) as monitor: + can_sock.pair(monitor) + def responder(): + pkts = monitor.sniff(count=1, timeout=1.0) + if pkts: + resp_id = j1939_to_can_id(6, 0, 0, 0xFE, 0xCA, 0x10) + monitor.send(CAN(identifier=resp_id, flags='extended', data=b'\x00\x00\x11\x22\x33\x44')) + t = threading.Thread(target=responder) + t.start() + with J1939Socket(can_sock, src_addr=0xF9) as s: + req = J1939(pgn=0xEA00, dst=0x10) / J1939Request(req_pgn=0xFECA) + ans = s.sr1(req, timeout=1.0) + assert ans is not None + assert ans.pgn == 0xFECA + t.join(timeout=5) + cleanup_testsockets() + +def test_sr1_multi_packet_bam(): + with TestSocket(CAN) as can_sock, TestSocket(CAN) as monitor: + can_sock.pair(monitor) + def responder(): + pkts = monitor.sniff(count=1, timeout=1.0) + if pkts: + bam_id = j1939_to_can_id(7, 0, 0, J1939_TP_CM_PF, J1939_GLOBAL_ADDRESS, 0x10) + bam_d = bytes([J1939_TP_CTRL_BAM, 10, 0, 2, 0xFF]) + struct.pack('= 240) +p_pdu2 = J1939(priority=3, pgn=0xFECA, src=0x20) +assert p_pdu2.to_can_id() == j1939_to_can_id(3, 0, 0, 0xFE, 0xCA, 0x20) + += J1939 to_can() and from_can() round trip +from scapy.contrib.j1939 import J1939, J1939Request +from scapy.layers.can import CAN + +req = J1939(pgn=0xEA00, dst=0x20, src=0xF9, priority=6) / J1939Request(req_pgn=0xFECA) +can_pkt = req.to_can() +assert isinstance(can_pkt, CAN) +assert can_pkt.flags.extended +assert can_pkt.length == 3 +decoded_req = J1939.from_can(can_pkt) +assert decoded_req.pgn == 0xEA00 +assert decoded_req.dst == 0x20 +assert decoded_req.src == 0xF9 +assert decoded_req.priority == 6 +assert decoded_req[J1939Request].req_pgn == 0xFECA + +bcast = J1939(b'\x01\x02\x03\x04\x05\x06\x07\x08', pgn=0xFECA, src=0x20, priority=6) +can_bcast = bcast.to_can() +decoded_bcast = J1939.from_can(can_bcast) +assert decoded_bcast.pgn == 0xFECA +assert decoded_bcast.src == 0x20 +assert decoded_bcast.data == b'\x01\x02\x03\x04\x05\x06\x07\x08' + += J1939 mysummary and getfieldval +from scapy.contrib.j1939 import J1939, J1939Request +p = J1939(pgn=0xFECA, src=0x10, dst=0x20, priority=6) +assert "0x0FECA" in p.mysummary() +assert p.getfieldval("pgn") == 0xFECA +try: + p.getfieldval("unknown_field") + assert False, "Expected AttributeError" +except AttributeError: + pass + +req = J1939Request(req_pgn=0xFECA) +assert req.req_pgn == 0xFECA +assert req.getfieldval("req_pgn") == 0xFECA + += J1939.answers() nested payload matching +from scapy.packet import Packet +from scapy.fields import ByteField +from scapy.contrib.j1939 import J1939 + +class _SubReq(Packet): + name = "_SubReq" + fields_desc = [ByteField("val", 1)] + +class _SubResp(Packet): + name = "_SubResp" + fields_desc = [ByteField("val", 1)] + def answers(self, other): + return int(isinstance(other, _SubReq) and self.val == other.val) + +req_pkt = J1939(pgn=0xEF00, src=0x10, dst=0x20) / _SubReq(val=5) +resp_pkt = J1939(pgn=0xEF00, src=0x20, dst=0x10) / _SubResp(val=5) +assert resp_pkt.answers(req_pkt) == 1 + += J1939_TP_CM and J1939Ack answers() edge branches +import struct +from scapy.layers.can import CAN +from scapy.contrib.j1939 import ( + J1939, J1939Request, J1939Ack, J1939_TP_CM, + J1939_TP_CM_RTS, J1939_TP_CM_CTS, J1939_TP_CM_BAM, J1939_TP_CM_ABORT +) + +# J1939_TP_CM.do_dissect returns raw bytes unchanged +raw_cm = bytes([32, 20, 0, 3, 0xFF, 0xCA, 0xFE, 0x00]) +assert J1939_TP_CM().do_dissect(raw_cm) == raw_cm + +# J1939Request matching across J1939, RTS, BAM, and Ack +req_match = J1939(pgn=0xEA00) / J1939Request(req_pgn=0xFECA) +req_match_can = CAN() / J1939(pgn=0xEA00) / J1939Request(req_pgn=0xFECA) +req_match_bytes = J1939(struct.pack("