### Starting an SMB Server with NTLM Authentication Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Configure and start an SMB server using Scapy's SMB_Server class, specifying shares and NTLM authentication for multiple users. This example demonstrates setting up a basic SMB server. ```python smbserver( shares=[SMBShare(name="Scapy", path="/tmp")], iface="eth0", ssp=NTLMSSP( IDENTITIES={ ``` -------------------------------- ### Vsomeip Setup on Raspberry Pi Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/automotive.rst Steps to clone the vsomeip repository, apply a patch for newer boost libraries, build, and install it. This is part of setting up a test environment for SOME/IP messages. ```bash 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 ``` -------------------------------- ### XCP Scanner Command-Line Examples Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/automotive.rst Examples of how to use the xcpscanner tool from the command line to scan for automotive ECUs. ```bash python3.6 -m scapy.tools.automotive.xcpscanner can0 ``` ```bash python3.6 -m scapy.tools.automotive.xcpscanner can0 -b 500 ``` ```bash python3.6 -m scapy.tools.automotive.xcpscanner can0 -s 50 -e 100 ``` ```bash python3.6 -m scapy.tools.automotive.xcpscanner can0 -b 500 -v ``` -------------------------------- ### Setup CAN Interfaces Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/automotive.rst Commands to bring up CAN interfaces with a specified bitrate. Ensure the bitrate matches the CAN bus under test. ```bash ip link set can0 up type can bitrate 500000 ip link set can1 up type can bitrate 500000 ``` -------------------------------- ### Install libpcap on OpenBSD Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Installs the libpcap package on OpenBSD systems using pkg_add. ```text $ doas pkg_add libpcap ``` -------------------------------- ### Install Scapy via Pip or Source Source: https://context7.com/secdev/scapy/llms.txt Install Scapy using pip for Python 3.7+ or clone from source. Run as root/administrator for raw socket access. Optional extras can be installed with `pip install scapy[all]`. ```bash pip install scapy ``` ```bash git clone https://github.com/secdev/scapy cd scapy ./run_scapy # interactive shell ``` ```bash pip install scapy[all] ``` -------------------------------- ### Start Monitor Mode on Linux with airmon-ng Source: https://github.com/secdev/scapy/blob/master/doc/scapy/troubleshooting.rst Use the 'airmon-ng' utility to start monitor mode on a specified wireless interface on Linux. ```bash $ sudo airmon-ng start wlan0 ``` -------------------------------- ### NetlogonClient Example Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/dcerpc.rst Shows how to use the NetlogonClient for network logon operations, including authentication and session key negotiation. ```APIDOC ## NetlogonClient Example ### Description This example demonstrates the usage of `NetlogonClient`, an extension of `DCERPC_Client` that implements its own `NetlogonSSP` for network logon authentication. ### Usage ```python from scapy.layers.msrpce.msnrpc import * from scapy.layers.msrpce.raw.ms_nrpc import * client = NetlogonClient( auth_level=DCE_C_AUTHN_LEVEL.PKT_PRIVACY, computername="SERVER", domainname="DOMAIN", ) client.connect_and_bind("192.168.0.100") client.negotiate_sessionkey(bytes.fromhex("77777777777777777777777777777777")) client.close() ``` ``` -------------------------------- ### Install libpcap on Debian/Ubuntu Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Installs the libpcap development package on Debian-based systems using apt-get. ```text $ sudo apt-get install libpcap-dev ``` -------------------------------- ### HTTP_Server: Basic Implementation Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/http.rst Provides a basic example of creating a custom HTTP_Server that responds to requests. ```APIDOC ## HTTP_Server: Basic Implementation ### Description An example of a custom HTTP server automaton that defines how to answer incoming HTTP requests. ### Method `answer(pkt)` ### Parameters - **pkt** (object) - The incoming HTTP request packet. ### Request Example ```python from scapy.layers.http import * from scapy.layers.ntlm import * class Custom_HTTP_Server(HTTP_Server): def answer(self, pkt): if pkt.Path == b"/": return HTTPResponse() / ( ``` ``` -------------------------------- ### Install libpcap on Fedora Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Installs the libpcap development package on Fedora systems using yum. ```text $ yum install libpcap-devel ``` -------------------------------- ### HTTP_Client: Simple GET Request Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/http.rst Demonstrates how to use the HTTP_Client to send a simple GET request to a local HTTP server. ```APIDOC ## HTTP_Client: Simple GET Request ### Description Sends a simple GET request to a specified HTTP server and retrieves the response. ### Method `request(url)` ### Parameters - **url** (string) - The URL of the HTTP server to connect to (e.g., "http://127.0.0.1:8080"). ### Request Example ```python from scapy.layers.http import * client = HTTP_Client() resp = client.request("http://127.0.0.1:8080") client.close() ``` ``` -------------------------------- ### Start PipeEngine and Send Data Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/pipetools.rst This snippet demonstrates starting a PipeEngine and sending data through different sources (lower and higher canals) to observe how it's processed by linked drains and sinks. ```pycon p.start() s.send("foo") s2.send("bar") s.send("i like potato") print(si2.recv(), ":", si2.recv()) ``` -------------------------------- ### UTScapy Test Campaign Structure Example Source: https://github.com/secdev/scapy/blob/master/doc/scapy/development.rst This example demonstrates the generic format for a test campaign, including campaign name, comments, test sets, unit tests, keywords, and Python code execution. ```text % Test Campaign Name * Comment describing this campaign + Test Set 1 * comments for test set 1 = Unit Test 1 ~ keywords * Comments for unit test 1 # Python statements follow a = 1 print(a) a == 1 ``` -------------------------------- ### UDS Default Multi-Layer Mode Example Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/automotive.rst Demonstrates the default multi-layer mode for UDS, where services are nested. ```python pkt = UDS() / UDS_DSC(diagnosticSessionType=0x01) UDS(b'\x10\x01') ``` -------------------------------- ### Start Bluetooth LE Advertising Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/bluetooth.rst Use this command to enable Bluetooth Low Energy advertising. Ensure advertising has been previously started. ```python3 bt.sr(HCI_Hdr()/ HCI_Command_Hdr()/ HCI_Cmd_LE_Set_Advertise_Enable(enable=True)) ``` -------------------------------- ### ISOTP Scanner Command-Line Usage Examples Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/automotive.rst Examples of how to use the isotpscanner tool from the command line for different operating systems and interfaces. Ensure the correct python interpreter (python2 or python3) and interface parameters are used. ```bash python2 -m scapy.tools.automotive.isotpscanner --interface=pcan --channel=PCAN_USBBUS1 --bitrate=250000 --start 0 --end 100 ``` ```bash python2 -m scapy.tools.automotive.isotpscanner --interface vector --channel 0 --bitrate 250000 --start 0 --end 100 ``` ```bash python2 -m scapy.tools.automotive.isotpscanner --interface socketcan --channel=can0 --bitrate=250000 --start 0 --end 100 ``` ```bash python3 -m scapy.tools.automotive.isotpscanner --channel can0 --start 0 --end 100 ``` -------------------------------- ### Packet Construction Example Source: https://github.com/secdev/scapy/blob/master/doc/scapy/build_dissect.rst Demonstrates the default behavior when combining layers without explicit binding, leading to incorrect dissection. ```python p = Foo()/Bar1(val=1337) p p.show2() ``` -------------------------------- ### Install Scapy from Source Source: https://github.com/secdev/scapy/blob/master/README.md Clone the Scapy repository and run the interactive shell. This method is suitable for development or when the latest version is needed. ```bash git clone https://github.com/secdev/scapy cd scapy ./run_scapy ``` -------------------------------- ### Clone Scapy and Run Source: https://github.com/secdev/scapy/blob/master/doc/notebooks/Scapy in 15 minutes.ipynb Clone the Scapy repository and run the provided script as root to start using Scapy interactively. ```shell git clone https://github.com/secdev/scapy --depth=1 sudo ./run_scapy Welcome to Scapy (2.4.0) >>> ``` -------------------------------- ### Basic TriggerDrain Usage Example Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/pipetools.rst Demonstrates the setup and basic operation of TriggerDrain and TriggeredValve for conditional message processing. The PipeEngine must be started and stopped. ```pycon >>> a = CLIFeeder() >>> d = TriggerDrain(lambda msg: True) # Pass messages and trigger when a condition is met >>> d2 = TriggeredValve() >>> s = ConsoleSink() >>> a > d > d2 > s >>> d ^ d2 # Link the triggers >>> p = PipeEngine(s) >>> p.start() INFO: Pipe engine thread started. >>> >>> a.send("this will be printed") >'this will be printed' >>> a.send("this won't, because the valve was switched") >>> a.send("this will, because the valve was switched again") >'this will, because the valve was switched again' >>> p.stop() ``` -------------------------------- ### Create and Show SNMP Packet Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/asn1_snmp.rst Demonstrates creating an SNMP packet with a GET PDU and a list of variable bindings, then displaying its structure. ```python a=SNMP(version=3, PDU=SNMPget(varbindlist=[SNMPvarbind(oid="1.2.3",value=5), SNMPvarbind(oid="3.2.1",value="hello")])) a.show() ``` -------------------------------- ### TFTP Client Initial State Setup Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/automaton.rst Sets up the initial state for the TFTP read client automaton, configuring block size and a random source port if not provided. ```python @ATMT.state(initial=1) def BEGIN(self): self.blocksize=512 self.my_tid = self.sport or RandShort()._fix() ``` -------------------------------- ### Plotting Packet Data with Matplotlib Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst This example demonstrates how to plot packet data using Scapy's plot() method, which requires Matplotlib to be installed. ```python >>> p=sniff(count=50) >>> p.plot(lambda x:len(x)) ``` -------------------------------- ### Programmatic SMB Client Initialization and Share Listing Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Initialize the SMB client programmatically without CLI mode and list available shares. Ensure the client has necessary credentials for session setup. ```python >>> from scapy.layers.smbclient import smbclient >>> cli = smbclient("server1.domain.local", "Administrator@domain.local", password="password", cli=False) >>> shares = cli.shares() >>> shares [('ADMIN$', 'DISKTREE', 'Remote Admin'), ('C$', 'DISKTREE', 'Default share'), ('common', 'DISKTREE', ''), ('IPC$', 'IPC', 'Remote IPC'), ('NETLOGON', 'DISKTREE', 'Logon server share '), ('SYSVOL', 'DISKTREE', 'Logon server share '), ('Users', 'DISKTREE', '')] >>> cli.use('c$') >>> cli.cd(r'Program Files\Microsoft') >>> names = [x[0] for x in cli.ls()] >>> names ['.', '..', 'EdgeUpdater'] ``` -------------------------------- ### Setup Mobile Originated Call Packet Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Initiates the construction of a GSM UM packet for mobile-originated calls. This function serves as a starting point, with parameters for optional Information Elements. ```python def setupMobileOriginated(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Facility_presence=0, CallingPartySubaddress_presence=0, CalledPartyBcdNumber_presence=0, CalledPartySubaddress_presence=0, RepeatIndicator_presence1=0, LowLayerCompatibility_presence=0, LowLayerCompatibility_presence1=0, RepeatIndicator_presence2=0, HighLayerCompatibility_presence=0, HighLayerCompatibility_presence1=0, UserUser_presence=0, SsVersionIndicator_presence=0, ``` -------------------------------- ### Setup DCOM Client and Connect Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/dcom.rst Initializes a DCOM client using NTLM authentication and connects to a specified server. Ensure NTLMSSP is imported and the server address is correct. ```python from scapy.layers.msrpce.msdcom import DCOM_Client from scapy.layers.ntlm import NTLMSSP client = DCOM_Client( ssp=NTLMSSP(UPN="Administrator@domain.local", PASSWORD="Scapy1111@"), ) client.connect("server1.domain.local") ``` -------------------------------- ### FTP Password Sniffer Script Source: https://github.com/secdev/scapy/wiki/contrib/code/Contrib: Code: FtpPasswordSniffer This is the main script for the FTP password sniffer. It includes setup, configuration, and the core logic for packet processing and credential extraction. Ensure Scapy is installed and necessary permissions are granted for network sniffing. ```python #!/usr/bin/python ############################################################################# ## ## ## ftp_password_sniffer.py --- Simple FTP password sniffer using scapy ## ## see http://trac.innovacode.com/ for latest release ## ## ## ## Copyright (C) 2008 Franck TABARY ## ## ## ## 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; version 2. ## ## ## ## This program is distributed in the hope that it will be useful, but ## ## WITHOUT ANY WARRANTY; without even the implied warranty of ## ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## ## General Public License for more details. ## ## ## ############################################################################# import logging import re from scapy import * ################################# ##### Define some constants ##### ################################# APP_NAME='ftp_password_sniffer' LOGFILE = '/var/log/'+APP_NAME+'.log' PIDFILE = '/var/run/'+APP_NAME+'.pid' conf.iface='eth0' conf.verb=0 conf.promisc=0 last_ftp_login='' last_ftp_pw='' login_success='success' login_failed='failed' log=None ########################################## ##### printUsage: display short help ##### ########################################## def printUsage(): print "Password Sniffer." print "" print "Usage: password_sniffer [option]" print "" print "Valid options:" print " -h, --help : display this help" print " -c, --console : don't fork into background" print " -d, --debug : switch to debug log level" print "" ############################################################## ##### getFtpCredentiels: extract login/pass from packets ##### ############################################################## def getFtpCredentials(pkt): global last_ftp_login, last_ftp_pw, log src=pkt.sprintf("%IP.src%") dst=pkt.sprintf("%IP.dst%") sport=pkt.sprintf("%IP.sport%") dport=pkt.sprintf("%IP.dport%") raw=pkt.sprintf("%Raw.load%") if dport=='21': raw=raw[0:-5] # From client user=re.findall("(?i)USER (.*)",raw) if user: last_ftp_login=user[0] pw=re.findall("(?i)PASS (.*)",raw) if pw: last_ftp_pw=pw[0] if sport=='21': raw=raw[1:-5] # From server reason='' if last_ftp_login and last_ftp_pw: success=re.findall(r'^230',raw) if success: status=login_success else: failed=re.findall(r'^530 (.*)',raw) if failed: reason=' ('+failed[0]+')' status=login_failed if success or failed: msg='FTP: Login '+dst+' -> '+src+': '+status+': ' msg=msg+last_ftp_login+': '+last_ftp_pw+reason log.info(msg) last_ftp_login='' last_ftp_pw='' ##################################################### ##### callback: called for each packet received ##### ##################################################### def callback(pkt): global log sport=pkt.sprintf("%IP.sport%") dport=pkt.sprintf("%IP.dport%") raw=pkt.sprintf("%Raw.load%") if raw!='??': log.debug(raw) # FTP if dport=='21' or sport=='21': getFtpCredentials(pkt) ######################################################################## ``` -------------------------------- ### Start SMB Server with Kerberos Auth Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Configures an SMB server with Kerberos authentication. Ensure the KEY and SPN parameters are correctly set for your environment. ```python smbserver( shares=[SMBShare(name="Scapy", path="/tmp")], iface="eth0", ssp=KerberosSSP( KEY=Key( EncryptionType.AES256_CTS_HMAC_SHA1_96, key=bytes.fromhex("0000000000000000000000000000000000000000000000000000000000000000"), ), SPN="cifs/server.domain.local", ), ) ``` -------------------------------- ### ARP MitM Setup Source: https://github.com/secdev/scapy/blob/master/doc/scapy/usage.rst Configures the system for an ARP Man-in-the-Middle attack by disabling IP source routing and enabling IP forwarding. It then starts Scapy to initiate the attack, poisoning the ARP caches of two machines to intercept traffic. ```bash $ sysctl net.ipv4.conf.virbr0.send_redirects=0 # virbr0 = interface $ sysctl net.ipv4.ip_forward=1 $ sudo scapy ``` -------------------------------- ### Load nRF Sniffer and Capture Bluetooth Traffic Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/bluetooth.rst Load the nrf_sniffer contrib module and the extcap interface. Then, list available interfaces and start sniffing Bluetooth LE advertisements using the nRF Sniffer. This requires Scapy version 2.5.0 or later and a properly installed Wireshark module for the nRF Sniffer. ```pycon >>> load_contrib("nrf_sniffer") >>> load_extcap() >>> conf.ifaces Source Index Name Address nrf_sniffer_ble 100 nRF Sniffer for Bluetooth LE /dev/ttyUSB0-None [...] >>> sniff(iface="/dev/ttyUSB0-None", prn=lambda x: x.summary()) NRFS2_PCAP / NRFS2_Packet / NRF2_Packet_Event / BTLE / BTLE_ADV / BTLE_ADV_IND NRFS2_PCAP / NRFS2_Packet / NRF2_Packet_Event / BTLE / BTLE_ADV / BTLE_ADV_IND NRFS2_PCAP / NRFS2_Packet / NRF2_Packet_Event / BTLE / BTLE_ADV / BTLE_ADV_IND NRFS2_PCAP / NRFS2_Packet / NRF2_Packet_Event / BTLE / BTLE_ADV / BTLE_ADV_NONCONN_IND NRFS2_PCAP / NRFS2_Packet / NRF2_Packet_Event / BTLE / BTLE_ADV / BTLE_ADV_NONCONN_IND NRFS2_PCAP / NRFS2_Packet / NRF2_Packet_Event / BTLE / BTLE_ADV / BTLE_ADV_IND ``` -------------------------------- ### Start HTTP Server with Basic Authentication Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/http.rst Set up an HTTP server that uses basic authentication. This involves specifying the BASIC mechanism and providing user credentials. ```python server = HTTP_Server.spawn( port=8080, iface="eth0", mech=HTTP_AUTH_MECHS.BASIC, BASIC_IDENTITIES={"user": MD4le("password")}, ) ``` -------------------------------- ### Build and Visualize a PipeEngine Graph Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/pipetools.rst This example shows how to construct a PipeEngine graph with multiple sources (CLIFeeder, CLIHighFeeder), drains (Drain, TransformDrain), and sinks (ConsoleSink, QueueSink). It also demonstrates visualizing the graph structure. ```pycon s = CLIFeeder() s2 = CLIHighFeeder() d1 = Drain() d2 = TransformDrain(lambda x: x[::-1]) si1 = ConsoleSink() si2 = QueueSink() s > d1 d1 > si1 d1 > si2 s2 >> d1 d1 >> d2 d2 >> si1 p = PipeEngine() p.add(s) p.add(s2) p.graph(target="> the_above_image.png") ``` -------------------------------- ### Define Setup Container Packet Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Defines the SETUP Container packet structure for CCBS. Used for setup messages in GSM UM. ```python # no upper length min 2(max for L3) (251) class SetupContainer(Packet): """SETUP Container $(CCBS)$ Section 10.5.4.22b""" name = "Setup Container $(CCBS)$" fields_desc = [ XByteField("lengthSC", None), # optional ] + [ByteField("mess" + str(x), None) for x in range(1, 250)] def post_build(self, p, pay): a = [getattr(self, fld.name) for fld in self.fields_desc] res = _adapt(1, 250, a, self.fields_desc, 1) if self.lengthSC is None: p = chb(res[1]) + p[1:] if res[0] != 0: p = p[:-res[0]] return p + pay ``` -------------------------------- ### Construct GSM UM Start DTMF Packet Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Constructs a GSM UM START DTMF packet. This function is used for the START DTMF message as defined in Section 9.3.24. ```python def startDtmf(): """START DTMF Section 9.3.24""" a = TpPd(pd=0x3) b = MessageType(mesType=0x35) # 00110101 c = KeypadFacilityHdr(ieiKF=0x2C, eightBitKF=0x0) packet = a / b / c return packet ``` -------------------------------- ### Example Packet Creation and Dissection Source: https://github.com/secdev/scapy/blob/master/doc/scapy/build_dissect.rst Demonstrates creating a packet with IP and TCP layers and shows the resulting dissected structure, including a warning about bad dataofs. ```python >>> p=IP("A"*20)/TCP("B"*32) WARNING: bad dataofs (4). Assuming dataofs=5 >>> p >> ``` -------------------------------- ### Example Usage of Foo Packet with post_build Source: https://github.com/secdev/scapy/blob/master/doc/scapy/build_dissect.rst Demonstrates creating a `Foo` packet with a payload and displaying its structure, showing how the `len` field is automatically computed by `post_build()`. ```python >>> p = Foo()/("X"*32) >>> p.show2() ###[ Foo ]### type= 0 len= 32 sep= '\r\n' ###[ Raw ]### load= 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' ``` ```python >>> hexdump(raw(p)) 0000 00 32 30 0D 0A 58 58 58 58 58 58 58 58 58 58 58 .20..XXXXXXXXXXX 0010 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 XXXXXXXXXXXXXXXX 0020 58 58 58 58 58 XXXXX ``` -------------------------------- ### Construct GSM UM Start CC Packet Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Builds a GSM UM START CC packet, optionally including Call Control Capabilities. This function is used for the START CC message as defined in Section 9.3.23a. ```python def startCc(CallControlCapabilities_presence=0): """START CC Section 9.3.23a""" a = TpPd(pd=0x3) b = MessageType(mesType=0x9) # 00001001 packet = a / b if CallControlCapabilities_presence is 1: c = CallControlCapabilitiesHdr(ieiCCC=0x15, eightBitCCC=0x0) packet = packet / c return packet ``` -------------------------------- ### Install Sphinx and Build HTML Documentation Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Follow these steps to build the HTML version of Scapy's documentation locally. Ensure you have a virtual environment activated before running the commands. ```bash (activate a virtualenv) pip install sphinx cd doc/scapy make html ``` -------------------------------- ### Install Sphinx ReadTheDocs Theme Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Install the ReadTheDocs theme for Sphinx to use its template for building documentation. ```bash pip install sphinx_rtd_theme ``` -------------------------------- ### Low-Level SMB Client Initialization Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Instantiate the low-level SMB_Client directly or via a helper, providing socket and SSP for connection. This offers the most direct control over SMB communication. ```python >>> import socket >>> from scapy.layers.smbclient import SMB_Client >>> sock = socket.socket() >>> sock.connect(("192.168.0.100", 445)) >>> lowsmbsock = SMB_Client.from_tcpsock(sock, ssp=NTLMSSP(UPN="Administrator", PASSWORD="password")) >>> resp = cli.sock.sr1(SMB2_Tree_Connect_Request(Path=r"\\server1\c$")) ``` -------------------------------- ### Running a TFTP Read Automaton Instance Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/automaton.rst Shows how to instantiate and run the TFTP read automaton. It also includes a method to clean up resources after the automaton has finished. ```python atmt = TFTP_read("my_file", "192.168.1.128") atmt.run() atmt.destroy() ``` -------------------------------- ### Construct GSM UM Setup Packet Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Builds a GSM UM SETUP packet by conditionally adding various Information Elements (IEs) based on presence flags. This function is used to construct the SETUP message as defined in Section 9.3.23.2. ```python def setup(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Facility_presence=0, CallingPartySubaddress_presence=0, CalledPartyBcdNumber_presence=0, CalledPartySubaddress_presence=0, RepeatIndicator_presence1=0, LowLayerCompatibility_presence=0, LowLayerCompatibility_presence1=0, RepeatIndicator_presence2=0, HighLayerCompatibility_presence=0, HighLayerCompatibility_presence1=0, UserUser_presence=0, SsVersionIndicator_presence=0, ClirSuppression_presence=0, ClirInvocation_presence=0, CallControlCapabilities_presence=0, Facility_presence1=0, Facility_presence2=0): """SETUP Section 9.3.23.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 packet = a / b if RepeatIndicator_presence is 1: c = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / c if BearerCapability_presence is 1: d = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / d if BearerCapability_presence1 is 1: e = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / e if Facility_presence is 1: f = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / f if CallingPartySubaddress_presence is 1: g = CallingPartySubaddressHdr(ieiCPS=0x5D, eightBitCPS=0x0) packet = packet / g if CalledPartyBcdNumber_presence is 1: h = CalledPartyBcdNumberHdr(ieiCPBN=0x5E, eightBitCPBN=0x0) packet = packet / h if CalledPartySubaddress_presence is 1: i = CalledPartySubaddressHdr(ieiCPS=0x6D, eightBitCPS=0x0) packet = packet / i if RepeatIndicator_presence1 is 1: j = RepeatIndicatorHdr(ieiRI=0xD0, eightBitRI=0x0) packet = packet / j if LowLayerCompatibility_presence is 1: k = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / k if LowLayerCompatibility_presence1 is 1: l = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / l if RepeatIndicator_presence2 is 1: m = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / m if HighLayerCompatibility_presence is 1: n = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / n if HighLayerCompatibility_presence1 is 1: o = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / o if UserUser_presence is 1: p = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / p if SsVersionIndicator_presence is 1: q = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / q if ClirSuppression_presence is 1: r = ClirSuppressionHdr(ieiCS=0xA1, eightBitCS=0x0) packet = packet / r if ClirInvocation_presence is 1: s = ClirInvocationHdr(ieiCI=0xA2, eightBitCI=0x0) packet = packet / s if CallControlCapabilities_presence is 1: t = CallControlCapabilitiesHdr(ieiCCC=0x15, eightBitCCC=0x0) packet = packet / t if Facility_presence1 is 1: u = FacilityHdr(ieiF=0x1D, eightBitF=0x0) packet = packet / u if Facility_presence2 is 1: v = FacilityHdr(ieiF=0x1B, eightBitF=0x0) packet = packet / v return packet ``` -------------------------------- ### Request TGT with PKINIT (Cert and Key files) Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/kerberos.rst Demonstrates requesting a TGT using PKINIT with separate certificate and private key files. Requires specifying the certificate file, key file, realm, and optionally a CA certificate. ```python >>> # One could also have used a different cert and key file: >>> t.request_tgt(x509="admin.cert", x509key="admin.key", realm="DOMAIN.LOCAL", ca="ca.pem") ``` -------------------------------- ### TestFLF Dissection Example Source: https://github.com/secdev/scapy/blob/master/doc/scapy/build_dissect.rst An example demonstrating the dissection of a TestFLF packet. It shows how the packet is parsed and its fields are represented. ```python >>> TestFLF("\x00\x02ABCDEFGHIJKL") > ``` -------------------------------- ### Run Scapy SMB Server from Command Line Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Shows how to start the Scapy SMB server directly from the command line, useful for unauthenticated modes. Use -h for a list of options. ```bash $ python3 -m scapy.layers.smbserver --port 12345 ``` -------------------------------- ### DCERPC Client Example (SAMR) Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/dcerpc.rst Demonstrates how to use the DCERPC_Client to connect to a server, open a pipe, bind to an interface, and enumerate domains using the SAMR interface. ```APIDOC ## DCERPC Client Example (SAMR) ### Description This example shows how to establish a DCE/RPC connection using `DCERPC_Client`, authenticate with NTLMSSP, open the `lsass` pipe, bind to the `samr` interface, and enumerate domains. ### Usage ```python from scapy.layers.ntlm import NTLMSSP, MD4le from scapy.layers.dcerpc import * from scapy.layers.msrpce.all import * ssp = NTLMSSP( UPN="User", HASHNT=MD4le("Password"), ) client = DCERPC_Client( DCERPC_Transport.NCACN_NP, ssp=ssp, ndr64=False, ) client.connect("192.168.0.100") client.open_smbpipe("lsass") # open the \pipe\lsass pipe client.bind(find_dcerpc_interface("samr")) # Get Server Handle: call [0] SamrConnect serverHandle = client.sr1_req(SamrConnect_Request( DesiredAccess=( 0x00000010 # SAM_SERVER_ENUMERATE_DOMAINS ) )).ServerHandle # Enumerate domains: call [6] SamrEnumerateDomainsInSamServer EnumerationContext = 0 while True: resp = client.sr1_req( SamrEnumerateDomainsInSamServer_Request( ServerHandle=serverHandle, EnumerationContext=EnumerationContext, ) ) # note: there are a lot of sub-structures print(resp.valueof("Buffer").valueof("Buffer")[0].valueof("Name").valueof("Buffer").decode()) EnumerationContext = resp.EnumerationContext # continue enumeration if resp.status == 0: # no domain left to enumerate break client.close() ``` ``` -------------------------------- ### Update MacPorts and install libpcap on macOS Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Updates MacPorts and installs the libpcap library on macOS using the port command. ```text $ sudo port -d selfupdate $ sudo port install libpcap ``` -------------------------------- ### Update Homebrew and install libpcap on macOS Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Updates Homebrew and installs the libpcap library on macOS using the brew command. ```text $ brew update $ brew install libpcap ``` -------------------------------- ### Transition to a State with Parameters Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/automaton.rst Shows how to trigger a transition to a state that accepts parameters, passing specific values during the transition. ```python @ATMT.receive_condition(ANOTHER_STATE) def received_ICMP(self, pkt): if ICMP in pkt: raise self.MY_STATE("got icmp", pkt[ICMP].type) ``` -------------------------------- ### Start SMB Server with NTLM Auth in AD Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Initiates an SMB server with NTLM authentication using machine credentials. This requires an active account with WORKSTATION_TRUST_ACCOUNT in its userAccountControl. ```python smbserver(ssp=NTLMSSP_DOMAIN(UPN="Computer1@domain.local", HASHNT=bytes.fromhex("7facdc498ed1680c4fd1448319a8c04f"))) ``` -------------------------------- ### Install Latest Scapy Release Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Use pip to install the latest stable release of Scapy. This is the recommended method for most users. ```sh $ pip install scapy ``` -------------------------------- ### Initialize NTLMSSP Client Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/gssapi.rst Instantiate an NTLMSSP client with user credentials. This is the first step in establishing an NTLM authentication session. ```python from scapy.layers.ntlm import * clissp = NTLMSSP( UPN="Administrator@domain.local", PASSWORD="Password1!", ) ``` -------------------------------- ### Run and Draw a Simple Automaton Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/automaton.rst This snippet shows how to instantiate and run the HelloWorld automaton, and how to generate a graphical representation of its structure. ```python a=HelloWorld() a.run() ``` ```python HelloWorld.graph() ``` -------------------------------- ### Create GSM UM EMERGENCY SETUP Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Generates an EMERGENCY SETUP message. Optionally includes the Bearer Capability information element. ```python def emergencySetup(BearerCapability_presence=0): """EMERGENCY SETUP Section 9.3.8""" a = TpPd(pd=0x3) b = MessageType(mesType=0xe) # 00001110 packet = a / b if BearerCapability_presence is 1: c = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / c return packet ``` -------------------------------- ### Start Bridge and Sender Threads Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/automotive.rst Starts the execution of the bridge and sender threads, initiating the CAN traffic bridging and packet sending processes. ```python threadBridge.start() threadSender.start() ``` -------------------------------- ### Start SMB Server with Combined NTLM and Kerberos Auth Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Sets up an SMB server that supports both NTLM and Kerberos authentication using SPNEGOSSP. This allows clients to use either authentication method. ```python smbserver( shares=[SMBShare(name="Scapy", path="/tmp")], iface="eth0", ssp=SPNEGOSSP( [ KerberosSSP( KEY=Key( EncryptionType.AES256_CTS_HMAC_SHA1_96, key=bytes.fromhex("0000000000000000000000000000000000000000000000000000000000000000"), ), SPN="cifs/server.domain.local", ), NTLMSSP( IDENTITIES={ "User1": MD4le("Password1"), "Administrator": MD4le("Password2"), }, ), ] ), ) ``` -------------------------------- ### Instantiate Basic PROFINET IO Data Packets Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/pnio.rst Demonstrates how to instantiate basic Scapy packets used for PROFINET IO data exchange, including ProfinetIO, PROFIsafe, and PNIORealTime_IOxS. Ensure the 'pnio' contrib module is loaded. ```python >>> load_contrib('pnio') >>> raw(ProfinetIO()/b'AAA') b'\x00\x00AAA' ``` ```python >>> raw(PROFIsafe.build_PROFIsafe_class(PROFIsafeControl, 4)(data = b'AAA', control=0x20, crc=0x424242)) b'AAA\x00 BBB' ``` ```python >>> hexdump(PNIORealTime_IOxS()) 0000 80 . ``` -------------------------------- ### Define a State with Parameters Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/automaton.rst Illustrates how to define a state that accepts parameters, which are then printed within the state's execution. ```python @ATMT.state() def MY_STATE(self, param1, param2): print("state=MY_STATE. param1=%r param2=%r" % (param1, param2)) ``` -------------------------------- ### Visualize traceroute with 3D graphics Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Visualizes traceroute results in 3D using VPython-Jupyter. Install VPython-Jupyter via 'pip install vpython'. ```python >>> a,u=traceroute(["www.python.org", "google.com","slashdot.org"]) >>> a.trace3D() ``` -------------------------------- ### Initialize WinSSP with NTLM Package Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/gssapi.rst Use this snippet to initialize WinSSP with the 'NTLM' package for NTLM authentication on Windows. This is useful when explicit NTLM authentication is required. ```python from scapy.arch.windows.sspi import * clissp = WinSSP(Package="NTLM") ``` -------------------------------- ### Scapy FlagsField Docstring Example Source: https://github.com/secdev/scapy/blob/master/doc/scapy/development.rst Demonstrates the structure and usage of a docstring for Scapy's FlagsField, including doctest examples for flag representation. ```python class FlagsField(BitField): """ Handle Flag type field Make sure all your flags have a label Example: >>> from scapy.packet import Packet >>> class FlagsTest(Packet): fields_desc = [FlagsField("flags", 0, 8, ["f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7"])] >>> FlagsTest(flags=9).show2() ###[ FlagsTest ]### flags = f0+f3 >>> FlagsTest(flags=0).show2().strip() ###[ FlagsTest ]### flags = :param name: field's name :param default: default value for the field :param size: number of bits in the field :param names: (list or dict) label for each flag, Least Significant Bit tag's name is written first """ ``` -------------------------------- ### HTTP GET Request with NTLM Authentication Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/http.rst Performs a GET request to a server requiring NTLM authentication. Provide user credentials via NTLMSSP. ```python from scapy.layers.http import * client = HTTP_Client( HTTP_AUTH_MECHS.NTLM, ssp=NTLMSSP(UPN="user", PASSWORD="password"), ) resp = client.request("http://127.0.0.1:8080") client.close() ``` -------------------------------- ### TFTP Read Client Automaton Initialization Source: https://github.com/secdev/scapy/blob/master/doc/scapy/advanced_usage/automaton.rst This snippet shows the initialization of a TFTP read client automaton, setting up parameters like filename, server, and ports. ```python class TFTP_read(Automaton): def parse_args(self, filename, server, sport = None, port=69, **kargs): Automaton.parse_args(self, **kargs) self.filename = filename self.server = server self.port = port self.sport = sport ``` -------------------------------- ### Install Scapy Development Version via URL Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Install the development version of Scapy in a single command using a direct URL to the master branch archive. ```sh $ pip install https://github.com/secdev/scapy/archive/refs/heads/master.zip ``` -------------------------------- ### Create START DTMF REJECT Packet Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Constructs a START DTMF REJECT packet as defined in Section 9.3.26. Requires TpPd, MessageType, and Cause layers. ```python def startDtmfReject(): """ START DTMF REJECT Section 9.3.26""" a = TpPd(pd=0x3) b = MessageType(mesType=0x37) # 00110111 c = Cause() packet = a / b / c return packet ``` -------------------------------- ### Initialize WinSSP with SPNEGO Package Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/gssapi.rst Use this snippet to initialize WinSSP with the 'Negotiate' package for SPNEGO authentication on Windows. This allows Scapy to leverage the logged-in user's credentials. ```python from scapy.arch.windows.sspi import * clissp = WinSSP(Package="Negotiate") ``` -------------------------------- ### Create START DTMF ACKNOWLEDGE Packet Source: https://github.com/secdev/scapy/wiki/Z_Legacy---Contrib:-gsm_um Constructs a START DTMF ACKNOWLEDGE packet as defined in Section 9.3.25. Requires TpPd, MessageType, and KeypadFacilityHdr layers. ```python def startDtmfAcknowledge(): """START DTMF ACKNOWLEDGE Section 9.3.25""" a = TpPd(pd=0x3) b = MessageType(mesType=0x32) # 00110010 c = KeypadFacilityHdr(ieiKF=0x2C, eightBitKF=0x0) packet = a / b / c return packet ``` -------------------------------- ### Scapy SMB Client with KerberosSSP Authentication Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/smb.rst Illustrates how to connect to an SMB server using KerberosSSP authentication by providing the UPN and password. ```python >>> smbclient("server1.domain.local", ssp=KerberosSSP(UPN="Administrator@domain.local", PASSWORD="password")) ``` -------------------------------- ### Quick HTTP GET Request Source: https://context7.com/secdev/scapy/llms.txt Demonstrates how to perform a quick HTTP GET request using the `http_request` function and access the response status code and payload. ```APIDOC ## Quick HTTP GET using the shorthand ### Description Performs a quick HTTP GET request to a specified host and path, returning the response object. ### Method `http_request(host, path, port=80, ssl=False, verbose=1)` ### Parameters - **host** (str) - The hostname or IP address to send the request to. - **path** (str) - The path of the request (e.g., "/"). - **port** (int) - Optional. The port number (default is 80). - **ssl** (bool) - Optional. Whether to use SSL/TLS (default is False). - **verbose** (int) - Optional. Verbosity level (default is 1). ### Response Example ```python resp = http_request("www.example.com", "/", verbose=0) if resp: print(resp[HTTPResponse].Status_Code) print(resp[HTTPResponse].load[:200]) ``` ``` -------------------------------- ### Install Scapy Development Version from Git Source: https://github.com/secdev/scapy/blob/master/doc/scapy/installation.rst Install the latest development version of Scapy directly from its Git repository. This provides the newest features but may be less stable. ```sh $ git clone https://github.com/secdev/scapy.git $ cd scapy $ pip install . ``` -------------------------------- ### Run Local TIME Server Source: https://github.com/secdev/scapy/wiki/contrib/code/Contrib: Code: TimeProtocol This snippet demonstrates how to run your own TIME server. It listens for requests and responds with the current system time. ```python >>> TIME_server() Ether / IP / UDP 192.168.1.11:1053 > 192.168.1.10:time / Padding ==> IP / UDP 19 2.168.1.10:time > 192.168.1.11:1053 / Raw ``` -------------------------------- ### Basic HTTP GET Request with HTTP_Client Source: https://github.com/secdev/scapy/blob/master/doc/scapy/layers/http.rst Performs a simple GET request to a local HTTP server using the HTTP_Client automaton. Ensure the server is running on 127.0.0.1:8080. ```python from scapy.layers.http import * client = HTTP_Client() resp = client.request("http://127.0.0.1:8080") client.close() ```