Example #1
0
 def _random_memory_addr_pkt(addr_len=None, size_len=None, size=None):
     # type: (Optional[int], Optional[int], Optional[int]) -> Packet
     pkt = UDS() / UDS_RMBA()  # type: Packet
     pkt.memorySizeLen = size_len or random.randint(1, 4)
     pkt.memoryAddressLen = addr_len or random.randint(1, 4)
     UDS_RMBARandomEnumerator.set_size(pkt, size or 4)
     UDS_RMBARandomEnumerator.set_addr(
         pkt, random.randint(
             0, (2 ** (8 * pkt.memoryAddressLen) - 1)) & 0xfffffff0)
     return pkt
Example #2
0
 def _random_memory_addr_pkt(addr_len=None):  # noqa: E501
     # type: (Optional[int]) -> Packet
     pkt = UDS() / UDS_RD()  # type: Packet
     pkt.dataFormatIdentifiers = random.randint(0, 16)
     pkt.memorySizeLen = random.randint(1, 4)
     pkt.memoryAddressLen = addr_len or random.randint(1, 4)
     UDS_RMBARandomEnumerator.set_size(pkt, 0x10)
     addr = random.randint(0, 2 ** (8 * pkt.memoryAddressLen) - 1) & \
         (0xffffffff << (4 * pkt.memoryAddressLen))
     UDS_RMBARandomEnumerator.set_addr(pkt, addr)
     return pkt
Example #3
0
    def get_key_pkt(seed, level=1):
        # type: (Packet, int) -> Optional[Packet]

        def key_function_int(s):
            # type: (int) -> int
            return 0xffffffff & ~s

        def key_function_short(s):
            # type: (int) -> int
            return 0xffff & ~s

        try:
            s = seed.securitySeed
        except AttributeError:
            return None

        fmt = None
        key_function = None  # Optional[Callable[[int], int]]

        if len(s) == 2:
            fmt = "H"
            key_function = key_function_short

        if len(s) == 4:
            fmt = "I"
            key_function = key_function_int

        if key_function is not None and fmt is not None:
            key = struct.pack(fmt, key_function(struct.unpack(fmt, s)[0]))
            return cast(
                Packet,
                UDS() / UDS_SA(securityAccessType=level + 1, securityKey=key))
        else:
            return None
Example #4
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     # Only generate services with unset positive response bit (0x40) as
     # default scan_range
     scan_range = kwargs.pop("scan_range",
                             (x for x in range(0x100) if not x & 0x40))
     return (UDS(service=x) for x in scan_range)
Example #5
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     control_type = kwargs.pop("scan_range", range(0x100))
     return cast(
         Iterable[Packet],
         UDS() / UDS_CC(controlType=control_type,
                        communicationType0=1,
                        communicationType2=15))
Example #6
0
    def _get_initial_requests(self, **kwargs):
        # type: (Any) -> Iterable[Packet]
        scan_range = kwargs.pop("scan_range", range(0x10000))
        rdbi_enumerator = kwargs.pop("rdbi_enumerator", None)

        if rdbi_enumerator is None:
            log_interactive.debug("[i] Use entire scan range")
            return (UDS() / UDS_WDBI(dataIdentifier=x) for x in scan_range)
        elif isinstance(rdbi_enumerator, UDS_RDBIEnumerator):
            log_interactive.debug("[i] Selective scan based on RDBI results")
            return (UDS() / UDS_WDBI(dataIdentifier=t.resp.dataIdentifier) /
                    Raw(load=bytes(t.resp)[3:])
                    for t in rdbi_enumerator.results_with_positive_response
                    if len(bytes(t.resp)) >= 3)
        else:
            raise Scapy_Exception("rdbi_enumerator has to be an instance "
                                  "of UDS_RDBIEnumerator")
Example #7
0
    def _get_initial_requests(self, **kwargs):
        # type: (Any) -> Iterable[Packet]
        type_list = kwargs.pop("type_list", [1, 2, 3])
        scan_range = kwargs.pop("scan_range", range(0x10000))

        return (
            UDS() /
            UDS_RC(routineControlType=rc_type, routineIdentifier=data_id)
            for rc_type, data_id in itertools.product(type_list, scan_range))
Example #8
0
    def enter(socket,  # type: _SocketUnion
              configuration,  # type: AutomotiveTestCaseExecutorConfiguration
              _  # type: Dict[str, Any]
              ):  # type: (...) -> bool
        if configuration.unittest:
            configuration["tps"] = None
            socket.sr1(UDS() / UDS_TP(), timeout=0.1, verbose=False)
            return True

        UDS_TPEnumerator.cleanup(socket, configuration)
        configuration["tps"] = UDS_TesterPresentSender(socket)
        configuration["tps"].start()
        return True
Example #9
0
    def _get_initial_requests(self, **kwargs):
        # type: (Any) -> Iterable[Packet]

        samples_per_block = {
            4: 29, 5: 22, 6: 19, 8: 11, 9: 11, 10: 13, 11: 14, 12: 31, 13: 4,
            14: 26, 16: 30, 17: 4, 18: 20, 19: 5, 20: 49, 21: 54, 22: 9, 23: 4,
            24: 10, 25: 8, 28: 6, 29: 3, 32: 11, 36: 4, 37: 3, 40: 9, 41: 9,
            42: 3, 44: 2, 47: 3, 48: 4, 49: 3, 52: 8, 64: 35, 66: 2, 68: 24,
            69: 19, 70: 30, 71: 28, 72: 16, 73: 4, 74: 6, 75: 27, 76: 41,
            77: 11, 78: 6, 81: 2, 88: 3, 90: 2, 92: 16, 97: 15, 98: 20, 100: 6,
            101: 5, 102: 5, 103: 10, 106: 10, 108: 4, 124: 3, 128: 7, 136: 15,
            137: 14, 138: 27, 139: 10, 148: 9, 150: 2, 152: 2, 168: 23,
            169: 15, 170: 16, 171: 16, 172: 2, 176: 3, 177: 4, 178: 2, 187: 2,
            232: 3, 235: 2, 240: 8, 252: 25, 256: 7, 257: 2, 287: 6, 290: 2,
            316: 2, 319: 3, 323: 3, 324: 19, 326: 2, 327: 2, 330: 4, 331: 10,
            332: 3, 334: 8, 338: 3, 832: 6, 833: 2, 900: 4, 956: 4, 958: 3,
            964: 12, 965: 13, 966: 34, 967: 3, 972: 10, 1000: 3, 1012: 23,
            1013: 14, 1014: 15
        }
        to_scan = []
        block_size = UDS_RDBIRandomEnumerator.block_size

        probe_start = kwargs.pop("probe_start", 0)
        probe_end = kwargs.pop("probe_end", 0x10000)
        probe_range = range(probe_start, probe_end, block_size)

        for block_index, start in enumerate(probe_range):
            end = start + block_size
            count_samples = samples_per_block.get(block_index, 1)
            to_scan += random.sample(range(start, end), count_samples)

        # Use locality effect
        # If an identifier brought a positive response in any state,
        # it is likely that in another state it is available as well
        positive_identifiers = [t.resp.dataIdentifier for t in
                                self.results_with_positive_response]
        to_scan += positive_identifiers

        # make all identifiers unique with set()
        # Sort for better logs
        to_scan = sorted(list(set(to_scan)))
        return (UDS() / UDS_RDBI(identifiers=[x]) for x in to_scan)
Example #10
0
    def get_seed_pkt(sock, level=1, record=b""):
        # type: (_SocketUnion, int, bytes) -> Optional[Packet]
        req = UDS() / UDS_SA(securityAccessType=level,
                             securityAccessDataRecord=record)
        for _ in range(10):
            seed = sock.sr1(req, timeout=5, verbose=False)
            if seed is None:
                return None
            elif seed.service == 0x7f and \
                    UDS_Enumerator._get_negative_response_code(seed) != 0x37:
                log_interactive.info("Security access no seed! NR: %s",
                                     repr(seed))
                return None

            elif seed.service == 0x7f and seed.negativeResponseCode == 0x37:
                log_interactive.info("Security access retry to get seed")
                time.sleep(10)
                continue
            else:
                return seed
        return None
Example #11
0
    def __pois_to_requests(self, pois):
        # type: (List[_PointOfInterest]) -> List[Packet]
        tested_addrs = self._get_memory_addresses_from_results(
            self.results_with_response)
        testing_addrs = set()
        new_requests = list()

        for addr, upward, mem_size_len, mem_addr_len, mem_size in pois:
            for i in range(0, mem_size * 50, mem_size):
                if upward:
                    addr = min(addr + i, 2**(8 * mem_addr_len) - 1)
                else:
                    addr = max(addr - i, 0)

                if addr not in tested_addrs and \
                        (addr, mem_size) not in testing_addrs:
                    pkt = UDS() / UDS_RMBA(memorySizeLen=mem_size_len,
                                           memoryAddressLen=mem_addr_len)
                    self.set_size(pkt, mem_size)
                    self.set_addr(pkt, addr)
                    new_requests.append(pkt)
                    testing_addrs.add((addr, mem_size))

        return new_requests
Example #12
0
def hsfz_scan(
        ip,  # type: str
        scan_range=range(0x100),  # type: Iterable[int]
        src=0xf4,  # type: int
        timeout=0.1,  # type: Union[int, float]
        verbose=True  # type: bool
):
    # type: (...) -> List[UDS_HSFZSocket]
    """
    Helper function to scan for HSFZ endpoints.

    Example:
        >>> sockets = hsfz_scan("192.168.0.42")

    :param ip: IPv4 address of target to scan
    :param scan_range: Range for HSFZ destination address
    :param src: HSFZ source address, used during the scan
    :param timeout: Timeout for each request
    :param verbose: Show information during scan, if True
    :return: A list of open UDS_HSFZSockets
    """
    results = list()
    for i in scan_range:
        with UDS_HSFZSocket(src, i, ip) as sock:
            try:
                resp = sock.sr1(UDS() / UDS_TP(),
                                timeout=timeout,
                                verbose=False)
                if resp:
                    results.append((i, resp))
                if resp and verbose:
                    print("Found endpoint %s, src=0x%x, dst=0x%x" %
                          (ip, src, i))
            except Exception as e:
                print("Error %s at destination address 0x%x" % (e, i))
    return [UDS_HSFZSocket(0xf4, dst, ip) for dst, _ in results]
Example #13
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     pdid = kwargs.pop("scan_range", range(0x100))
     return cast(
         Iterable[Packet],
         UDS() / UDS_RDBPI(transmissionMode=1, periodicDataIdentifier=pdid))
Example #14
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     scan_range = kwargs.pop("scan_range", range(0x10000))
     return (UDS() / UDS_IOCBI(dataIdentifier=x) for x in scan_range)
Example #15
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     session_range = kwargs.pop("scan_range", range(2, 0x100))
     return UDS() / UDS_DSC(diagnosticSessionType=session_range)
Example #16
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     cnt = kwargs.pop("scan_range", range(0x100))
     return cast(Iterable[Packet], UDS() / UDS_TD(blockSequenceCounter=cnt))
Example #17
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     return [UDS() / UDS_TP()]
Example #18
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     reset_type = kwargs.pop("scan_range", range(0x100))
     return cast(Iterable[Packet], UDS() / UDS_ER(resetType=reset_type))
Example #19
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     scan_range = kwargs.pop("scan_range", range(1, 256, 2))
     return (UDS() / UDS_SA(securityAccessType=x) for x in scan_range)
Example #20
0
 def _get_initial_requests(self, **kwargs):
     # type: (Any) -> Iterable[Packet]
     # Only generate services with unset positive response bit (0x40)
     return (UDS(service=x) for x in range(0x100) if not x & 0x40)