diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4dada1a99f0..061d1eabd53 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,6 +97,8 @@ To be precise, `scapy/layers` protocols should not be importing `scapy/contrib` protocols, whereas `scapy/contrib` protocols may import both `scapy/contrib` and `scapy/layers` protocols. +The detailed requirements are explained in [Design patterns](https://scapy.readthedocs.io/en/latest/build_dissect.html#design-patterns) on Scapy's doc. + ### Features Protocol-related features should be implemented within the same module diff --git a/doc/scapy/advanced_usage.rst b/doc/scapy/advanced_usage.rst index 4d1573efab0..7ab9c8cead2 100644 --- a/doc/scapy/advanced_usage.rst +++ b/doc/scapy/advanced_usage.rst @@ -906,7 +906,7 @@ To send data through it, the object must call its ``self._gen_data(msg)`` or ``s The Source should also (if possible), set ``self.is_exhausted`` to ``True`` when empty, to allow the clean stop of the ``PipeEngine``. If the source is infinite, it will need a force-stop (see PipeEngine below) -For instance, here is how CLIHighFeeder is implemented: +For instance, here is how CLIHighFeeder is implemented:: class CLIFeeder(CLIFeeder): def send(self, msg): @@ -937,7 +937,7 @@ A ``Drain`` object will receive data from the lower canal in its ``push`` method To send the data back into the next linked Drain / Sink, it must call the ``self._send(msg)`` or ``self._high_send(msg)`` methods. -For instance, here is how TransformDrain is implemented: +For instance, here is how TransformDrain is implemented:: class TransformDrain(Drain): def __init__(self, f, name=None): @@ -969,7 +969,7 @@ A ``Sink`` class receives data like a ``Drain``, from the lower canal in its ``p A ``Sink`` is the dead end of data, it won't be sent anywhere after it. -For instance, here is how ConsoleSink is implemented: +For instance, here is how ConsoleSink is implemented:: class ConsoleSink(Sink): def push(self, msg): @@ -982,7 +982,7 @@ Link objects As shown in the example, most sources can be linked to any drain, on both lower and higher canals. -The use of `>` indicates a link on the low canal, and `>>` on the higher one. +The use of ``>`` indicates a link on the low canal, and ``>>`` on the higher one. For instance @@ -1072,1390 +1072,3 @@ Several triggering Drains exist, they are pretty explicit. It is highly recommen - TriggeredValve : Let messages alternatively pass or not, changing on trigger - TriggeredQueueingValve : Let messages alternatively pass or queued, changing on trigger - TriggeredSwitch : Let messages alternatively high or low, changing on trigger - -PROFINET IO RTC -=============== - -PROFINET IO is an industrial protocol composed of different layers such as the Real-Time Cyclic (RTC) layer, used to exchange data. However, this RTC layer is stateful and depends on a configuration sent through another layer: the DCE/RPC endpoint of PROFINET. This configuration defines where each exchanged piece of data must be located in the RTC ``data`` buffer, as well as the length of this same buffer. Building such packet is then a bit more complicated than other protocols. - -RTC data packet ---------------- - -The first thing to do when building the RTC ``data`` buffer is to instantiate each Scapy packet which represents a piece of data. Each one of them may require some specific piece of configuration, such as its length. All packets and their configuration are: - -* ``PNIORealTimeRawData``: a simple raw data like ``Raw`` - - * ``length``: defines the length of the data - -* ``Profisafe``: the PROFIsafe profile to perform functional safety - - * ``length``: defines the length of the whole packet - * ``CRC``: defines the length of the CRC, either ``3`` or ``4`` - -* ``PNIORealTimeIOxS``: either an IO Consumer or Provider Status byte - - * Doesn't require any configuration - -To instantiate one of these packets with its configuration, the ``config`` argument must be given. It is a ``dict()`` which contains all the required piece of configuration:: - - >>> load_contrib('pnio_rtc') - >>> raw(PNIORealTimeRawData(load='AAA', config={'length': 4})) - 'AAA\x00' - >>> raw(Profisafe(load='AAA', Control_Status=0x20, CRC=0x424242, config={'length': 8, 'CRC': 3})) - 'AAA\x00 BBB' - >>> hexdump(PNIORealTimeIOxS()) - 0000 80 . - - -RTC packet ----------- - -Now that a data packet can be instantiated, a whole RTC packet may be built. ``PNIORealTime`` contains a field ``data`` which is a list of all data packets to add in the buffer, however, without the configuration, Scapy won't be -able to dissect it:: - - >>> load_contrib("pnio_rtc") - >>> p=PNIORealTime(cycleCounter=1024, data=[ - ... PNIORealTimeIOxS(), - ... PNIORealTimeRawData(load='AAA', config={'length':4}) / PNIORealTimeIOxS(), - ... Profisafe(load='AAA', Control_Status=0x20, CRC=0x424242, config={'length': 8, 'CRC': 3}) / PNIORealTimeIOxS(), - ... ]) - >>> p.show() - ###[ PROFINET Real-Time ]### - len= None - dataLen= None - \data\ - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0 - | extension= 0 - |###[ PNIO RTC Raw data ]### - | load= 'AAA' - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0 - | extension= 0 - |###[ PROFISafe ]### - | load= 'AAA' - | Control_Status= 0x20 - | CRC= 0x424242 - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0 - | extension= 0 - padding= '' - cycleCounter= 1024 - dataStatus= primary+validData+run+no_problem - transferStatus= 0 - - >>> p.show2() - ###[ PROFINET Real-Time ]### - len= 44 - dataLen= 15 - \data\ - |###[ PNIO RTC Raw data ]### - | load= '\x80AAA\x00\x80AAA\x00 BBB\x80' - padding= '' - cycleCounter= 1024 - dataStatus= primary+validData+run+no_problem - transferStatus= 0 - -For Scapy to be able to dissect it correctly, one must also configure the layer for it to know the location of each data in the buffer. This configuration is saved in the dictionary ``conf.contribs["PNIO_RTC"]`` which can be updated with the ``pnio_update_config`` method. Each item in the dictionary uses the tuple ``(Ether.src, Ether.dst)`` as key, to be able to separate the configuration of each communication. Each value is then a list of a tuple which describes a data packet. It is composed of the negative index, from the end of the data buffer, of the packet position, the class of the packet as the second item and the ``config`` dictionary to provide to the class as last. If we continue the previous example, here is the configuration to set:: - - >>> load_contrib("pnio") - >>> e=Ether(src='00:01:02:03:04:05', dst='06:07:08:09:0a:0b') / ProfinetIO() / p - >>> e.show2() - ###[ Ethernet ]### - dst= 06:07:08:09:0a:0b - src= 00:01:02:03:04:05 - type= 0x8892 - ###[ ProfinetIO ]### - frameID= RT_CLASS_1 - ###[ PROFINET Real-Time ]### - len= 44 - dataLen= 15 - \data\ - |###[ PNIO RTC Raw data ]### - | load= '\x80AAA\x00\x80AAA\x00 BBB\x80' - padding= '' - cycleCounter= 1024 - dataStatus= primary+validData+run+no_problem - transferStatus= 0 - >>> pnio_update_config({('00:01:02:03:04:05', '06:07:08:09:0a:0b'): [ - ... (-9, Profisafe, {'length': 8, 'CRC': 3}), - ... (-9 - 5, PNIORealTimeRawData, {'length':4}), - ... ]}) - >>> e.show2() - ###[ Ethernet ]### - dst= 06:07:08:09:0a:0b - src= 00:01:02:03:04:05 - type= 0x8892 - ###[ ProfinetIO ]### - frameID= RT_CLASS_1 - ###[ PROFINET Real-Time ]### - len= 44 - dataLen= 15 - \data\ - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - |###[ PNIO RTC Raw data ]### - | load= 'AAA' - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - |###[ PROFISafe ]### - | load= 'AAA' - | Control_Status= 0x20 - | CRC= 0x424242L - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - padding= '' - cycleCounter= 1024 - dataStatus= primary+validData+run+no_problem - transferStatus= 0 - -If no data packets are configured for a given offset, it defaults to a ``PNIORealTimeIOxS``. However, this method is not very convenient for the user to configure the layer and it only affects the dissection of packets. In such cases, one may have access to several RTC packets, sniffed or retrieved from a PCAP file. Thus, ``PNIORealTime`` provides some methods to analyse a list of ``PNIORealTime`` packets and locate all data in it, based on simple heuristics. All of them take as first argument an iterable which contains the list of packets to analyse. - -* ``PNIORealTime.find_data()`` analyses the data buffer and separate real data from IOxS. It returns a dict which can be provided to ``pnio_update_config``. -* ``PNIORealTime.find_profisafe()`` analyses the data buffer and find the PROFIsafe profiles among the real data. It returns a dict which can be provided to ``pnio_update_config``. -* ``PNIORealTime.analyse_data()`` executes both previous methods and update the configuration. **This is usually the method to call.** -* ``PNIORealTime.draw_entropy()`` will draw the entropy of each byte in the data buffer. It can be used to easily visualize PROFIsafe locations as entropy is the base of the decision algorithm of ``find_profisafe``. - -:: - - >>> load_contrib('pnio_rtc') - >>> t=rdpcap('/path/to/trace.pcap', 1024) - >>> PNIORealTime.analyse_data(t) - {('00:01:02:03:04:05', '06:07:08:09:0a:0b'): [(-19, , {'length': 1}), (-15, , {'CRC': 3, 'length': 6}), (-7, , {'CRC': 3, 'length': 5})]} - >>> t[100].show() - ###[ Ethernet ]### - dst= 06:07:08:09:0a:0b - src= 00:01:02:03:04:05 - type= n_802_1Q - ###[ 802.1Q ]### - prio= 6L - id= 0L - vlan= 0L - type= 0x8892 - ###[ ProfinetIO ]### - frameID= RT_CLASS_1 - ###[ PROFINET Real-Time ]### - len= 44 - dataLen= 22 - \data\ - |###[ PNIO RTC Raw data ]### - | load= '\x80\x80\x80\x80\x80\x80\x00\x80\x80\x80\x12:\x0e\x12\x80\x80\x00\x12\x8b\x97\xe3\x80' - padding= '' - cycleCounter= 6208 - dataStatus= primary+validData+run+no_problem - transferStatus= 0 - - >>> t[100].show2() - ###[ Ethernet ]### - dst= 06:07:08:09:0a:0b - src= 00:01:02:03:04:05 - type= n_802_1Q - ###[ 802.1Q ]### - prio= 6L - id= 0L - vlan= 0L - type= 0x8892 - ###[ ProfinetIO ]### - frameID= RT_CLASS_1 - ###[ PROFINET Real-Time ]### - len= 44 - dataLen= 22 - \data\ - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - [...] - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - |###[ PNIO RTC Raw data ]### - | load= '' - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - [...] - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - |###[ PROFISafe ]### - | load= '' - | Control_Status= 0x12 - | CRC= 0x3a0e12L - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - |###[ PROFISafe ]### - | load= '' - | Control_Status= 0x12 - | CRC= 0x8b97e3L - |###[ PNIO RTC IOxS ]### - | dataState= good - | instance= subslot - | reserved= 0x0L - | extension= 0L - padding= '' - cycleCounter= 6208 - dataStatus= primary+validData+run+no_problem - transferStatus= 0 - -In addition, one can see, when displaying a ``PNIORealTime`` packet, the field ``len``. This is a computed field which is not added in the final packet build. It is mainly useful for dissection and reconstruction, but it can also be used to modify the behaviour of the packet. In fact, RTC packet must always be long enough for an Ethernet frame and to do so, a padding must be added right after the ``data`` buffer. The default behaviour is to add ``padding`` whose size is computed during the ``build`` process:: - - >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()])) - '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' - -However, one can set ``len`` to modify this behaviour. ``len`` controls the length of the whole ``PNIORealTime`` packet. Then, to shorten the length of the padding, ``len`` can be set to a lower value:: - - >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()], len=50)) - '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' - >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()])) - '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' - >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()], len=30)) - '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' - - -SCTP -==== - -SCTP is a relatively young transport-layer protocol combining both TCP and UDP characteristics. The `RFC 3286 `_ introduces it and its description lays in the `RFC 4960 `_. - -It is not broadly used, its mainly present in core networks operated by telecommunication companies, to support VoIP for instance. - - -Enabling dynamic addressing reconfiguration and chunk authentication capabilities ---------------------------------------------------------------------------------- - -If you are trying to discuss with SCTP servers, you may be interested in capabilities added in `RFC 4895 `_ which describe how to authenticated some SCTP chunks, and/or `RFC 5061 `_ to dynamically reconfigure the IP address of a SCTP association. - -These capabilities are not always enabled by default on Linux. Scapy does not need any modification on its end, but SCTP servers may need specific activation. - -To enable the RFC 4895 about authenticating chunks:: - - $ sudo echo 1 > /proc/sys/net/sctp/auth_enable - -To enable the RFC 5061 about dynamic address reconfiguration:: - - $ sudo echo 1 > /proc/sys/net/sctp/addip_enable - -You may also want to use the dynamic address reconfiguration without necessarily enabling the chunk authentication:: - - $ sudo echo 1 > /proc/sys/net/sctp/addip_noauth_enable - - -Automotive Penetration Testing with Scapy -========================================= - -.. note:: - All automotive related features work best on Linux systems. CANSockets and ISOTPSockets in Scapy are based on Linux kernel modules. - The python-can project is used to support CAN and CANSockets on other systems, besides Linux. - This guide explains the hardware setup on a BeagleBone Black. The BeagleBone Black was chosen because of its two CAN interfaces on the main processor. - The presence of two CAN interfaces in one device gives the possibility of CAN MITM attacks and session hijacking. - The Cannelloni framework turns a BeagleBone Black into a CAN-to-UDP interface, which gives you the freedom to run Scapy - on a more powerful machine. - -Protocols ---------- - -The following table should give a brief overview about all automotive capabilities -of Scapy. Most application layer protocols have many specialized ``Packet`` classes. -These special purpose classes are not part of this overview. Use the ``explore()`` -function to get all information about one specific protocol. - -+---------------------+----------------------+--------------------------------------------------------+ -| OSI Layer | Protocol | Scapy Implementations | -+=====================+======================+========================================================+ -| Application Layer | UDS (ISO 14229) | UDS, UDS_* | -| +----------------------+--------------------------------------------------------+ -| | GMLAN | GMLAN, GMLAN_* | -| +----------------------+--------------------------------------------------------+ -| | SOME/IP | SOMEIP, SD | -| +----------------------+--------------------------------------------------------+ -| | BMW ENET | ENET, ENETSocket | -| +----------------------+--------------------------------------------------------+ -| | OBD | OBD, OBD_S0X | -| +----------------------+--------------------------------------------------------+ -| | CCP | CCP, DTO, CRO | -+---------------------+----------------------+--------------------------------------------------------+ -| Transportaion Layer | ISO-TP (ISO 15765-2) | ISOTPSocket, ISOTPNativeSocket, ISOTPSoftSocket | -| | | | -| | | ISOTPSniffer, ISOTPMessageBuilder | -| | | | -| | | ISOTPHeader, ISOTPHeaderEA, | -| | | | -| | | ISOTP, ISOTP_SF, ISOTP_FF, ISOTP_CF, ISOTP_FC | -+---------------------+----------------------+--------------------------------------------------------+ -| Data Link Layer | CAN (ISO 11898) | CAN, CANSocket, rdcandump | -+---------------------+----------------------+--------------------------------------------------------+ - - -Hands-On -^^^^^^^^ - -Send a message over Linux SocketCAN:: - - load_layer('can') - load_contrib('cansocket') - socket = CANSocket(iface='can0') - packet = CAN(identifier=0x123, data=b'01020304') - - socket.sr1(packet, timeout=1) - - srcan(packet, 'can0', timeout=1) - -Send a message over a Vector CAN-Interface:: - - import can - load_layer('can') - conf.contribs['CANSocket'] = {'use-python-can' : True} - load_contrib('cansocket') - from can.interfaces.vector import VectorBus - socket = CANSocket(iface=VectorBus(0, bitrate=1000000)) - packet = CAN(identifier=0x123, data=b'01020304') - socket.sr1(packet) - - srcan(packet, VectorBus(0, bitrate=1000000)) - -System compatibilities ----------------------- - -Dependent on your setup, different implementations have to be used. - -+---------------------+----------------------+-------------------------------------+----------------------------------------------------------+ -| Python \ OS | Linux with can_isotp | Linux wo can_isotp | Windows / OSX | -+=====================+======================+=====================================+==========================================================+ -| Python 3 | ISOTPNativeSocket | ISOTPSoftSocket | ISOTPSoftSocket | -| +----------------------+-------------------------------------+ | -| | ``conf.contribs['CANSocket'] = {'use-python-can': False}`` | ``conf.contribs['CANSocket'] = {'use-python-can': True}``| -+---------------------+------------------------------------------------------------+----------------------------------------------------------+ -| Python 2 | ISOTPSoftSocket | ISOTPSoftSocket | -| | | | -| | ``conf.contribs['CANSocket'] = {'use-python-can': True}`` | ``conf.contribs['CANSocket'] = {'use-python-can': True}``| -+---------------------+------------------------------------------------------------+----------------------------------------------------------+ - -The class ``ISOTPSocket`` can be set to a ``ISOTPNativeSocket`` or a ``ISOTPSoftSocket``. -The decision is made dependent on the configuration ``conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': True}`` (to select ``ISOTPNativeSocket``) or -``conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': False}`` (to select ``ISOTPSoftSocket``). -This will allow you to write platform independent code. Apply this configuration before loading the ISOTP layer -with ``load_contrib("isotp")``. - -Another remark in respect to ISOTPSocket compatibility. Always use with for socket creation. Example:: - - with ISOTPSocket("vcan0", did=0x241, sid=0x641) as sock: - sock.send(...) - - -CAN Layer ---------- - -Setup -^^^^^ - -These commands enable a virtual CAN interface on a Linux machine:: - - from scapy.layers.can import * - import os - - bashCommand = "/bin/bash -c 'sudo modprobe vcan; sudo ip link add name vcan0 type vcan; sudo ip link set dev vcan0 up'" - os.system(bashCommand) - -If it's required, the CAN interface can be set into a ``listen-only`` or ``loopback`` mode with `ip link set` commands:: - - ip link set vcan0 type can help # shows additional information - - -This example shows a basic functions of Linux can-utils. These utilities are handy for -quick checks or logging. - -.. image:: graphics/animations/animation-cansend.svg - -CAN Frame -^^^^^^^^^ - -Creating a standard CAN frame:: - - frame = CAN(identifier=0x200, length=8, data=b'\x01\x02\x03\x04\x05\x06\x07\x08') - -Creating an extended CAN frame:: - - frame = CAN(flags='extended', identifier=0x10010000, length=8, data=b'\x01\x02\x03\x04\x05\x06\x07\x08') - -.. image:: graphics/animations/animation-scapy-canframe.svg - -Writing and reading to pcap files:: - - x = CAN(identifier=0x7ff,length=8,data=b'\x01\x02\x03\x04\x05\x06\x07\x08') - wrpcap('/tmp/scapyPcapTest.pcap', x, append=False) - y = rdpcap('/tmp/scapyPcapTest.pcap', 1) - -.. image:: graphics/animations/animation-scapy-rdpcap.svg -.. image:: graphics/animations/animation-scapy-rdcandump.svg - -CANSocket native -^^^^^^^^^^^^^^^^ - -Creating a simple native CANSocket:: - - conf.contribs['CANSocket'] = {'use-python-can': False} #(default) - load_contrib('cansocket') - - # Simple Socket - socket = CANSocket(iface="vcan0") - -Creating a native CANSocket only listen for messages with Id == 0x200:: - - socket = CANSocket(iface="vcan0", can_filters=[{'can_id': 0x200, 'can_mask': 0x7FF}]) - -Creating a native CANSocket only listen for messages with Id >= 0x200 and Id <= 0x2ff:: - - socket = CANSocket(iface="vcan0", can_filters=[{'can_id': 0x200, 'can_mask': 0x700}]) - -Creating a native CANSocket only listen for messages with Id != 0x200:: - - socket = CANSocket(iface="vcan0", can_filters=[{'can_id': 0x200 | CAN_INV_FILTER, 'can_mask': 0x7FF}]) - -Creating a native CANSocket with multiple can_filters:: - - socket = CANSocket(iface='vcan0', can_filters=[{'can_id': 0x200, 'can_mask': 0x7ff}, - {'can_id': 0x400, 'can_mask': 0x7ff}, - {'can_id': 0x600, 'can_mask': 0x7ff}, - {'can_id': 0x7ff, 'can_mask': 0x7ff}]) - -Creating a native CANSocket which also receives its own messages:: - - socket = CANSocket(iface="vcan0", receive_own_messages=True) - -.. image:: graphics/animations/animation-scapy-native-cansocket.svg - -Sniff on a CANSocket: - -.. image:: graphics/animations/animation-scapy-cansockets-sniff.svg - - -CANSocket python-can -^^^^^^^^^^^^^^^^^^^^ - -python-can is required to use various CAN-interfaces on Windows, OSX or Linux. -The python-can library is used through a CANSocket object. To create a python-can -CANSocket object, a python-can ``Bus`` object has to be used as interface. -The ``timeout`` parameter can be used to increase the receive performance of a -python-can CANSocket object. ``recv`` inside a python-can CANSocket object is -implemented through busy wait, since there is no ``select`` functionality on -Windows or on some proprietary CAN interfaces (like Vector interfaces). A small -``timeout`` might be required, if a ``sniff`` or ``bridge_and_sniff`` on multiple -interfaces is performed. - -Ways of creating a python-can CANSocket:: - - conf.contribs['CANSocket'] = {'use-python-can': True} - load_contrib('cansocket') - import can - -Creating a simple python-can CANSocket:: - - socket = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)) - -Creating a python-can CANSocket with multiple filters:: - - socket = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000, - can_filters=[{'can_id': 0x200, 'can_mask': 0x7ff}, - {'can_id': 0x400, 'can_mask': 0x7ff}, - {'can_id': 0x600, 'can_mask': 0x7ff}, - {'can_id': 0x7ff, 'can_mask': 0x7ff}])) - -.. image:: graphics/animations/animation-scapy-python-can-cansocket.svg - -For further details on python-can check: https://python-can.readthedocs.io/en/2.2.0/ - -CANSocket MITM attack with bridge and sniff -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -This example shows how to use bridge and sniff on virtual CAN interfaces. -For real world applications, use real CAN interfaces. -Set up two vcans on Linux terminal:: - - sudo modprobe vcan - sudo ip link add name vcan0 type vcan - sudo ip link add name vcan1 type vcan - sudo ip link set dev vcan0 up - sudo ip link set dev vcan1 up - -Import modules:: - - import threading - load_contrib('cansocket') - load_layer("can") - -Create can sockets for attack:: - - socket0 = CANSocket(iface='vcan0') - socket1 = CANSocket(iface='vcan1') - -Create a function to send packet with threading:: - - def sendPacket(): - sleep(0.2) - socket0.send(CAN(flags='extended', identifier=0x10010000, length=8, data=b'\x01\x02\x03\x04\x05\x06\x07\x08')) - -Create a function for forwarding or change packets:: - - def forwarding(pkt): - return pkt - -Create a function to bridge and sniff between two sockets:: - - def bridge(): - bSocket0 = CANSocket(iface='vcan0') - bSocket1 = CANSocket(iface='vcan1') - bridge_and_sniff(if1=bSocket0, if2=bSocket1, xfrm12=forwarding, xfrm21=forwarding, timeout=1) - bSocket0.close() - bSocket1.close() - -Create threads for sending packet and to bridge and sniff:: - - threadBridge = threading.Thread(target=bridge) - threadSender = threading.Thread(target=sendMessage) - -Start the threads:: - - threadBridge.start() - threadSender.start() - -Sniff packets:: - - packets = socket1.sniff(timeout=0.3) - -Close the sockets:: - - socket0.close() - socket1.close() - -.. image:: graphics/animations/animation-scapy-cansockets-mitm.svg -.. image:: graphics/animations/animation-scapy-cansockets-mitm2.svg - - -CAN Calibration Protocol (CCP) ------------------------------- - -CCP is derived from CAN. The CAN-header is part of a CCP frame. CCP has two types -of message objects. One is called Command Receive Object (CRO), the other is called -Data Transmission Object (DTO). Usually CROs are sent to an ECU, and DTOs are received -from an ECU. The information, if one DTO answers a CRO is implemented through a counter -field (ctr). If both objects have the same counter value, the payload of a DTO object -can be interpreted from the command of the associated CRO object. - -Creating a CRO message:: - - CCP(identifier=0x700)/CRO(ctr=1)/CONNECT(station_address=0x02) - CCP(identifier=0x711)/CRO(ctr=2)/GET_SEED(resource=2) - CCP(identifier=0x711)/CRO(ctr=3)/UNLOCK(key=b"123456") - -If we aren't interested in the DTO of an ECU, we can just send a CRO message like this: -Sending a CRO message:: - - pkt = CCP(identifier=0x700)/CRO(ctr=1)/CONNECT(station_address=0x02) - sock = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)) - sock.send(pkt) - -If we are interested in the DTO of an ECU, we need to set the basecls parameter of the -CANSocket to CCP and we need to use sr1: -Sending a CRO message:: - - cro = CCP(identifier=0x700)/CRO(ctr=0x53)/PROGRAM_6(data=b"\x10\x11\x12\x10\x11\x12") - sock = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000), basecls=CCP) - dto = sock.sr1(cro) - dto.show() - ###[ CAN Calibration Protocol ]### - flags= - identifier= 0x700 - length= 8 - reserved= 0 - ###[ DTO ]### - packet_id= 0xff - return_code= acknowledge / no error - ctr= 83 - ###[ PROGRAM_6_DTO ]### - MTA0_extension= 2 - MTA0_address= 0x34002006 - -Since sr1 calls the answers function, our payload of the DTO objects gets interpreted with the -command of our CRO object. - -ISOTP ------ - -ISOTP message -^^^^^^^^^^^^^ - -Creating an ISOTP message:: - - load_contrib('isotp') - ISOTP(src=0x241, dst=0x641, data=b"\x3eabc") - -Creating an ISOTP message with extended addressing:: - - ISOTP(src=0x241, dst=0x641, exdst=0x41, data=b"\x3eabc") - -Creating an ISOTP message with extended addressing:: - - ISOTP(src=0x241, dst=0x641, exdst=0x41, exsrc=0x41, data=b"\x3eabc") - -Create CAN-frames from an ISOTP message:: - - ISOTP(src=0x241, dst=0x641, exdst=0x41, exsrc=0x55, data=b"\x3eabc" * 10).fragment() - -Send ISOTP message over ISOTP socket:: - - isoTpSocket = ISOTPSocket('vcan0', sid=0x241, did=0x641) - isoTpMessage = ISOTP('Message') - isoTpSocket.send(isoTpMessage) - -Sniff ISOTP message:: - - isoTpSocket = ISOTPSocket('vcan0', sid=0x641, did=0x241) - packets = isoTpSocket.sniff(timeout=0.5) - -ISOTP MITM attack with bridge and sniff -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Set up two vcans on Linux terminal:: - - sudo modprobe vcan - sudo ip link add name vcan0 type vcan - sudo ip link add name vcan1 type vcan - sudo ip link set dev vcan0 up - sudo ip link set dev vcan1 up - -Set up ISOTP:: - -.. note:: - - First make sure you build an iso-tp kernel module. - -When the vcan core module is loaded with "sudo modprobe vcan" the iso-tp module can be loaded to the kernel. - -Therefore navigate to isotp directory, and load module with "sudo insmod ./net/can/can-isotp.ko". (Tested on Kernel 4.9.135-1-MANJARO) - -Detailed instructions you find in https://github.com/hartkopp/can-isotp. - -Import modules:: - - import threading - load_contrib('cansocket') - conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': True} - load_contrib('isotp') - -Create to ISOTP sockets for attack:: - - isoTpSocketVCan0 = ISOTPSocket('vcan0', sid=0x241, did=0x641) - isoTpSocketVCan1 = ISOTPSocket('vcan1', sid=0x641, did=0x241) - -Create function to send packet on vcan0 with threading:: - - def sendPacketWithISOTPSocket(): - sleep(0.2) - packet = ISOTP('Request') - isoTpSocketVCan0.send(packet) - -Create function to forward packet:: - - def forwarding(pkt): - return pkt - -Create function to bridge and sniff between two buses:: - - def bridge(): - bSocket0 = ISOTPSocket('vcan0', sid=0x641, did=0x241) - bSocket1 = ISOTPSocket('vcan1', sid=0x241, did=0x641) - bridge_and_sniff(if1=bSocket0, if2=bSocket1, xfrm12=forwarding, xfrm21=forwarding, timeout=1) - bSocket0.close() - bSocket1.close() - -Create threads for sending packet and to bridge and sniff:: - - threadBridge = threading.Thread(target=bridge) - threadSender = threading.Thread(target=sendPacketWithISOTPSocket) - -Start threads are based on Linux kernel modules. The python-can project is used to support CAN and CANSockets on other systems, besides Linux. This guide explains the hardware setup on a BeagleBone Black. The BeagleBone Black was chosen because of its two CAN interfaces on the main processor. The presence of two CAN interfaces in one device gives the possibility of CAN MITM attacks and session hijacking. The Cannelloni framework turns a BeagleBone Black into a CAN-to-UDP interface, which gives you the freedom to run Scapy on a more powerful machine.:: - - threadBridge.start() - threadSender.start() - -Sniff on vcan1:: - - receive = isoTpSocketVCan1.sniff(timeout=1) - -Close sockets:: - - isoTpSocketVCan0.close() - isoTpSocketVCan1.close() - -An ISOTPSocket will not respect ``src, dst, exdst, exsrc`` of an ISOTP message object. - -ISOTP Sockets -------------- - -Scapy provides two kinds of ISOTP Sockets. One implementation, the ISOTPNativeSocket -is using the Linux kernel module from Hartkopp. The other implementation, the ISOTPSoftSocket -is completely implemented in Python. This implementation can be used on Linux, -Windows, and OSX. - -ISOTPNativeSocket -^^^^^^^^^^^^^^^^^ - -**Requires:** - -* Python3 -* Linux -* Hartkopp's Linux kernel module: ``https://github.com/hartkopp/can-isotp.git`` - -During pentests, the ISOTPNativeSockets do have a better performance and -reliability, usually. If you are working on Linux, consider this implementation:: - - conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': True} - load_contrib('isotp') - sock = ISOTPSocket("can0", sid=0x641, did=0x241) - -Since this implementation is using a standard Linux socket, all Scapy functions -like ``sniff, sr, sr1, bridge_and_sniff`` work out of the box. - -ISOTPSoftSocket -^^^^^^^^^^^^^^^ - -ISOTPSoftSockets can use any CANSocket. This gives the flexibility to use all -python-can interfaces. Additionally, these sockets work on Python2 and Python3. -Usage on Linux with native CANSockets:: - - conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': False} - load_contrib('isotp') - with ISOTPSocket("can0", sid=0x641, did=0x241) as sock: - sock.send(...) - -Usage with python-can CANSockets:: - - conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': False} - conf.contribs['CANSocket'] = {'use-python-can': True} - load_contrib('isotp') - with ISOTPSocket(CANSocket(iface=python_can.interface.Bus(bustype='socketcan', channel="can0", bitrate=250000)), sid=0x641, did=0x241) as sock: - sock.send(...) - -This second example allows the usage of any ``python_can.interface`` object. - -**Attention:** The internal implementation of ISOTPSoftSockets requires a background -thread. In order to be able to close this thread properly, we suggest the use of -Pythons ``with`` statement. - - -UDS ---- - -The main usage of UDS is flashing and diagnostic of an ECU. UDS is an -application layer protocol and can be used as a DoIP or ENET payload or a UDS packet -can directly be sent over an ISOTPSocket. Every OEM has its own customization of UDS. -This increases the difficulty of generic applications and OEM specific knowledge is -required for penetration tests. RoutineControl jobs and ReadDataByIdentifier/WriteDataByIdentifier -services are heavily customized. - -Use the argument ``basecls=UDS`` on the ``init`` function of an ISOTPSocket. - -Here are two usage examples: - -.. image:: graphics/animations/animation-scapy-uds.svg -.. image:: graphics/animations/animation-scapy-uds2.svg - - -Customization of UDS_RDBI, UDS_WDBI -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -In real-world use-cases, the UDS layer is heavily customized. OEMs define there own substructure of packets. -Especially the packets ReadDataByIdentifier or WriteDataByIdentifier have a very OEM or even ECU specific -substructure. Therefore a ``StrField`` ``dataRecord`` is not added to the ``field_desc``. -The intended usage is to create ECU or OEM specific description files, which extend the general UDS layer of -Scapy with further protocol implementations. - -Customization example:: - - cat scapy/contrib/automotive/OEM-XYZ/car-model-xyz.py - #! /usr/bin/env python - - # Protocol customization for car model xyz of OEM XYZ - # This file contains further OEM car model specific UDS additions. - - from scapy.packet import Packet - from scapy.contrib.automotive.uds import * - - # Define a new packet substructure - - class DBI_IP(Packet): - name = 'DataByIdentifier_IP_Packet' - fields_desc = [ - ByteField('ADDRESS_FORMAT_ID', 0), - IPField('IP', ''), - IPField('SUBNETMASK', ''), - IPField('DEFAULT_GATEWAY', '') - ] - - # Bind the new substructure onto the existing UDS packets - - bind_layers(UDS_RDBIPR, DBI_IP, dataIdentifier=0x172b) - bind_layers(UDS_WDBI, DBI_IP, dataIdentifier=0x172b) - - # Give add a nice name to dataIdentifiers enum - - UDS_RDBI.dataIdentifiers[0x172b] = 'GatewayIP' - -If one wants to work with this custom additions, these can be loaded at runtime to the Scapy interpreter:: - - >>> load_contrib("automotive.uds") - >>> load_contrib("automotive.OEM-XYZ.car-model-xyz") - - >>> pkt = UDS()/UDS_WDBI()/DBI_IP(IP='192.168.2.1', SUBNETMASK='255.255.255.0', DEFAULT_GATEWAY='192.168.2.1') - - >>> pkt.show() - ###[ UDS ]### - service= WriteDataByIdentifier - ###[ WriteDataByIdentifier ]### - dataIdentifier= GatewayIP - dataRecord= 0 - ###[ DataByIdentifier_IP_Packet ]### - ADDRESS_FORMAT_ID= 0 - IP= 192.168.2.1 - SUBNETMASK= 255.255.255.0 - DEFAULT_GATEWAY= 192.168.2.1 - - >>> hexdump(pkt) - 0000 2E 17 2B 00 C0 A8 02 01 FF FF FF 00 C0 A8 02 01 ..+............. - -.. image:: graphics/animations/animation-scapy-uds3.svg - -GMLAN ------ -GMLAN is very similar to UDS. It's GMs application layer protocol for -flashing, calibration and diagnostic of their cars. -Use the argument ``basecls=GMLAN`` on the ``init`` function of an ISOTPSocket. - -Usage example: - -.. image:: graphics/animations/animation-scapy-gmlan.svg - - -SOME/IP and SOME/IP SD messages -------------------------------- - -Creating a SOME/IP message -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -This example shows a SOME/IP message which requests a service 0x1234 with the method 0x421. Different types of SOME/IP messages follow the same procedure and their specifications can be seen here ``http://www.some-ip.com/papers/cache/AUTOSAR_TR_SomeIpExample_4.2.1.pdf``. - - -Load the contribution:: - - load_contrib("automotive.someip") - -Create UDP package:: - - u = UDP(sport=30509, dport=30509) - -Create IP package:: - - i = IP(src="192.168.0.13", dst="192.168.0.10") - -Create SOME/IP package:: - - sip = SOMEIP() - sip.iface_ver = 0 - sip.proto_ver = 1 - sip.msg_type = "REQUEST" - sip.retcode = "E_OK" - sip.msg_id.srv_id = 0x1234 - sip.msg_id.method_id = 0x421 - -Add the payload:: - - sip.add_payload(Raw ("Hello")) - -Stack it and send it:: - - p = i/u/sip - send(p) - - -Creating a SOME/IP SD message -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -In this example a SOME/IP SD offer service message is shown with an IPv4 endpoint. Different entries and options basically follow the same procedure as shown here and can be seen at ``https://www.autosar.org/fileadmin/user_upload/standards/classic/4-3/AUTOSAR_SWS_ServiceDiscovery.pdf``. - -Load the contribution:: - - load_contrib("automotive.someip_sd") - -Create UDP package:: - - u = UDP(sport=30490, dport=30490) - -The UDP port must be the one which was chosen for the SOME/IP SD transmission. - -Create IP package:: - - i = IP(src="192.168.0.13", dst="224.224.224.245") - -The IP source must be from the service and the destination address needs to be the chosen multicast address. - -Create the entry array input:: - - ea = SDEntry_Service() - - ea.type = 0x01 - ea.srv_id = 0x1234 - ea.inst_id = 0x5678 - ea.major_ver = 0x00 - ea.ttl = 3 - -Create the options array input:: - - oa = SDOption_IP4_Endpoint() - oa.addr = "192.168.0.13" - oa.l4_proto = 0x11 - oa.port = 30509 - -l4_proto defines the protocol for the communication with the endpoint, UDP in this case. - -Create the SD package and put in the inputs:: - - sd = SD() - sd.set_entryArray(ea) - sd.set_optionArray(oa) - spsd = sd.get_someip(True) - -The get_someip method stacks the SOMEIP/SD message on top of a SOME/IP message, which has the desired SOME/IP values prefilled for the SOME/IP SD package transmission. - -Stack it and send it:: - - p = i/u/spsd - send(p) - - - - -OBD message -------------- - -OBD is implemented on top of ISOTP. Use an ISOTPSocket for the communication with a ECU. -You should set the parameters ``basecls=OBD`` and ``padding=True`` in your ISOTPSocket init call. - -OBD is split into different service groups. Here are some example requests: - -Request supported PIDs of service 0x01:: - - req = OBD()/OBD_S01(pid=[0x00]) - -The response will contain a PacketListField, called `data_records`. This field contains the actual response:: - - resp = OBD()/OBD_S01_PR(data_records=[OBD_S01_PR_Record()/OBD_PID00(supported_pids=3196041235)]) - resp.show() - ###[ On-board diagnostics ]### - service= CurrentPowertrainDiagnosticDataResponse - ###[ Parameter IDs ]### - \data_records\ - |###[ OBD_S01_PR_Record ]### - | pid= 0x0 - |###[ PID_00_PIDsSupported ]### - | supported_pids= PID20+PID1F+PID1C+PID15+PID14+PID13+PID11+PID10+PID0F+PID0E+PID0D+PID0C+PID0B+PID0A+PID07+PID06+PID05+PID04+PID03+PID01 - -Let's assume our ECU under test supports the pid 0x15:: - - req = OBD()/OBD_S01(pid=[0x15]) - resp = sock.sr1(req) - resp.show() - ###[ On-board diagnostics ]### - service= CurrentPowertrainDiagnosticDataResponse - ###[ Parameter IDs ]### - \data_records\ - |###[ OBD_S01_PR_Record ]### - | pid= 0x15 - |###[ PID_15_OxygenSensor2 ]### - | outputVoltage= 1.275 V - | trim= 0 % - - -The different services in OBD support different kinds of data. -Service 01 and Service 02 support Parameter Identifiers (pid). -Service 03, 07 and 0A support Diagnostic Trouble codes (dtc). -Service 04 doesn't require a payload. -Service 05 is not implemented on OBD over CAN. -Service 06 support Monitoring Identifiers (mid). -Service 08 support Test Identifiers (tid). -Service 09 support Information Identifiers (iid). - -Examples: -^^^^^^^^^ - -Request supported Information Identifiers:: - - req = OBD()/OBD_S09(iid=[0x00]) - -Request the Vehicle Identification Number (VIN):: - - req = OBD()/OBD_S09(iid=0x02) - resp = sock.sr1(req) - resp.show() - ###[ On-board diagnostics ]### - service= VehicleInformationResponse - ###[ Infotype IDs ]### - \data_records\ - |###[ OBD_S09_PR_Record ]### - | iid= 0x2 - |###[ IID_02_VehicleIdentificationNumber ]### - | count= 1 - | vehicle_identification_numbers= ['W0L000051T2123456'] - - -.. image:: graphics/animations/animation-scapy-obd.svg - - -Test-Setup Tutorials --------------------- - -Hardware Setup -^^^^^^^^^^^^^^ - -Beagle Bone Black Operating System Setup -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -#. | **Download an Image** - | The latest Debian Linux image can be found at the website - | ``https://beagleboard.org/latest-images``. Choose the BeagleBone - Black IoT version and download it. - - :: - - wget https://debian.beagleboard.org/images/bone-debian-8.7\ - -iot-armhf-2017-03-19-4gb.img.xz - - - After the download, copy it to an SD-Card with minimum of 4 GB storage. - - :: - - xzcat bone-debian-8.7-iot-armhf-2017-03-19-4gb.img.xz | \ - sudo dd of=/dev/xvdj - - -#. | **Enable WiFi** - | USB-WiFi dongles are well supported by Debian Linux. Login over SSH - on the BBB and add the WiFi network credentials to the file - ``/var/lib/connman/wifi.config``. If a USB-WiFi dongle is not - available, it is also possible to share the host's internet - connection with the Ethernet connection of the BBB emulated over - USB. A tutorial to share the host network connection can be found - on this page: - | ``https://elementztechblog.wordpress.com/2014/12/22/sharing-internet -using-network-over-usb-in-beaglebone-black/``. - | Login as root onto the BBB: - - :: - - ssh debian@192.168.7.2 - sudo su - - - Provide the WiFi login credentials to connman: - - :: - - echo "[service_home] - Type = wifi - Name = ssid - Security = wpa - Passphrase = xxxxxxxxxxxxx" \ - > /var/lib/connman/wifi.config - - - Restart the connman service: - - :: - - systemctl restart connman.service - - -Dual-CAN Setup -~~~~~~~~~~~~~~ - -#. | **Device tree setup** - | You'll need to follow this section only if you want to use two CAN - interfaces (DCAN0 and DCAN1). This will disable I2C2 from using pins - P9.19 and P9.20, which are needed by DCAN0. You only need to perform the - steps in this section once. - - | Warning: The configuration in this section will disable BBB capes from - working. Each cape has a small I2C EEPROM that stores info that the BBB - needs to know in order to communicate with the cape. Disable I2C2, and - the BBB has no way to talk to cape EEPROMs. Of course, if you don't use - capes then this is not a problem. - - | Acquire DTS sources that matches your kernel version. Go - `here `__ and switch over to the - branch that represents your kernel version. Download the entire branch - as a ZIP file. Extract it and do the following (version 4.1 shown as an - example): - - :: - - # cd ~/src/linux-4.1/arch/arm/boot/dts/include/ - # rm dt-bindings - # ln -s ../../../../../include/dt-bindings - # cd .. - Edit am335x-bone-common.dtsi and ensure the line with "//pinctrl-0 = <&i2c2_pins>;" is commented out. - Remove the complete &ocp section at the end of this file - # mv am335x-boneblack.dts am335x-boneblack.raw.dts - # cpp -nostdinc -I include -undef -x assembler-with-cpp am335x-boneblack.raw.dts > am335x-boneblack.dts - # dtc -W no-unit_address_vs_reg -O dtb -o am335x-boneblack.dtb -b 0 -@ am335x-boneblack.dts - # cp /boot/dtbs/am335x-boneblack.dtb /boot/dtbs/am335x-boneblack.orig.dtb - # cp am335x-boneblack.dtb /boot/dtbs/ - Reboot - -#. **Overlay setup** - | This section describes how to build the device overlays for the two CAN devices (DCAN0 and DCAN1). You only need to perform the steps in this section once. - | Acquire BBB cape overlays, in one of two ways… - - :: - - # apt-get install bb-cape-overlays - https://github.com/beagleboard/bb.org-overlays/ - - | Then do the following: - - - :: - - # cd ~/src/bb.org-overlays-master/src/arm - # ln -s ../../include - # mv BB-CAN1-00A0.dts BB-CAN1-00A0.raw.dts - # cp BB-CAN1-00A0.raw.dts BB-CAN0-00A0.raw.dts - Edit BB-CAN0-00A0.raw.dts and make relevant to CAN0. Example is shown below. - # cpp -nostdinc -I include -undef -x assembler-with-cpp BB-CAN0-00A0.raw.dts > BB-CAN0-00A0.dts - # cpp -nostdinc -I include -undef -x assembler-with-cpp BB-CAN1-00A0.raw.dts > BB-CAN1-00A0.dts - # dtc -W no-unit_address_vs_reg -O dtb -o BB-CAN0-00A0.dtbo -b 0 -@ BB-CAN0-00A0.dts - # dtc -W no-unit_address_vs_reg -O dtb -o BB-CAN1-00A0.dtbo -b 0 -@ BB-CAN1-00A0.dts - # cp *.dtbo /lib/firmware - - -#. | **CAN0 Example Overlay** - | Inside the DTS folder, create a file with the content of the - following listing. - - :: - - cd ~/bb.org-overlays/src/arm - cat < BB-CAN0-00A0.raw.dts - - /* - * Copyright (C) 2015 Robert Nelson - * - * Virtual cape for CAN0 on connector pins P9.19 P9.20 - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. - */ - /dts-v1/; - /plugin/; - - #include - #include - - / { - compatible = "ti,beaglebone", "ti,beaglebone-black", "ti,beaglebone-green"; - - /* identification */ - part-number = "BB-CAN0"; - version = "00A0"; - - /* state the resources this cape uses */ - exclusive-use = - /* the pin header uses */ - "P9.19", /* can0_rx */ - "P9.20", /* can0_tx */ - /* the hardware ip uses */ - "dcan0"; - - fragment@0 { - target = <&am33xx_pinmux>; - __overlay__ { - bb_dcan0_pins: pinmux_dcan0_pins { - pinctrl-single,pins = < - BONE_P9_19 (PIN_INPUT_PULLUP | MUX_MODE2) /* uart1_txd.d_can0_rx */ - BONE_P9_20 (PIN_OUTPUT_PULLUP | MUX_MODE2) /* uart1_rxd.d_can0_tx */ - >; - }; - }; - }; - - fragment@1 { - target = <&dcan0>; - __overlay__ { - status = "okay"; - pinctrl-names = "default"; - pinctrl-0 = <&bb_dcan0_pins>; - }; - }; - }; - EOF - - -#. | **Test the Dual-CAN Setup** - | Do the following each time you need CAN, or automate these steps if you like. - - :: - - # echo BB-CAN0 > /sys/devices/platform/bone_capemgr/slots - # echo BB-CAN1 > /sys/devices/platform/bone_capemgr/slots - # modprobe can - # modprobe can-dev - # modprobe can-raw - # ip link set can0 up type can bitrate 50000 - # ip link set can1 up type can bitrate 50000 - - Check the output of the Capemanager if both CAN interfaces have been - loaded. - - :: - - cat /sys/devices/platform/bone_capemgr/slots - - 0: PF---- -1 - 1: PF---- -1 - 2: PF---- -1 - 3: PF---- -1 - 4: P-O-L- 0 Override Board Name,00A0,Override Manuf, BB-CAN0 - 5: P-O-L- 1 Override Board Name,00A0,Override Manuf, BB-CAN1 - - - If something went wrong, ``dmesg`` provides kernel messages to analyse the root of failure. - -#. | **References** - - - `embedded-things.com: Enable CANbus on the Beaglebone - Black `__ - - `electronics.stackexchange.com: Beaglebone Black CAN bus - Setup `__ - -#. | **Acknowledgment** - | Thanks to Tom Haramori. Parts of this section are copied from his guide: https://github.com/haramori/rhme3/blob/master/Preparation/BBB_CAN_setup.md - - - -ISO-TP Kernel Module Installation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A Linux ISO-TP kernel module can be downloaded from this website: -``https://github.com/hartkopp/can-isotp.git``. The file -``README.isotp`` in this repository provides all information and -necessary steps for downloading and building this kernel module. The -ISO-TP kernel module should also be added to the ``/etc/modules`` file, -to load this module automatically at system boot of the BBB. - -CAN-Interface Setup -~~~~~~~~~~~~~~~~~~~ - -As the final step to prepare the BBB's CAN interfaces for usage, these -interfaces have to be set up through some terminal commands. The bitrate -can be chosen to fit the bitrate of a CAN bus under test. - -:: - - ip link set can0 up type can bitrate 500000 - ip link set can1 up type can bitrate 500000 - -Raspberry Pi SOME/IP setup -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To build a small test environment in which you can send SOME/IP messages to and from server instances or disguise yourself as a server, one Raspberry Pi, your laptop and the vsomeip library are sufficient. - -#. | **Download image** - - Download the latest raspbian image (``https://www.raspberrypi.org/downloads/raspbian/``) and install it on the Raspberry. - -#. | **Vsomeip setup** - - Download the vsomeip library on the Rapsberry, apply the git patch so it can work with the newer boost libraries and then install it. - - :: - - git clone https://github.com/GENIVI/vsomeip.git - cd vsomeip - wget -O 0001-Support-boost-v1.66.patch.zip \ - https://github.com/GENIVI/vsomeip/files/2244890/0001-Support-boost-v1.66.patch.zip - unzip 0001-Support-boost-v1.66.patch.zip - git apply 0001-Support-boost-v1.66.patch - mkdir build - cd build - cmake -DENABLE_SIGNAL_HANDLING=1 .. - make - make install - -#. | **Make applications** - - Write some small applications which function as either a service or a client and use the Scapy SOME/IP implementation to communicate with the client or the server. Examples for vsomeip applications are available on the vsomeip github wiki page (``https://github.com/GENIVI/vsomeip/wiki/vsomeip-in-10-minutes``). - - - -Software Setup -^^^^^^^^^^^^^^ - -Cannelloni Framework Installation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The Cannelloni framework is a small application written in C++ to -transfer CAN data over UDP. In this way, a researcher can map the CAN -communication of a remote device to its workstation, or even combine -multiple remote CAN devices on his machine. The framework can be -downloaded from this website: -``https://github.com/mguentner/cannelloni.git``. The ``README.md`` file -explains the installation and usage in detail. Cannelloni needs virtual -CAN interfaces on the operator's machine. The next listing shows the -setup of virtual CAN interfaces. - -:: - - modprobe vcan - - ip link add name vcan0 type vcan - ip link add name vcan1 type vcan - - ip link set dev vcan0 up - ip link set dev vcan1 up - - tc qdisc add dev vcan0 root tbf rate 300kbit latency 100ms burst 1000 - tc qdisc add dev vcan1 root tbf rate 300kbit latency 100ms burst 1000 - - cannelloni -I vcan0 -R -r 20000 -l 20000 & - cannelloni -I vcan1 -R -r 20001 -l 20001 & - - diff --git a/doc/scapy/build_dissect.rst b/doc/scapy/build_dissect.rst index 33669987e0f..feadfde5dff 100644 --- a/doc/scapy/build_dissect.rst +++ b/doc/scapy/build_dissect.rst @@ -1128,3 +1128,24 @@ The goal is to keep the writing of packets fluent and intuitive. The basic instr * Use inverted camel case and common abbreviations (e.g. len, src, dst, dstPort, srcIp). * Wherever it is either possible or relevant, prefer using the names from the specifications. This aims to help newcomers to easily forge packets. + +Add new protocols to Scapy +-------------------------- + +New protocols can go either in ``scapy/layers`` or to ``scapy/contrib``. Protocols in ``scapy/layers`` should be usually found on common networks, while protocols in ``scapy/contrib`` should be uncommon or specific. + +To be precise, ``scapy/layers`` protocols should not be importing ``scapy/contrib`` protocols, whereas ``scapy/contrib`` protocols may import both ``scapy/contrib`` and ``scapy/layers`` protocols. + +Scapy provides an ``explore()`` function, to search through the available layer/contrib modules. Therefore, modules contributed back to Scapy must provide information about them, knowingly: + +- A **contrib** module must have defined, near the top of the module (below the license header is a good place) **(without the brackets)** `Example `_ :: + + # scapy.contrib.description = [...] + # scapy.contrib.status = [...] + # scapy.contrib.name = [...] (optional) + +- If the contrib module does not contain any packets, and should not be indexed in `explore()`, then you should instead set:: + + # scapy.contrib.status = skip + +- A **layer** module must have a docstring, in which the first line shortly describes the module. diff --git a/doc/scapy/graphics/animations/animation-cansend.svg b/doc/scapy/graphics/animations/animation-cansend.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-rdcandump.svg b/doc/scapy/graphics/animations/animation-rdcandump.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-can.svg b/doc/scapy/graphics/animations/animation-scapy-can.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-canframe.svg b/doc/scapy/graphics/animations/animation-scapy-canframe.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-cansockets-mitm.svg b/doc/scapy/graphics/animations/animation-scapy-cansockets-mitm.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-cansockets-mitm2.svg b/doc/scapy/graphics/animations/animation-scapy-cansockets-mitm2.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-cansockets-sniff.svg b/doc/scapy/graphics/animations/animation-scapy-cansockets-sniff.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-demo.svg b/doc/scapy/graphics/animations/animation-scapy-demo.svg new file mode 100644 index 00000000000..7e7268f74c6 --- /dev/null +++ b/doc/scapy/graphics/animations/animation-scapy-demo.svg @@ -0,0 +1,44 @@ + + + + + + + + + + demo@scapy:~/github/scapy# demo@scapy:~/github/scapy# s demo@scapy:~/github/scapy# su demo@scapy:~/github/scapy# sud demo@scapy:~/github/scapy# sudo demo@scapy:~/github/scapy# sudo demo@scapy:~/github/scapy# sudo . demo@scapy:~/github/scapy# sudo ./ demo@scapy:~/github/scapy# sudo ./r demo@scapy:~/github/scapy# sudo ./ru demo@scapy:~/github/scapy# sudo ./run_scapy WARNING: No route found for IPv6 destination :: (no default route?) e apyyyyCY//////////YCa | >>> >>> e >>> ex >>> exp >>> expl >>> explo >>> explor >>> explore >>> explore( >>> explore() demo@scapy:~/github/scapy# sudo ./run_scapyINFO: Can't import matplotlib. Won't be able to plot.WARNING: No route found for IPv6 destination :: (no default route?)e aSPY//YASa apyyyyCY//////////YCa | sY//////YSpcs scpCY//Pp | Welcome to Scapy ayp ayyyyyyySCP//Pp syY//C | Version 2.4.2.dev228 AYAsAYYYYYYYY///Ps cY//S | pCCCCY//p cSSps y//Y | https://github.com/secdev/scapy SPPPP///a pP///AC//Y | A//A cyP////C | Have fun! p///Ac sC///a | P////YCpc A//A | We are in France, we say Skappee. scccccp///pSP///p p//Y | OK? Merci. sY/////////y caa S//P | -- Sebastien Chabal cayCyayP//Ya pY/Ya | sY/PsY////YCc aC//Yp sc sccaCY//PCypaapyCP//YSs spCPY//////YPSps ccaacs using IPython 7.2.0>>> explore() ┌────────────────────────| Scapy v2.4.2.dev228 |────────────────────────┐ │ │ Chose the type of packets you want to explore: < Layers > < Contribs > < Cancel > └───────────────────────────────────────────────────────────────────────┘ < Layers > < Contribs > < Cancel > │ │ │ │ │ ( ) IPv4 (Internet Protoco │ ( ) Bluetooth 4LE layer │ ( ) Wireless MAC according to IEEE 802.15.4. │ │ ( ) IrDA infrared data co │ ( ) LLMNR (Link Local Multicast Node Resolution). │ (*) Packet class. Binding mechanism. fuzz() method. ^ └─────────────────────────────────────────────── │ (*) Packet class. Binding mechanism. fuzz() method. ^ │ ( ) ASN.1 Packet │ │ ( ) ASN.1 Packet │ │ ( ) Bluetooth layers, sockets and send/receive functions. │ │ ( ) Bluetooth layers, sockets and send/receive functions. │ │ ( ) Classes and functions for layer 2 protocols. │ │ ( ) Classes and functions for layer 2 protocols. │ │ ( ) IPv4 (Internet Protocol v4). │ │ ( ) IPv4 (Internet Protocol v4). │ │ (*) IPv4 (Internet Protocol v4). │ < Ok > < Cancel > ┌───────────────────────────────────────────| Scapy v2.4.2.dev228 |────────────────────────────────────────────┐ Please select a layer among the following, to see all packets contained in it: │ ( ) IPv6 (Internet Protocol v6). │ │ ( ) Wireless LAN according to IEEE 802.11. │ │ ( ) Per-Packet Information (PPI) Protocol │ │ ( ) Bluetooth 4LE layer │ │ ( ) DHCP (Dynamic Host Configuration Protocol) and BOOTP │ │ ( ) DHCPv6: Dynamic Host Configuration Protocol for IPv6. [RFC 3315] │ │ ( ) DNS: Domain Name System. │ │ ( ) Extensible Authentication Protocol (EAP) │ │ ( ) GPRS (General Packet Radio Service) for mobile data communication. │ │ ( ) HSRP (Hot Standby Router Protocol): proprietary redundancy protocol for Cisco routers. # noqa: E501 │ │ ( ) IPsec layer │ │ ( ) IrDA infrared data communication. │ │ ( ) ISAKMP (Internet Security Association and Key Management Protocol). │ │ ( ) PPP (Point to Point Protocol) │ │ ( ) L2TP (Layer 2 Tunneling Protocol) for VPNs. │ │ ( ) LLMNR (Link Local Multicast Node Resolution). v └──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ │ ( ) Packet class. Binding mechanism. fuzz() method. ^ │ (*) IPv4 (Internet Protocol v4). │ < Ok > < Cancel > │ ( ) ASN.1 Packet │ ( ) DHCPv6: Dynamic Host Configuration Protocol for IPv │ ( ) GPRS (General Packet Radio Service) for mobile data communication. < Ok > < Cancel > Packets contained in scapy.layers.inet: Class |Name--------------------------|------- --------------------------|-------------------------------------------ICMP |ICMPICMPerror |ICMP in ICMPIP |IPIPOption |IP OptionIPOption_Address_Extension|IP Option Address ExtensionIPOption_EOL |IP Option End of Options ListIPOption_LSRR |IP Option Loose Source and Record RouteIPOption_MTU_Probe |IP Option MTU ProbeIPOption_MTU_Reply |IP Option MTU ReplyIPOption_NOP |IP Option No OperationIPOption_RR |IP Option Record RouteIPOption_Router_Alert |IP Option Router AlertIPOption_SDBM |IP Option Selective Directed Broadcast ModeIPOption_SSRR |IP Option Strict Source and Record RouteIPOption_Security |IP Option SecurityIPOption_Stream_Id |IP Option Stream IDIPOption_Traceroute |IP Option TracerouteIPerror |IP in ICMPTCP |TCPTCPerror |TCP in ICMPUDP >>> l >>> ls >>> ls( >>> ls(I >>> ls(IP >>> ls(IP) UDP |UDPUDPerror |UDP in ICMP>>> ls(IP) >>> p >>> pk >>> pkt >>> pkt >>> pkt = >>> pkt = >>> pkt = I >>> pkt = IP >>> pkt = IP( >>> pkt = IP(d >>> pkt = IP(ds >>> pkt = IP(dst >>> pkt = IP(dst= >>> pkt = IP(dst=" >>> pkt = IP(dst="w >>> pkt = IP(dst="ww >>> pkt = IP(dst="www >>> pkt = IP(dst="www. >>> pkt = IP(dst="www.s >>> pkt = IP(dst="www.se >>> pkt = IP(dst="www.sec >>> pkt = IP(dst="www.secd >>> pkt = IP(dst="www.secde >>> pkt = IP(dst="www.secdev >>> pkt = IP(dst="www.secdev. >>> pkt = IP(dst="www.secdev.o >>> pkt = IP(dst="www.secdev.or >>> pkt = IP(dst="www.secdev.org >>> pkt = IP(dst="www.secdev.org" >>> pkt = IP(dst="www.secdev.org") >>> pkt = IP(dst="www.secdev.org")/ >>> pkt = IP(dst="www.secdev.org")/I >>> pkt = IP(dst="www.secdev.org")/IC >>> pkt = IP(dst="www.secdev.org")/ICM >>> pkt = IP(dst="www.secdev.org")/ICMP >>> pkt = IP(dst="www.secdev.org")/ICMP( version : BitField (4 bits) = (4) ihl : BitField (4 bits) = (None)tos : XByteField = (0)len : ShortField = (None)id : ShortField = (1)flags : FlagsField (3 bits) = (<Flag 0 ()>)frag : BitField (13 bits) = (0)ttl : ByteField = (64)proto : ByteEnumField = (0)chksum : XShortField = (None)src : SourceIPField = (None)dst : DestIPField = (None)options : PacketListField = ([])>>> pkt = IP(dst="www.secdev.org")/ICMP() >>> pkt. >>> pkt.s >>> pkt.sh >>> pkt.sho >>> pkt.show >>> pkt.show2 >>> pkt.show2( >>> pkt.show2() >>> pkt = IP(dst="www.secdev.org")/ICMP() >>> pkt.show2() >>> >>> s ###[ IP ]### version= 4 ihl= 5 tos= 0x0 len= 28 id= 1 flags= frag= 0 ttl= 64 proto= icmp chksum= 0x875a src= 212.83.148.19 dst= 217.25.178.5 \options\###[ ICMP ]### type= echo-request code= 0 chksum= 0xf7ff id= 0x0 seq= 0x0>>> sr >>> sr sr() sr1flood() srbt1() srloop() srp1() srpflood() sr1() srbt() srflood() srp() srp1flood() srploop() sr() sr1flood() srbt1() srloop() srp1() srpflood() >>> sr1 >>> sr1 function(x, promisc, filter, iface, nofilter, args, kargs) sr1() srbt() srflood() srp() srp1flood() srploop() >>> sr1( >>> sr1( >>> sr1(p >>> sr1(pk >>> sr1(pkt >>> sr1(pkt) .... ..... . >>> sr1(pkt) Begin emission: .....Finished sending 1 packets. .* Received 7 packets, got 1 answers, remaining 0 packets<IP version=4 ihl=5 tos=0x0 len=28 id=21006 flags= frag=0 ttl=60 proto=icmp chksum=0x394d src=217.25.178.5 dst=212.83.148.19 |<ICMP type=echo-reply code=0 chksum=0xffff id=0x0 seq=0x0 |<Padding load='\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>> >>> _ >>> _. >>> _.s >>> _.sh >>> _.sho >>> _.show >>> _.show( x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>>>>> _.show() >>> _.show() id= 21006 ttl= 60 chksum= 0x394d src= 217.25.178.5 dst= 212.83.148.19 type= echo-reply chksum= 0xffff###[ Padding ]### load= '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'demo@scapy:~/github/scapy# >>> demo@scapy:~/github/scapy# exit demo@scapy:~/github/scapy# exit + \ No newline at end of file diff --git a/doc/scapy/graphics/animations/animation-scapy-gmlan.svg b/doc/scapy/graphics/animations/animation-scapy-gmlan.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-native-cansocket.svg b/doc/scapy/graphics/animations/animation-scapy-native-cansocket.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-obd.svg b/doc/scapy/graphics/animations/animation-scapy-obd.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-python-can-cansocket.svg b/doc/scapy/graphics/animations/animation-scapy-python-can-cansocket.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-rdcandump.svg b/doc/scapy/graphics/animations/animation-scapy-rdcandump.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-rdpcap.svg b/doc/scapy/graphics/animations/animation-scapy-rdpcap.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-uds.svg b/doc/scapy/graphics/animations/animation-scapy-uds.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-uds2.svg b/doc/scapy/graphics/animations/animation-scapy-uds2.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/animations/animation-scapy-uds3.svg b/doc/scapy/graphics/animations/animation-scapy-uds3.svg old mode 100644 new mode 100755 diff --git a/doc/scapy/graphics/scapy-main-console.png b/doc/scapy/graphics/scapy-main-console.png deleted file mode 100644 index 02402168fba..00000000000 Binary files a/doc/scapy/graphics/scapy-main-console.png and /dev/null differ diff --git a/doc/scapy/graphics/scapy_version_timeline.jpg b/doc/scapy/graphics/scapy_version_timeline.jpg new file mode 100644 index 00000000000..840dbc04a1e Binary files /dev/null and b/doc/scapy/graphics/scapy_version_timeline.jpg differ diff --git a/doc/scapy/index.rst b/doc/scapy/index.rst index 6fd46d70f69..d881b6b8040 100644 --- a/doc/scapy/index.rst +++ b/doc/scapy/index.rst @@ -17,17 +17,32 @@ This document is under a `Creative Commons Attribution - Non-Commercial .. toctree:: :maxdepth: 2 + :caption: General documentation introduction installation usage advanced_usage + +.. toctree:: + :maxdepth: 2 + :caption: Extend scapy + extending build_dissect functions - bluetooth +.. toctree:: + :maxdepth: 2 + :caption: Layer-specific documentation + :glob: + + layers/index.rst + +.. toctree:: + :maxdepth: 2 + :caption: About troubleshooting development diff --git a/doc/scapy/installation.rst b/doc/scapy/installation.rst index 46ae4bf2d02..cc82c8eaec0 100644 --- a/doc/scapy/installation.rst +++ b/doc/scapy/installation.rst @@ -13,14 +13,12 @@ Overview 3. (Optional): `Install additional software for special features <#optional-software-for-special-features>`_. 4. Run Scapy with root privileges. -Each of these steps can be done in a different way depending on your platform and on the version of Scapy you want to use. +Each of these steps can be done in a different way depending on your platform and on the version of Scapy you want to use. Follow the platform-specific instructions for more detail. -At the moment, there are two different versions of Scapy: +Scapy versions +============== -* **Scapy v2.x**. The current up-to-date version. It consists of several files packaged in the standard distutils way. - Scapy v2 <= 2.3.3 needs Python 2.5, Scapy v2 > 2.3.3 needs Python 2.7 or 3.4+. -* **Scapy v1.x (deprecated)**. It does not support Python 3. It consists of only one file and works on Python 2.4, so it might be easier to install. - Moreover, your OS may already have specially prepared packages or ports for it. The last version is v1.2.2. +.. image:: graphics/scapy_version_timeline.jpg .. note:: @@ -94,15 +92,6 @@ Then you can always update to the latest version:: You can run scapy without installing it using the ``run_scapy`` (unix) or ``run_scapy.bat`` (Windows) script or running it directly from the executable zip file (see the previous section). -Installing Scapy v1.2 (Deprecated) -================================== - -As Scapy v1 consists only of one single Python file, installation is easy: -Just download the last version and run it with your Python interpreter:: - - $ wget https://raw.githubusercontent.com/secdev/scapy/v1.2.0.2/scapy.py - $ sudo python scapy.py - Optional software for special features ====================================== @@ -339,9 +328,6 @@ Windows Scapy is primarily being developed for Unix-like systems and works best on those platforms. But the latest version of Scapy supports Windows out-of-the-box. So you can use nearly all of Scapy's features on your Windows machine as well. -.. note:: - If you update from Scapy-win v1.2.0.2 to Scapy v2 remember to use ``from scapy.all import *`` instead of ``from scapy import *``. - .. image:: graphics/scapy-win-screenshot1.png :scale: 80 :align: center diff --git a/doc/scapy/introduction.rst b/doc/scapy/introduction.rst index 20b64379fd8..08e7443c316 100644 --- a/doc/scapy/introduction.rst +++ b/doc/scapy/introduction.rst @@ -115,6 +115,9 @@ information is lost in this operation. Quick demo ========== +.. image:: graphics/animations/animation-scapy-demo.svg + :align: center + First, we play a bit and create four IP packets at once. Let's see how it works. We first instantiate the IP class. Then, we instantiate it again and we provide a destination that is worth four IP addresses (/30 gives the netmask). Using a Python idiom, we develop this implicit packet in a set of explicit packets. Then, we quit the interpreter. As we provided a session file, the variables we were working on are saved, then reloaded:: # ./run_scapy -s mysession @@ -187,25 +190,5 @@ Learning Python Scapy uses the Python interpreter as a command board. That means that you can directly use the Python language (assign variables, use loops, define functions, etc.) If you are new to Python and you really don't understand a word because of that, or if you want to learn this language, take an hour to read the very good `Python tutorial `_ by Guido Van Rossum. After that, you'll know Python :) (really!). For a more in-depth tutorial `Dive Into Python `_ is a very good start too. - -For a quick start, here's an overview of Python's data types: - -* ``int`` (signed, 32bits) : ``42`` -* ``long`` (signed, infinite): ``42L`` -* ``str`` : ``"bell\x07\n"`` or ``’bell\x07\n’`` - -* ``tuple`` (immutable): ``(1,4,"42")`` -* ``list`` (mutable): ``[4,2,"1"]`` -* ``dict`` (mutable): ``{ "one":1 , "two":2 }`` - -There are no block delimiters in Python. Instead, indentation does matter:: - - if cond: - instr - instr - elif cond2: - instr - else: - instr diff --git a/doc/scapy/layers/automative.rst b/doc/scapy/layers/automative.rst new file mode 100644 index 00000000000..13778ad8350 --- /dev/null +++ b/doc/scapy/layers/automative.rst @@ -0,0 +1,1088 @@ +***************************************** +Automotive Penetration Testing with Scapy +***************************************** + +.. note:: + All automotive related features work best on Linux systems. CANSockets and ISOTPSockets in Scapy are based on Linux kernel modules. + The python-can project is used to support CAN and CANSockets on other systems, besides Linux. + This guide explains the hardware setup on a BeagleBone Black. The BeagleBone Black was chosen because of its two CAN interfaces on the main processor. + The presence of two CAN interfaces in one device gives the possibility of CAN MITM attacks and session hijacking. + The Cannelloni framework turns a BeagleBone Black into a CAN-to-UDP interface, which gives you the freedom to run Scapy + on a more powerful machine. + +Protocols +--------- + +The following table should give a brief overview about all automotive capabilities +of Scapy. Most application layer protocols have many specialized ``Packet`` classes. +These special purpose classes are not part of this overview. Use the ``explore()`` +function to get all information about one specific protocol. + ++---------------------+----------------------+--------------------------------------------------------+ +| OSI Layer | Protocol | Scapy Implementations | ++=====================+======================+========================================================+ +| Application Layer | UDS (ISO 14229) | UDS, UDS_* | +| +----------------------+--------------------------------------------------------+ +| | GMLAN | GMLAN, GMLAN_* | +| +----------------------+--------------------------------------------------------+ +| | SOME/IP | SOMEIP, SD | +| +----------------------+--------------------------------------------------------+ +| | BMW ENET | ENET, ENETSocket | +| +----------------------+--------------------------------------------------------+ +| | OBD | OBD, OBD_S0X | +| +----------------------+--------------------------------------------------------+ +| | CCP | CCP, DTO, CRO | ++---------------------+----------------------+--------------------------------------------------------+ +| Transportaion Layer | ISO-TP (ISO 15765-2) | ISOTPSocket, ISOTPNativeSocket, ISOTPSoftSocket | +| | | | +| | | ISOTPSniffer, ISOTPMessageBuilder | +| | | | +| | | ISOTPHeader, ISOTPHeaderEA, | +| | | | +| | | ISOTP, ISOTP_SF, ISOTP_FF, ISOTP_CF, ISOTP_FC | ++---------------------+----------------------+--------------------------------------------------------+ +| Data Link Layer | CAN (ISO 11898) | CAN, CANSocket, rdcandump | ++---------------------+----------------------+--------------------------------------------------------+ + + +Hands-On +^^^^^^^^ + +Send a message over Linux SocketCAN:: + + load_layer('can') + load_contrib('cansocket') + socket = CANSocket(iface='can0') + packet = CAN(identifier=0x123, data=b'01020304') + + socket.sr1(packet, timeout=1) + + srcan(packet, 'can0', timeout=1) + +Send a message over a Vector CAN-Interface:: + + import can + load_layer('can') + conf.contribs['CANSocket'] = {'use-python-can' : True} + load_contrib('cansocket') + from can.interfaces.vector import VectorBus + socket = CANSocket(iface=VectorBus(0, bitrate=1000000)) + packet = CAN(identifier=0x123, data=b'01020304') + socket.sr1(packet) + + srcan(packet, VectorBus(0, bitrate=1000000)) + +System compatibilities +---------------------- + +Dependent on your setup, different implementations have to be used. + ++---------------------+----------------------+-------------------------------------+----------------------------------------------------------+ +| Python \ OS | Linux with can_isotp | Linux wo can_isotp | Windows / OSX | ++=====================+======================+=====================================+==========================================================+ +| Python 3 | ISOTPNativeSocket | ISOTPSoftSocket | ISOTPSoftSocket | +| +----------------------+-------------------------------------+ | +| | ``conf.contribs['CANSocket'] = {'use-python-can': False}`` | ``conf.contribs['CANSocket'] = {'use-python-can': True}``| ++---------------------+------------------------------------------------------------+----------------------------------------------------------+ +| Python 2 | ISOTPSoftSocket | ISOTPSoftSocket | +| | | | +| | ``conf.contribs['CANSocket'] = {'use-python-can': True}`` | ``conf.contribs['CANSocket'] = {'use-python-can': True}``| ++---------------------+------------------------------------------------------------+----------------------------------------------------------+ + +The class ``ISOTPSocket`` can be set to a ``ISOTPNativeSocket`` or a ``ISOTPSoftSocket``. +The decision is made dependent on the configuration ``conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': True}`` (to select ``ISOTPNativeSocket``) or +``conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': False}`` (to select ``ISOTPSoftSocket``). +This will allow you to write platform independent code. Apply this configuration before loading the ISOTP layer +with ``load_contrib("isotp")``. + +Another remark in respect to ISOTPSocket compatibility. Always use with for socket creation. Example:: + + with ISOTPSocket("vcan0", did=0x241, sid=0x641) as sock: + sock.send(...) + + +CAN Layer +--------- + +Setup +^^^^^ + +These commands enable a virtual CAN interface on a Linux machine:: + + from scapy.layers.can import * + import os + + bashCommand = "/bin/bash -c 'sudo modprobe vcan; sudo ip link add name vcan0 type vcan; sudo ip link set dev vcan0 up'" + os.system(bashCommand) + +If it's required, the CAN interface can be set into a ``listen-only`` or ``loopback`` mode with `ip link set` commands:: + + ip link set vcan0 type can help # shows additional information + + +This example shows a basic functions of Linux can-utils. These utilities are handy for +quick checks or logging. + +.. image:: ../graphics/animations/animation-cansend.svg + +CAN Frame +^^^^^^^^^ + +Creating a standard CAN frame:: + + frame = CAN(identifier=0x200, length=8, data=b'\x01\x02\x03\x04\x05\x06\x07\x08') + +Creating an extended CAN frame:: + + frame = CAN(flags='extended', identifier=0x10010000, length=8, data=b'\x01\x02\x03\x04\x05\x06\x07\x08') + +.. image:: ../graphics/animations/animation-scapy-canframe.svg + +Writing and reading to pcap files:: + + x = CAN(identifier=0x7ff,length=8,data=b'\x01\x02\x03\x04\x05\x06\x07\x08') + wrpcap('/tmp/scapyPcapTest.pcap', x, append=False) + y = rdpcap('/tmp/scapyPcapTest.pcap', 1) + +.. image:: ../graphics/animations/animation-scapy-rdpcap.svg +.. image:: ../graphics/animations/animation-scapy-rdcandump.svg + +CANSocket native +^^^^^^^^^^^^^^^^ + +Creating a simple native CANSocket:: + + conf.contribs['CANSocket'] = {'use-python-can': False} #(default) + load_contrib('cansocket') + + # Simple Socket + socket = CANSocket(iface="vcan0") + +Creating a native CANSocket only listen for messages with Id == 0x200:: + + socket = CANSocket(iface="vcan0", can_filters=[{'can_id': 0x200, 'can_mask': 0x7FF}]) + +Creating a native CANSocket only listen for messages with Id >= 0x200 and Id <= 0x2ff:: + + socket = CANSocket(iface="vcan0", can_filters=[{'can_id': 0x200, 'can_mask': 0x700}]) + +Creating a native CANSocket only listen for messages with Id != 0x200:: + + socket = CANSocket(iface="vcan0", can_filters=[{'can_id': 0x200 | CAN_INV_FILTER, 'can_mask': 0x7FF}]) + +Creating a native CANSocket with multiple can_filters:: + + socket = CANSocket(iface='vcan0', can_filters=[{'can_id': 0x200, 'can_mask': 0x7ff}, + {'can_id': 0x400, 'can_mask': 0x7ff}, + {'can_id': 0x600, 'can_mask': 0x7ff}, + {'can_id': 0x7ff, 'can_mask': 0x7ff}]) + +Creating a native CANSocket which also receives its own messages:: + + socket = CANSocket(iface="vcan0", receive_own_messages=True) + +.. image:: ../graphics/animations/animation-scapy-native-cansocket.svg + +Sniff on a CANSocket: + +.. image:: ../graphics/animations/animation-scapy-cansockets-sniff.svg + + +CANSocket python-can +^^^^^^^^^^^^^^^^^^^^ + +python-can is required to use various CAN-interfaces on Windows, OSX or Linux. +The python-can library is used through a CANSocket object. To create a python-can +CANSocket object, a python-can ``Bus`` object has to be used as interface. +The ``timeout`` parameter can be used to increase the receive performance of a +python-can CANSocket object. ``recv`` inside a python-can CANSocket object is +implemented through busy wait, since there is no ``select`` functionality on +Windows or on some proprietary CAN interfaces (like Vector interfaces). A small +``timeout`` might be required, if a ``sniff`` or ``bridge_and_sniff`` on multiple +interfaces is performed. + +Ways of creating a python-can CANSocket:: + + conf.contribs['CANSocket'] = {'use-python-can': True} + load_contrib('cansocket') + import can + +Creating a simple python-can CANSocket:: + + socket = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)) + +Creating a python-can CANSocket with multiple filters:: + + socket = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000, + can_filters=[{'can_id': 0x200, 'can_mask': 0x7ff}, + {'can_id': 0x400, 'can_mask': 0x7ff}, + {'can_id': 0x600, 'can_mask': 0x7ff}, + {'can_id': 0x7ff, 'can_mask': 0x7ff}])) + +.. image:: ../graphics/animations/animation-scapy-python-can-cansocket.svg + +For further details on python-can check: https://python-can.readthedocs.io/en/2.2.0/ + +CANSocket MITM attack with bridge and sniff +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +This example shows how to use bridge and sniff on virtual CAN interfaces. +For real world applications, use real CAN interfaces. +Set up two vcans on Linux terminal:: + + sudo modprobe vcan + sudo ip link add name vcan0 type vcan + sudo ip link add name vcan1 type vcan + sudo ip link set dev vcan0 up + sudo ip link set dev vcan1 up + +Import modules:: + + import threading + load_contrib('cansocket') + load_layer("can") + +Create can sockets for attack:: + + socket0 = CANSocket(iface='vcan0') + socket1 = CANSocket(iface='vcan1') + +Create a function to send packet with threading:: + + def sendPacket(): + sleep(0.2) + socket0.send(CAN(flags='extended', identifier=0x10010000, length=8, data=b'\x01\x02\x03\x04\x05\x06\x07\x08')) + +Create a function for forwarding or change packets:: + + def forwarding(pkt): + return pkt + +Create a function to bridge and sniff between two sockets:: + + def bridge(): + bSocket0 = CANSocket(iface='vcan0') + bSocket1 = CANSocket(iface='vcan1') + bridge_and_sniff(if1=bSocket0, if2=bSocket1, xfrm12=forwarding, xfrm21=forwarding, timeout=1) + bSocket0.close() + bSocket1.close() + +Create threads for sending packet and to bridge and sniff:: + + threadBridge = threading.Thread(target=bridge) + threadSender = threading.Thread(target=sendMessage) + +Start the threads:: + + threadBridge.start() + threadSender.start() + +Sniff packets:: + + packets = socket1.sniff(timeout=0.3) + +Close the sockets:: + + socket0.close() + socket1.close() + +.. image:: ../graphics/animations/animation-scapy-cansockets-mitm.svg +.. image:: ../graphics/animations/animation-scapy-cansockets-mitm2.svg + + +CAN Calibration Protocol (CCP) +------------------------------ + +CCP is derived from CAN. The CAN-header is part of a CCP frame. CCP has two types +of message objects. One is called Command Receive Object (CRO), the other is called +Data Transmission Object (DTO). Usually CROs are sent to an ECU, and DTOs are received +from an ECU. The information, if one DTO answers a CRO is implemented through a counter +field (ctr). If both objects have the same counter value, the payload of a DTO object +can be interpreted from the command of the associated CRO object. + +Creating a CRO message:: + + CCP(identifier=0x700)/CRO(ctr=1)/CONNECT(station_address=0x02) + CCP(identifier=0x711)/CRO(ctr=2)/GET_SEED(resource=2) + CCP(identifier=0x711)/CRO(ctr=3)/UNLOCK(key=b"123456") + +If we aren't interested in the DTO of an ECU, we can just send a CRO message like this: +Sending a CRO message:: + + pkt = CCP(identifier=0x700)/CRO(ctr=1)/CONNECT(station_address=0x02) + sock = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)) + sock.send(pkt) + +If we are interested in the DTO of an ECU, we need to set the basecls parameter of the +CANSocket to CCP and we need to use sr1: +Sending a CRO message:: + + cro = CCP(identifier=0x700)/CRO(ctr=0x53)/PROGRAM_6(data=b"\x10\x11\x12\x10\x11\x12") + sock = CANSocket(iface=can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000), basecls=CCP) + dto = sock.sr1(cro) + dto.show() + ###[ CAN Calibration Protocol ]### + flags= + identifier= 0x700 + length= 8 + reserved= 0 + ###[ DTO ]### + packet_id= 0xff + return_code= acknowledge / no error + ctr= 83 + ###[ PROGRAM_6_DTO ]### + MTA0_extension= 2 + MTA0_address= 0x34002006 + +Since sr1 calls the answers function, our payload of the DTO objects gets interpreted with the +command of our CRO object. + +ISOTP +----- + +ISOTP message +^^^^^^^^^^^^^ + +Creating an ISOTP message:: + + load_contrib('isotp') + ISOTP(src=0x241, dst=0x641, data=b"\x3eabc") + +Creating an ISOTP message with extended addressing:: + + ISOTP(src=0x241, dst=0x641, exdst=0x41, data=b"\x3eabc") + +Creating an ISOTP message with extended addressing:: + + ISOTP(src=0x241, dst=0x641, exdst=0x41, exsrc=0x41, data=b"\x3eabc") + +Create CAN-frames from an ISOTP message:: + + ISOTP(src=0x241, dst=0x641, exdst=0x41, exsrc=0x55, data=b"\x3eabc" * 10).fragment() + +Send ISOTP message over ISOTP socket:: + + isoTpSocket = ISOTPSocket('vcan0', sid=0x241, did=0x641) + isoTpMessage = ISOTP('Message') + isoTpSocket.send(isoTpMessage) + +Sniff ISOTP message:: + + isoTpSocket = ISOTPSocket('vcan0', sid=0x641, did=0x241) + packets = isoTpSocket.sniff(timeout=0.5) + +ISOTP MITM attack with bridge and sniff +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Set up two vcans on Linux terminal:: + + sudo modprobe vcan + sudo ip link add name vcan0 type vcan + sudo ip link add name vcan1 type vcan + sudo ip link set dev vcan0 up + sudo ip link set dev vcan1 up + +Set up ISOTP:: + +.. note:: + + First make sure you build an iso-tp kernel module. + +When the vcan core module is loaded with "sudo modprobe vcan" the iso-tp module can be loaded to the kernel. + +Therefore navigate to isotp directory, and load module with "sudo insmod ./net/can/can-isotp.ko". (Tested on Kernel 4.9.135-1-MANJARO) + +Detailed instructions you find in https://github.com/hartkopp/can-isotp. + +Import modules:: + + import threading + load_contrib('cansocket') + conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': True} + load_contrib('isotp') + +Create to ISOTP sockets for attack:: + + isoTpSocketVCan0 = ISOTPSocket('vcan0', sid=0x241, did=0x641) + isoTpSocketVCan1 = ISOTPSocket('vcan1', sid=0x641, did=0x241) + +Create function to send packet on vcan0 with threading:: + + def sendPacketWithISOTPSocket(): + sleep(0.2) + packet = ISOTP('Request') + isoTpSocketVCan0.send(packet) + +Create function to forward packet:: + + def forwarding(pkt): + return pkt + +Create function to bridge and sniff between two buses:: + + def bridge(): + bSocket0 = ISOTPSocket('vcan0', sid=0x641, did=0x241) + bSocket1 = ISOTPSocket('vcan1', sid=0x241, did=0x641) + bridge_and_sniff(if1=bSocket0, if2=bSocket1, xfrm12=forwarding, xfrm21=forwarding, timeout=1) + bSocket0.close() + bSocket1.close() + +Create threads for sending packet and to bridge and sniff:: + + threadBridge = threading.Thread(target=bridge) + threadSender = threading.Thread(target=sendPacketWithISOTPSocket) + +Start threads are based on Linux kernel modules. The python-can project is used to support CAN and CANSockets on other systems, besides Linux. This guide explains the hardware setup on a BeagleBone Black. The BeagleBone Black was chosen because of its two CAN interfaces on the main processor. The presence of two CAN interfaces in one device gives the possibility of CAN MITM attacks and session hijacking. The Cannelloni framework turns a BeagleBone Black into a CAN-to-UDP interface, which gives you the freedom to run Scapy on a more powerful machine.:: + + threadBridge.start() + threadSender.start() + +Sniff on vcan1:: + + receive = isoTpSocketVCan1.sniff(timeout=1) + +Close sockets:: + + isoTpSocketVCan0.close() + isoTpSocketVCan1.close() + +An ISOTPSocket will not respect ``src, dst, exdst, exsrc`` of an ISOTP message object. + +ISOTP Sockets +------------- + +Scapy provides two kinds of ISOTP Sockets. One implementation, the ISOTPNativeSocket +is using the Linux kernel module from Hartkopp. The other implementation, the ISOTPSoftSocket +is completely implemented in Python. This implementation can be used on Linux, +Windows, and OSX. + +ISOTPNativeSocket +^^^^^^^^^^^^^^^^^ + +**Requires:** + +* Python3 +* Linux +* Hartkopp's Linux kernel module: ``https://github.com/hartkopp/can-isotp.git`` + +During pentests, the ISOTPNativeSockets do have a better performance and +reliability, usually. If you are working on Linux, consider this implementation:: + + conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': True} + load_contrib('isotp') + sock = ISOTPSocket("can0", sid=0x641, did=0x241) + +Since this implementation is using a standard Linux socket, all Scapy functions +like ``sniff, sr, sr1, bridge_and_sniff`` work out of the box. + +ISOTPSoftSocket +^^^^^^^^^^^^^^^ + +ISOTPSoftSockets can use any CANSocket. This gives the flexibility to use all +python-can interfaces. Additionally, these sockets work on Python2 and Python3. +Usage on Linux with native CANSockets:: + + conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': False} + load_contrib('isotp') + with ISOTPSocket("can0", sid=0x641, did=0x241) as sock: + sock.send(...) + +Usage with python-can CANSockets:: + + conf.contribs['ISOTP'] = {'use-can-isotp-kernel-module': False} + conf.contribs['CANSocket'] = {'use-python-can': True} + load_contrib('isotp') + with ISOTPSocket(CANSocket(iface=python_can.interface.Bus(bustype='socketcan', channel="can0", bitrate=250000)), sid=0x641, did=0x241) as sock: + sock.send(...) + +This second example allows the usage of any ``python_can.interface`` object. + +**Attention:** The internal implementation of ISOTPSoftSockets requires a background +thread. In order to be able to close this thread properly, we suggest the use of +Pythons ``with`` statement. + + +UDS +--- + +The main usage of UDS is flashing and diagnostic of an ECU. UDS is an +application layer protocol and can be used as a DoIP or ENET payload or a UDS packet +can directly be sent over an ISOTPSocket. Every OEM has its own customization of UDS. +This increases the difficulty of generic applications and OEM specific knowledge is +required for penetration tests. RoutineControl jobs and ReadDataByIdentifier/WriteDataByIdentifier +services are heavily customized. + +Use the argument ``basecls=UDS`` on the ``init`` function of an ISOTPSocket. + +Here are two usage examples: + +.. image:: ../graphics/animations/animation-scapy-uds.svg +.. image:: ../graphics/animations/animation-scapy-uds2.svg + + +Customization of UDS_RDBI, UDS_WDBI +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In real-world use-cases, the UDS layer is heavily customized. OEMs define there own substructure of packets. +Especially the packets ReadDataByIdentifier or WriteDataByIdentifier have a very OEM or even ECU specific +substructure. Therefore a ``StrField`` ``dataRecord`` is not added to the ``field_desc``. +The intended usage is to create ECU or OEM specific description files, which extend the general UDS layer of +Scapy with further protocol implementations. + +Customization example:: + + cat scapy/contrib/automotive/OEM-XYZ/car-model-xyz.py + #! /usr/bin/env python + + # Protocol customization for car model xyz of OEM XYZ + # This file contains further OEM car model specific UDS additions. + + from scapy.packet import Packet + from scapy.contrib.automotive.uds import * + + # Define a new packet substructure + + class DBI_IP(Packet): + name = 'DataByIdentifier_IP_Packet' + fields_desc = [ + ByteField('ADDRESS_FORMAT_ID', 0), + IPField('IP', ''), + IPField('SUBNETMASK', ''), + IPField('DEFAULT_GATEWAY', '') + ] + + # Bind the new substructure onto the existing UDS packets + + bind_layers(UDS_RDBIPR, DBI_IP, dataIdentifier=0x172b) + bind_layers(UDS_WDBI, DBI_IP, dataIdentifier=0x172b) + + # Give add a nice name to dataIdentifiers enum + + UDS_RDBI.dataIdentifiers[0x172b] = 'GatewayIP' + +If one wants to work with this custom additions, these can be loaded at runtime to the Scapy interpreter:: + + >>> load_contrib("automotive.uds") + >>> load_contrib("automotive.OEM-XYZ.car-model-xyz") + + >>> pkt = UDS()/UDS_WDBI()/DBI_IP(IP='192.168.2.1', SUBNETMASK='255.255.255.0', DEFAULT_GATEWAY='192.168.2.1') + + >>> pkt.show() + ###[ UDS ]### + service= WriteDataByIdentifier + ###[ WriteDataByIdentifier ]### + dataIdentifier= GatewayIP + dataRecord= 0 + ###[ DataByIdentifier_IP_Packet ]### + ADDRESS_FORMAT_ID= 0 + IP= 192.168.2.1 + SUBNETMASK= 255.255.255.0 + DEFAULT_GATEWAY= 192.168.2.1 + + >>> hexdump(pkt) + 0000 2E 17 2B 00 C0 A8 02 01 FF FF FF 00 C0 A8 02 01 ..+............. + +.. image:: ../graphics/animations/animation-scapy-uds3.svg + +GMLAN +----- +GMLAN is very similar to UDS. It's GMs application layer protocol for +flashing, calibration and diagnostic of their cars. +Use the argument ``basecls=GMLAN`` on the ``init`` function of an ISOTPSocket. + +Usage example: + +.. image:: ../graphics/animations/animation-scapy-gmlan.svg + + +SOME/IP and SOME/IP SD messages +------------------------------- + +Creating a SOME/IP message +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This example shows a SOME/IP message which requests a service 0x1234 with the method 0x421. Different types of SOME/IP messages follow the same procedure and their specifications can be seen here ``http://www.some-ip.com/papers/cache/AUTOSAR_TR_SomeIpExample_4.2.1.pdf``. + + +Load the contribution:: + + load_contrib("automotive.someip") + +Create UDP package:: + + u = UDP(sport=30509, dport=30509) + +Create IP package:: + + i = IP(src="192.168.0.13", dst="192.168.0.10") + +Create SOME/IP package:: + + sip = SOMEIP() + sip.iface_ver = 0 + sip.proto_ver = 1 + sip.msg_type = "REQUEST" + sip.retcode = "E_OK" + sip.msg_id.srv_id = 0x1234 + sip.msg_id.method_id = 0x421 + +Add the payload:: + + sip.add_payload(Raw ("Hello")) + +Stack it and send it:: + + p = i/u/sip + send(p) + + +Creating a SOME/IP SD message +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In this example a SOME/IP SD offer service message is shown with an IPv4 endpoint. Different entries and options basically follow the same procedure as shown here and can be seen at ``https://www.autosar.org/fileadmin/user_upload/standards/classic/4-3/AUTOSAR_SWS_ServiceDiscovery.pdf``. + +Load the contribution:: + + load_contrib("automotive.someip_sd") + +Create UDP package:: + + u = UDP(sport=30490, dport=30490) + +The UDP port must be the one which was chosen for the SOME/IP SD transmission. + +Create IP package:: + + i = IP(src="192.168.0.13", dst="224.224.224.245") + +The IP source must be from the service and the destination address needs to be the chosen multicast address. + +Create the entry array input:: + + ea = SDEntry_Service() + + ea.type = 0x01 + ea.srv_id = 0x1234 + ea.inst_id = 0x5678 + ea.major_ver = 0x00 + ea.ttl = 3 + +Create the options array input:: + + oa = SDOption_IP4_Endpoint() + oa.addr = "192.168.0.13" + oa.l4_proto = 0x11 + oa.port = 30509 + +l4_proto defines the protocol for the communication with the endpoint, UDP in this case. + +Create the SD package and put in the inputs:: + + sd = SD() + sd.set_entryArray(ea) + sd.set_optionArray(oa) + spsd = sd.get_someip(True) + +The get_someip method stacks the SOMEIP/SD message on top of a SOME/IP message, which has the desired SOME/IP values prefilled for the SOME/IP SD package transmission. + +Stack it and send it:: + + p = i/u/spsd + send(p) + + + + +OBD message +------------- + +OBD is implemented on top of ISOTP. Use an ISOTPSocket for the communication with a ECU. +You should set the parameters ``basecls=OBD`` and ``padding=True`` in your ISOTPSocket init call. + +OBD is split into different service groups. Here are some example requests: + +Request supported PIDs of service 0x01:: + + req = OBD()/OBD_S01(pid=[0x00]) + +The response will contain a PacketListField, called `data_records`. This field contains the actual response:: + + resp = OBD()/OBD_S01_PR(data_records=[OBD_S01_PR_Record()/OBD_PID00(supported_pids=3196041235)]) + resp.show() + ###[ On-board diagnostics ]### + service= CurrentPowertrainDiagnosticDataResponse + ###[ Parameter IDs ]### + \data_records\ + |###[ OBD_S01_PR_Record ]### + | pid= 0x0 + |###[ PID_00_PIDsSupported ]### + | supported_pids= PID20+PID1F+PID1C+PID15+PID14+PID13+PID11+PID10+PID0F+PID0E+PID0D+PID0C+PID0B+PID0A+PID07+PID06+PID05+PID04+PID03+PID01 + +Let's assume our ECU under test supports the pid 0x15:: + + req = OBD()/OBD_S01(pid=[0x15]) + resp = sock.sr1(req) + resp.show() + ###[ On-board diagnostics ]### + service= CurrentPowertrainDiagnosticDataResponse + ###[ Parameter IDs ]### + \data_records\ + |###[ OBD_S01_PR_Record ]### + | pid= 0x15 + |###[ PID_15_OxygenSensor2 ]### + | outputVoltage= 1.275 V + | trim= 0 % + + +The different services in OBD support different kinds of data. +Service 01 and Service 02 support Parameter Identifiers (pid). +Service 03, 07 and 0A support Diagnostic Trouble codes (dtc). +Service 04 doesn't require a payload. +Service 05 is not implemented on OBD over CAN. +Service 06 support Monitoring Identifiers (mid). +Service 08 support Test Identifiers (tid). +Service 09 support Information Identifiers (iid). + +Examples: +^^^^^^^^^ + +Request supported Information Identifiers:: + + req = OBD()/OBD_S09(iid=[0x00]) + +Request the Vehicle Identification Number (VIN):: + + req = OBD()/OBD_S09(iid=0x02) + resp = sock.sr1(req) + resp.show() + ###[ On-board diagnostics ]### + service= VehicleInformationResponse + ###[ Infotype IDs ]### + \data_records\ + |###[ OBD_S09_PR_Record ]### + | iid= 0x2 + |###[ IID_02_VehicleIdentificationNumber ]### + | count= 1 + | vehicle_identification_numbers= ['W0L000051T2123456'] + + +.. image:: ../graphics/animations/animation-scapy-obd.svg + + +Test-Setup Tutorials +-------------------- + +Hardware Setup +^^^^^^^^^^^^^^ + +Beagle Bone Black Operating System Setup +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +#. | **Download an Image** + | The latest Debian Linux image can be found at the website + | ``https://beagleboard.org/latest-images``. Choose the BeagleBone + Black IoT version and download it. + + :: + + wget https://debian.beagleboard.org/images/bone-debian-8.7\ + -iot-armhf-2017-03-19-4gb.img.xz + + + After the download, copy it to an SD-Card with minimum of 4 GB storage. + + :: + + xzcat bone-debian-8.7-iot-armhf-2017-03-19-4gb.img.xz | \ + sudo dd of=/dev/xvdj + + +#. | **Enable WiFi** + | USB-WiFi dongles are well supported by Debian Linux. Login over SSH + on the BBB and add the WiFi network credentials to the file + ``/var/lib/connman/wifi.config``. If a USB-WiFi dongle is not + available, it is also possible to share the host's internet + connection with the Ethernet connection of the BBB emulated over + USB. A tutorial to share the host network connection can be found + on this page: + | ``https://elementztechblog.wordpress.com/2014/12/22/sharing-internet -using-network-over-usb-in-beaglebone-black/``. + | Login as root onto the BBB: + + :: + + ssh debian@192.168.7.2 + sudo su + + + Provide the WiFi login credentials to connman: + + :: + + echo "[service_home] + Type = wifi + Name = ssid + Security = wpa + Passphrase = xxxxxxxxxxxxx" \ + > /var/lib/connman/wifi.config + + + Restart the connman service: + + :: + + systemctl restart connman.service + + +Dual-CAN Setup +~~~~~~~~~~~~~~ + +#. | **Device tree setup** + | You'll need to follow this section only if you want to use two CAN + interfaces (DCAN0 and DCAN1). This will disable I2C2 from using pins + P9.19 and P9.20, which are needed by DCAN0. You only need to perform the + steps in this section once. + + | Warning: The configuration in this section will disable BBB capes from + working. Each cape has a small I2C EEPROM that stores info that the BBB + needs to know in order to communicate with the cape. Disable I2C2, and + the BBB has no way to talk to cape EEPROMs. Of course, if you don't use + capes then this is not a problem. + + | Acquire DTS sources that matches your kernel version. Go + `here `__ and switch over to the + branch that represents your kernel version. Download the entire branch + as a ZIP file. Extract it and do the following (version 4.1 shown as an + example): + + :: + + # cd ~/src/linux-4.1/arch/arm/boot/dts/include/ + # rm dt-bindings + # ln -s ../../../../../include/dt-bindings + # cd .. + Edit am335x-bone-common.dtsi and ensure the line with "//pinctrl-0 = <&i2c2_pins>;" is commented out. + Remove the complete &ocp section at the end of this file + # mv am335x-boneblack.dts am335x-boneblack.raw.dts + # cpp -nostdinc -I include -undef -x assembler-with-cpp am335x-boneblack.raw.dts > am335x-boneblack.dts + # dtc -W no-unit_address_vs_reg -O dtb -o am335x-boneblack.dtb -b 0 -@ am335x-boneblack.dts + # cp /boot/dtbs/am335x-boneblack.dtb /boot/dtbs/am335x-boneblack.orig.dtb + # cp am335x-boneblack.dtb /boot/dtbs/ + Reboot + +#. **Overlay setup** + | This section describes how to build the device overlays for the two CAN devices (DCAN0 and DCAN1). You only need to perform the steps in this section once. + | Acquire BBB cape overlays, in one of two ways… + + :: + + # apt-get install bb-cape-overlays + https://github.com/beagleboard/bb.org-overlays/ + + | Then do the following: + + + :: + + # cd ~/src/bb.org-overlays-master/src/arm + # ln -s ../../include + # mv BB-CAN1-00A0.dts BB-CAN1-00A0.raw.dts + # cp BB-CAN1-00A0.raw.dts BB-CAN0-00A0.raw.dts + Edit BB-CAN0-00A0.raw.dts and make relevant to CAN0. Example is shown below. + # cpp -nostdinc -I include -undef -x assembler-with-cpp BB-CAN0-00A0.raw.dts > BB-CAN0-00A0.dts + # cpp -nostdinc -I include -undef -x assembler-with-cpp BB-CAN1-00A0.raw.dts > BB-CAN1-00A0.dts + # dtc -W no-unit_address_vs_reg -O dtb -o BB-CAN0-00A0.dtbo -b 0 -@ BB-CAN0-00A0.dts + # dtc -W no-unit_address_vs_reg -O dtb -o BB-CAN1-00A0.dtbo -b 0 -@ BB-CAN1-00A0.dts + # cp *.dtbo /lib/firmware + + +#. | **CAN0 Example Overlay** + | Inside the DTS folder, create a file with the content of the + following listing. + + :: + + cd ~/bb.org-overlays/src/arm + cat < BB-CAN0-00A0.raw.dts + + /* + * Copyright (C) 2015 Robert Nelson + * + * Virtual cape for CAN0 on connector pins P9.19 P9.20 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + /dts-v1/; + /plugin/; + + #include + #include + + / { + compatible = "ti,beaglebone", "ti,beaglebone-black", "ti,beaglebone-green"; + + /* identification */ + part-number = "BB-CAN0"; + version = "00A0"; + + /* state the resources this cape uses */ + exclusive-use = + /* the pin header uses */ + "P9.19", /* can0_rx */ + "P9.20", /* can0_tx */ + /* the hardware ip uses */ + "dcan0"; + + fragment@0 { + target = <&am33xx_pinmux>; + __overlay__ { + bb_dcan0_pins: pinmux_dcan0_pins { + pinctrl-single,pins = < + BONE_P9_19 (PIN_INPUT_PULLUP | MUX_MODE2) /* uart1_txd.d_can0_rx */ + BONE_P9_20 (PIN_OUTPUT_PULLUP | MUX_MODE2) /* uart1_rxd.d_can0_tx */ + >; + }; + }; + }; + + fragment@1 { + target = <&dcan0>; + __overlay__ { + status = "okay"; + pinctrl-names = "default"; + pinctrl-0 = <&bb_dcan0_pins>; + }; + }; + }; + EOF + + +#. | **Test the Dual-CAN Setup** + | Do the following each time you need CAN, or automate these steps if you like. + + :: + + # echo BB-CAN0 > /sys/devices/platform/bone_capemgr/slots + # echo BB-CAN1 > /sys/devices/platform/bone_capemgr/slots + # modprobe can + # modprobe can-dev + # modprobe can-raw + # ip link set can0 up type can bitrate 50000 + # ip link set can1 up type can bitrate 50000 + + Check the output of the Capemanager if both CAN interfaces have been + loaded. + + :: + + cat /sys/devices/platform/bone_capemgr/slots + + 0: PF---- -1 + 1: PF---- -1 + 2: PF---- -1 + 3: PF---- -1 + 4: P-O-L- 0 Override Board Name,00A0,Override Manuf, BB-CAN0 + 5: P-O-L- 1 Override Board Name,00A0,Override Manuf, BB-CAN1 + + + If something went wrong, ``dmesg`` provides kernel messages to analyse the root of failure. + +#. | **References** + + - `embedded-things.com: Enable CANbus on the Beaglebone + Black `__ + - `electronics.stackexchange.com: Beaglebone Black CAN bus + Setup `__ + +#. | **Acknowledgment** + | Thanks to Tom Haramori. Parts of this section are copied from his guide: https://github.com/haramori/rhme3/blob/master/Preparation/BBB_CAN_setup.md + + + +ISO-TP Kernel Module Installation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A Linux ISO-TP kernel module can be downloaded from this website: +``https://github.com/hartkopp/can-isotp.git``. The file +``README.isotp`` in this repository provides all information and +necessary steps for downloading and building this kernel module. The +ISO-TP kernel module should also be added to the ``/etc/modules`` file, +to load this module automatically at system boot of the BBB. + +CAN-Interface Setup +~~~~~~~~~~~~~~~~~~~ + +As the final step to prepare the BBB's CAN interfaces for usage, these +interfaces have to be set up through some terminal commands. The bitrate +can be chosen to fit the bitrate of a CAN bus under test. + +:: + + ip link set can0 up type can bitrate 500000 + ip link set can1 up type can bitrate 500000 + +Raspberry Pi SOME/IP setup +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To build a small test environment in which you can send SOME/IP messages to and from server instances or disguise yourself as a server, one Raspberry Pi, your laptop and the vsomeip library are sufficient. + +#. | **Download image** + + Download the latest raspbian image (``https://www.raspberrypi.org/downloads/raspbian/``) and install it on the Raspberry. + +#. | **Vsomeip setup** + + Download the vsomeip library on the Rapsberry, apply the git patch so it can work with the newer boost libraries and then install it. + + :: + + git clone https://github.com/GENIVI/vsomeip.git + cd vsomeip + wget -O 0001-Support-boost-v1.66.patch.zip \ + https://github.com/GENIVI/vsomeip/files/2244890/0001-Support-boost-v1.66.patch.zip + unzip 0001-Support-boost-v1.66.patch.zip + git apply 0001-Support-boost-v1.66.patch + mkdir build + cd build + cmake -DENABLE_SIGNAL_HANDLING=1 .. + make + make install + +#. | **Make applications** + + Write some small applications which function as either a service or a client and use the Scapy SOME/IP implementation to communicate with the client or the server. Examples for vsomeip applications are available on the vsomeip github wiki page (``https://github.com/GENIVI/vsomeip/wiki/vsomeip-in-10-minutes``). + + + +Software Setup +^^^^^^^^^^^^^^ + +Cannelloni Framework Installation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Cannelloni framework is a small application written in C++ to +transfer CAN data over UDP. In this way, a researcher can map the CAN +communication of a remote device to its workstation, or even combine +multiple remote CAN devices on his machine. The framework can be +downloaded from this website: +``https://github.com/mguentner/cannelloni.git``. The ``README.md`` file +explains the installation and usage in detail. Cannelloni needs virtual +CAN interfaces on the operator's machine. The next listing shows the +setup of virtual CAN interfaces. + +:: + + modprobe vcan + + ip link add name vcan0 type vcan + ip link add name vcan1 type vcan + + ip link set dev vcan0 up + ip link set dev vcan1 up + + tc qdisc add dev vcan0 root tbf rate 300kbit latency 100ms burst 1000 + tc qdisc add dev vcan1 root tbf rate 300kbit latency 100ms burst 1000 + + cannelloni -I vcan0 -R -r 20000 -l 20000 & + cannelloni -I vcan1 -R -r 20001 -l 20001 & + diff --git a/doc/scapy/bluetooth.rst b/doc/scapy/layers/bluetooth.rst similarity index 99% rename from doc/scapy/bluetooth.rst rename to doc/scapy/layers/bluetooth.rst index 59645b6e0ce..091036dad92 100644 --- a/doc/scapy/bluetooth.rst +++ b/doc/scapy/layers/bluetooth.rst @@ -5,7 +5,7 @@ Bluetooth .. note:: If you're new to using Scapy, start with the :doc:`usage documentation - `, which describes how to use Scapy with Ethernet and IP. + <../usage>`, which describes how to use Scapy with Ethernet and IP. .. warning:: @@ -407,7 +407,7 @@ __ https://github.com/google/eddystone/tree/master/eddystone-url Once :ref:`advertising has been started `, the beacon may then be detected with the `Eddystone Validator`__ (Android): -.. image:: graphics/ble_eddystone_url.png +.. image:: ../graphics/ble_eddystone_url.png __ https://github.com/google/eddystone/tree/master/tools/eddystone-validator diff --git a/doc/scapy/layers/index.rst b/doc/scapy/layers/index.rst new file mode 100644 index 00000000000..5508057d578 --- /dev/null +++ b/doc/scapy/layers/index.rst @@ -0,0 +1,6 @@ +.. Layer-specific documentation + +.. toctree:: + :glob: + + * \ No newline at end of file diff --git a/doc/scapy/layers/pnio.rst b/doc/scapy/layers/pnio.rst new file mode 100644 index 00000000000..b3b37486575 --- /dev/null +++ b/doc/scapy/layers/pnio.rst @@ -0,0 +1,269 @@ +*************** +PROFINET IO RTC +*************** + +PROFINET IO is an industrial protocol composed of different layers such as the Real-Time Cyclic (RTC) layer, used to exchange data. However, this RTC layer is stateful and depends on a configuration sent through another layer: the DCE/RPC endpoint of PROFINET. This configuration defines where each exchanged piece of data must be located in the RTC ``data`` buffer, as well as the length of this same buffer. Building such packet is then a bit more complicated than other protocols. + +RTC data packet +--------------- + +The first thing to do when building the RTC ``data`` buffer is to instantiate each Scapy packet which represents a piece of data. Each one of them may require some specific piece of configuration, such as its length. All packets and their configuration are: + +* ``PNIORealTimeRawData``: a simple raw data like ``Raw`` + + * ``length``: defines the length of the data + +* ``Profisafe``: the PROFIsafe profile to perform functional safety + + * ``length``: defines the length of the whole packet + * ``CRC``: defines the length of the CRC, either ``3`` or ``4`` + +* ``PNIORealTimeIOxS``: either an IO Consumer or Provider Status byte + + * Doesn't require any configuration + +To instantiate one of these packets with its configuration, the ``config`` argument must be given. It is a ``dict()`` which contains all the required piece of configuration:: + + >>> load_contrib('pnio_rtc') + >>> raw(PNIORealTimeRawData(load='AAA', config={'length': 4})) + 'AAA\x00' + >>> raw(Profisafe(load='AAA', Control_Status=0x20, CRC=0x424242, config={'length': 8, 'CRC': 3})) + 'AAA\x00 BBB' + >>> hexdump(PNIORealTimeIOxS()) + 0000 80 . + + +RTC packet +---------- + +Now that a data packet can be instantiated, a whole RTC packet may be built. ``PNIORealTime`` contains a field ``data`` which is a list of all data packets to add in the buffer, however, without the configuration, Scapy won't be +able to dissect it:: + + >>> load_contrib("pnio_rtc") + >>> p=PNIORealTime(cycleCounter=1024, data=[ + ... PNIORealTimeIOxS(), + ... PNIORealTimeRawData(load='AAA', config={'length':4}) / PNIORealTimeIOxS(), + ... Profisafe(load='AAA', Control_Status=0x20, CRC=0x424242, config={'length': 8, 'CRC': 3}) / PNIORealTimeIOxS(), + ... ]) + >>> p.show() + ###[ PROFINET Real-Time ]### + len= None + dataLen= None + \data\ + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0 + | extension= 0 + |###[ PNIO RTC Raw data ]### + | load= 'AAA' + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0 + | extension= 0 + |###[ PROFISafe ]### + | load= 'AAA' + | Control_Status= 0x20 + | CRC= 0x424242 + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0 + | extension= 0 + padding= '' + cycleCounter= 1024 + dataStatus= primary+validData+run+no_problem + transferStatus= 0 + + >>> p.show2() + ###[ PROFINET Real-Time ]### + len= 44 + dataLen= 15 + \data\ + |###[ PNIO RTC Raw data ]### + | load= '\x80AAA\x00\x80AAA\x00 BBB\x80' + padding= '' + cycleCounter= 1024 + dataStatus= primary+validData+run+no_problem + transferStatus= 0 + +For Scapy to be able to dissect it correctly, one must also configure the layer for it to know the location of each data in the buffer. This configuration is saved in the dictionary ``conf.contribs["PNIO_RTC"]`` which can be updated with the ``pnio_update_config`` method. Each item in the dictionary uses the tuple ``(Ether.src, Ether.dst)`` as key, to be able to separate the configuration of each communication. Each value is then a list of a tuple which describes a data packet. It is composed of the negative index, from the end of the data buffer, of the packet position, the class of the packet as the second item and the ``config`` dictionary to provide to the class as last. If we continue the previous example, here is the configuration to set:: + + >>> load_contrib("pnio") + >>> e=Ether(src='00:01:02:03:04:05', dst='06:07:08:09:0a:0b') / ProfinetIO() / p + >>> e.show2() + ###[ Ethernet ]### + dst= 06:07:08:09:0a:0b + src= 00:01:02:03:04:05 + type= 0x8892 + ###[ ProfinetIO ]### + frameID= RT_CLASS_1 + ###[ PROFINET Real-Time ]### + len= 44 + dataLen= 15 + \data\ + |###[ PNIO RTC Raw data ]### + | load= '\x80AAA\x00\x80AAA\x00 BBB\x80' + padding= '' + cycleCounter= 1024 + dataStatus= primary+validData+run+no_problem + transferStatus= 0 + >>> pnio_update_config({('00:01:02:03:04:05', '06:07:08:09:0a:0b'): [ + ... (-9, Profisafe, {'length': 8, 'CRC': 3}), + ... (-9 - 5, PNIORealTimeRawData, {'length':4}), + ... ]}) + >>> e.show2() + ###[ Ethernet ]### + dst= 06:07:08:09:0a:0b + src= 00:01:02:03:04:05 + type= 0x8892 + ###[ ProfinetIO ]### + frameID= RT_CLASS_1 + ###[ PROFINET Real-Time ]### + len= 44 + dataLen= 15 + \data\ + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + |###[ PNIO RTC Raw data ]### + | load= 'AAA' + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + |###[ PROFISafe ]### + | load= 'AAA' + | Control_Status= 0x20 + | CRC= 0x424242L + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + padding= '' + cycleCounter= 1024 + dataStatus= primary+validData+run+no_problem + transferStatus= 0 + +If no data packets are configured for a given offset, it defaults to a ``PNIORealTimeIOxS``. However, this method is not very convenient for the user to configure the layer and it only affects the dissection of packets. In such cases, one may have access to several RTC packets, sniffed or retrieved from a PCAP file. Thus, ``PNIORealTime`` provides some methods to analyse a list of ``PNIORealTime`` packets and locate all data in it, based on simple heuristics. All of them take as first argument an iterable which contains the list of packets to analyse. + +* ``PNIORealTime.find_data()`` analyses the data buffer and separate real data from IOxS. It returns a dict which can be provided to ``pnio_update_config``. +* ``PNIORealTime.find_profisafe()`` analyses the data buffer and find the PROFIsafe profiles among the real data. It returns a dict which can be provided to ``pnio_update_config``. +* ``PNIORealTime.analyse_data()`` executes both previous methods and update the configuration. **This is usually the method to call.** +* ``PNIORealTime.draw_entropy()`` will draw the entropy of each byte in the data buffer. It can be used to easily visualize PROFIsafe locations as entropy is the base of the decision algorithm of ``find_profisafe``. + +:: + + >>> load_contrib('pnio_rtc') + >>> t=rdpcap('/path/to/trace.pcap', 1024) + >>> PNIORealTime.analyse_data(t) + {('00:01:02:03:04:05', '06:07:08:09:0a:0b'): [(-19, , {'length': 1}), (-15, , {'CRC': 3, 'length': 6}), (-7, , {'CRC': 3, 'length': 5})]} + >>> t[100].show() + ###[ Ethernet ]### + dst= 06:07:08:09:0a:0b + src= 00:01:02:03:04:05 + type= n_802_1Q + ###[ 802.1Q ]### + prio= 6L + id= 0L + vlan= 0L + type= 0x8892 + ###[ ProfinetIO ]### + frameID= RT_CLASS_1 + ###[ PROFINET Real-Time ]### + len= 44 + dataLen= 22 + \data\ + |###[ PNIO RTC Raw data ]### + | load= '\x80\x80\x80\x80\x80\x80\x00\x80\x80\x80\x12:\x0e\x12\x80\x80\x00\x12\x8b\x97\xe3\x80' + padding= '' + cycleCounter= 6208 + dataStatus= primary+validData+run+no_problem + transferStatus= 0 + + >>> t[100].show2() + ###[ Ethernet ]### + dst= 06:07:08:09:0a:0b + src= 00:01:02:03:04:05 + type= n_802_1Q + ###[ 802.1Q ]### + prio= 6L + id= 0L + vlan= 0L + type= 0x8892 + ###[ ProfinetIO ]### + frameID= RT_CLASS_1 + ###[ PROFINET Real-Time ]### + len= 44 + dataLen= 22 + \data\ + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + [...] + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + |###[ PNIO RTC Raw data ]### + | load= '' + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + [...] + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + |###[ PROFISafe ]### + | load= '' + | Control_Status= 0x12 + | CRC= 0x3a0e12L + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + |###[ PROFISafe ]### + | load= '' + | Control_Status= 0x12 + | CRC= 0x8b97e3L + |###[ PNIO RTC IOxS ]### + | dataState= good + | instance= subslot + | reserved= 0x0L + | extension= 0L + padding= '' + cycleCounter= 6208 + dataStatus= primary+validData+run+no_problem + transferStatus= 0 + +In addition, one can see, when displaying a ``PNIORealTime`` packet, the field ``len``. This is a computed field which is not added in the final packet build. It is mainly useful for dissection and reconstruction, but it can also be used to modify the behaviour of the packet. In fact, RTC packet must always be long enough for an Ethernet frame and to do so, a padding must be added right after the ``data`` buffer. The default behaviour is to add ``padding`` whose size is computed during the ``build`` process:: + + >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()])) + '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' + +However, one can set ``len`` to modify this behaviour. ``len`` controls the length of the whole ``PNIORealTime`` packet. Then, to shorten the length of the padding, ``len`` can be set to a lower value:: + + >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()], len=50)) + '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' + >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()])) + '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' + >>> raw(PNIORealTime(cycleCounter=0x4242, data=[PNIORealTimeIOxS()], len=30)) + '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00' diff --git a/doc/scapy/layers/sctp.rst b/doc/scapy/layers/sctp.rst new file mode 100644 index 00000000000..12d96dbc6c0 --- /dev/null +++ b/doc/scapy/layers/sctp.rst @@ -0,0 +1,27 @@ +**** +SCTP +**** + +SCTP is a relatively young transport-layer protocol combining both TCP and UDP characteristics. The `RFC 3286 `_ introduces it and its description lays in the `RFC 4960 `_. + +It is not broadly used, its mainly present in core networks operated by telecommunication companies, to support VoIP for instance. + + +Enabling dynamic addressing reconfiguration and chunk authentication capabilities +--------------------------------------------------------------------------------- + +If you are trying to discuss with SCTP servers, you may be interested in capabilities added in `RFC 4895 `_ which describe how to authenticated some SCTP chunks, and/or `RFC 5061 `_ to dynamically reconfigure the IP address of a SCTP association. + +These capabilities are not always enabled by default on Linux. Scapy does not need any modification on its end, but SCTP servers may need specific activation. + +To enable the RFC 4895 about authenticating chunks:: + + $ sudo echo 1 > /proc/sys/net/sctp/auth_enable + +To enable the RFC 5061 about dynamic address reconfiguration:: + + $ sudo echo 1 > /proc/sys/net/sctp/addip_enable + +You may also want to use the dynamic address reconfiguration without necessarily enabling the chunk authentication:: + + $ sudo echo 1 > /proc/sys/net/sctp/addip_noauth_enable \ No newline at end of file diff --git a/doc/scapy/usage.rst b/doc/scapy/usage.rst index 9c7840c5622..4dbd4fa4345 100644 --- a/doc/scapy/usage.rst +++ b/doc/scapy/usage.rst @@ -27,14 +27,6 @@ some features will not be available:: The basic features of sending and receiving packets should still work, though. -Screenshot ----------- - -If you have installed IPython (highly recommended), Scapy will hook to it and you will be able to use auto-completion using the TAB. - -.. image:: graphics/scapy-main-console.png - :align: center - Customizing the Terminal ------------------------ diff --git a/doc/scapy_version_timeline.ods b/doc/scapy_version_timeline.ods new file mode 100644 index 00000000000..10e0bca6960 Binary files /dev/null and b/doc/scapy_version_timeline.ods differ diff --git a/scapy/arch/pcapdnet.py b/scapy/arch/pcapdnet.py index c336b5d85d6..646e43a91e6 100644 --- a/scapy/arch/pcapdnet.py +++ b/scapy/arch/pcapdnet.py @@ -159,9 +159,11 @@ def load_winpcapy(): except OSError: conf.use_winpcapy = False if conf.interactive: - log_loading.warning("wpcap.dll is not installed. " - "Restricted mode enabled ! " - "Visit the Scapy's doc to install it") + log_loading.warning(conf.color_theme.format( + "Npcap/Winpcap is not installed ! See " + "https://scapy.readthedocs.io/en/latest/installation.html#windows", # noqa: E501 + "black+bg_red" + )) if conf.use_winpcapy: def get_if_list(): diff --git a/scapy/arch/windows/__init__.py b/scapy/arch/windows/__init__.py index 630240db0d9..f476e8be27c 100755 --- a/scapy/arch/windows/__init__.py +++ b/scapy/arch/windows/__init__.py @@ -593,6 +593,10 @@ class NetworkInterfaceDict(UserDict): @classmethod def _pcap_check(cls): """Performs checks/restart pcap adapter""" + if not conf.use_winpcapy: + # Winpcap/Npcap isn't installed + return + _detect = pcap_service_status() def _ask_user(): diff --git a/scapy/themes.py b/scapy/themes.py index c81712d70cd..be64aaa663a 100644 --- a/scapy/themes.py +++ b/scapy/themes.py @@ -17,7 +17,7 @@ class ColorTable: colors = { # Format: (ansi, pygments) - "normal": ("\033[0m", "noinherit"), + # foreground "black": ("\033[30m", "#ansiblack"), "red": ("\033[31m", "#ansired"), "green": ("\033[32m", "#ansigreen"), @@ -25,8 +25,20 @@ class ColorTable: "blue": ("\033[34m", "#ansiblue"), "purple": ("\033[35m", "#ansipurple"), "cyan": ("\033[36m", "#ansicyan"), - "grey": ("\033[37m", "#ansigrey"), - + "grey": ("\033[37m", "#ansiwhite"), + "reset": ("\033[39m", "noinherit"), + # background + "bg_black": ("\033[40m", "bg:#ansiblack"), + "bg_red": ("\033[41m", "bg:#ansired"), + "bg_green": ("\033[42m", "bg:#ansigreen"), + "bg_yellow": ("\033[43m", "bg:#ansiyellow"), + "bg_blue": ("\033[44m", "bg:#ansiblue"), + "bg_purple": ("\033[45m", "bg:#ansipurple"), + "bg_cyan": ("\033[46m", "bg:#ansicyan"), + "bg_grey": ("\033[47m", "bg:#ansiwhite"), + "bg_reset": ("\033[49m", "noinherit"), + # specials + "normal": ("\033[0m", "noinherit"), # color & brightness "bold": ("\033[1m", "bold"), "uline": ("\033[4m", "underline"), "blink": ("\033[5m", ""), @@ -73,6 +85,11 @@ def __getattr__(self, attr): raise AttributeError() return create_styler() + def format(self, string, fmt): + for style in fmt.split("+"): + string = getattr(self, style)(string) + return string + class NoTheme(ColorTheme): pass @@ -88,7 +105,9 @@ def __getattr__(self, attr): after = self.style_normal elif not isinstance(self, BlackAndWhite) and attr in Color.colors: before = Color.colors[attr][0] - after = self.style_normal + after = "".join(Color.colors[x][0] for x in [ + "normal", "reset", "bg_reset" + ]) else: before = after = "" diff --git a/tox.ini b/tox.ini index 0f6765f25bf..aaceb169ee1 100644 --- a/tox.ini +++ b/tox.ini @@ -101,7 +101,7 @@ commands = sphinx-build -W . _build/html [testenv:spell] deps = codespell # inet6, dhcp6 and the ipynb files contains french: ignore them -commands = codespell --ignore-words=.travis/codespell_ignore.txt --skip="*.pyc,*.png,*.raw,*.pdf,*.pcap,*.js,*.html,*.der,*_build*,*inet6.py,*dhcp6.py,*.ipynb,*.svg" scapy/ doc/ test/ .github/ +commands = codespell --ignore-words=.travis/codespell_ignore.txt --skip="*.pyc,*.png,*.raw,*.pdf,*.pcap,*.js,*.html,*.der,*_build*,*inet6.py,*dhcp6.py,*.ipynb,*.svg,*.gif,*.obs" scapy/ doc/ test/ .github/ [testenv:twine] description = "Check Scapy code distribution"