Interactive packet manipulation program and library for network security research and testing
—
Global configuration management, utility functions for data conversion, validation, file operations, and platform-specific functionality that supports Scapy's core operations.
Scapy's global configuration system that controls behavior, protocols, and platform-specific settings.
class Conf:
"""
Global configuration object for Scapy settings.
"""
def configure(self, **kwargs) -> None:
"""
Configure multiple settings at once.
Parameters:
- **kwargs: Configuration key-value pairs
"""
# Network interface settings
iface: str # Default network interface
ifaces: dict # Available network interfaces
# Protocol settings
ipv6_enabled: bool # Enable IPv6 support
load_layers: list # Protocol layers to load
# Display settings
verb: int # Verbosity level (0-3)
color_theme: str # Color theme for output
# Timeouts and limits
timeout: float # Default timeout for operations
retry: int # Default retry count
# File and path settings
temp_dir: str # Temporary directory path
# Platform settings
use_pcap: bool # Use libpcap for packet capture
use_netifaces: bool # Use netifaces library
# Global configuration instance
conf: ConfFunctions for converting between different data representations and formats.
def hexdump(x: bytes, dump: bool = False) -> str:
"""
Create hexadecimal dump of binary data.
Parameters:
- x: Binary data to dump
- dump: Return string instead of printing
Returns:
str: Hex dump string (if dump=True)
"""
def linehexdump(x: bytes, onlyasc: bool = 0, onlyhex: bool = 0) -> str:
"""
Create single-line hex dump.
Parameters:
- x: Binary data to dump
- onlyasc: Show only ASCII characters
- onlyhex: Show only hex values
Returns:
str: Single-line hex dump
"""
def chexdump(x: bytes) -> str:
"""
Create colored hex dump.
Parameters:
- x: Binary data to dump
Returns:
str: Colored hex dump
"""
def hexstr(x: bytes, onlyasc: bool = 0, onlyhex: bool = 0) -> str:
"""
Convert binary data to hex string representation.
Parameters:
- x: Binary data to convert
- onlyasc: Include only ASCII printable chars
- onlyhex: Include only hex values
Returns:
str: Hex string representation
"""
def mac2str(mac: str) -> bytes:
"""
Convert MAC address string to binary representation.
Parameters:
- mac: MAC address string (e.g., "aa:bb:cc:dd:ee:ff")
Returns:
bytes: Binary MAC address
"""
def str2mac(s: bytes) -> str:
"""
Convert binary MAC address to string representation.
Parameters:
- s: Binary MAC address (6 bytes)
Returns:
str: MAC address string
"""
def ltoa(addr: int) -> str:
"""
Convert long integer to IP address string.
Parameters:
- addr: IP address as 32-bit integer
Returns:
str: IP address string
"""
def atol(addr: str) -> int:
"""
Convert IP address string to long integer.
Parameters:
- addr: IP address string
Returns:
int: IP address as 32-bit integer
"""
def itom(x: int) -> str:
"""
Convert integer to netmask string.
Parameters:
- x: Netmask length (0-32)
Returns:
str: Netmask string (e.g., "255.255.255.0")
"""Functions for validating network addresses and data formats.
def valid_mac(mac: str) -> bool:
"""
Validate MAC address format.
Parameters:
- mac: MAC address string to validate
Returns:
bool: True if valid MAC address format
"""
def valid_ip(ip: str) -> bool:
"""
Validate IPv4 address format.
Parameters:
- ip: IP address string to validate
Returns:
bool: True if valid IPv4 address
"""
def valid_ip6(ip: str) -> bool:
"""
Validate IPv6 address format.
Parameters:
- ip: IPv6 address string to validate
Returns:
bool: True if valid IPv6 address
"""
def valid_net(net: str) -> bool:
"""
Validate network address format (CIDR notation).
Parameters:
- net: Network string to validate (e.g., "192.168.1.0/24")
Returns:
bool: True if valid network format
"""Functions for calculating various network checksums.
def checksum(data: bytes) -> int:
"""
Calculate Internet checksum (RFC 1071).
Parameters:
- data: Data to checksum
Returns:
int: 16-bit checksum value
"""
def fletcher16_checksum(data: bytes) -> int:
"""
Calculate Fletcher-16 checksum.
Parameters:
- data: Data to checksum
Returns:
int: 16-bit Fletcher checksum
"""Functions for working with network interfaces and routing information.
def get_if_list() -> list[str]:
"""
Get list of available network interfaces.
Returns:
list[str]: List of interface names
"""
def get_if_addr(iff: str) -> str:
"""
Get IP address of network interface.
Parameters:
- iff: Interface name
Returns:
str: IP address of interface
"""
def get_if_hwaddr(iff: str) -> str:
"""
Get hardware (MAC) address of network interface.
Parameters:
- iff: Interface name
Returns:
str: MAC address of interface
"""
def get_if_raw_hwaddr(iff: str) -> tuple[int, bytes]:
"""
Get raw hardware address information.
Parameters:
- iff: Interface name
Returns:
tuple: (address_family, raw_address)
"""Utility functions for file operations, temporary files, and system interaction.
def get_temp_file(keep: bool = False, autoext: str = "", fd: bool = False) -> str:
"""
Create temporary file.
Parameters:
- keep: Don't delete file automatically
- autoext: Automatic file extension
- fd: Return file descriptor instead of name
Returns:
str or int: Temporary file path or file descriptor
"""
def get_temp_dir() -> str:
"""
Get temporary directory path.
Returns:
str: Temporary directory path
"""
def sane(x: bytes, color: bool = False) -> str:
"""
Sanitize binary data for safe display.
Parameters:
- x: Binary data to sanitize
- color: Use color coding for non-printable chars
Returns:
str: Sanitized string representation
"""
def export_object(obj) -> bytes:
"""
Export Python object to binary format.
Parameters:
- obj: Object to export
Returns:
bytes: Serialized object data
"""
def import_object(data: bytes):
"""
Import Python object from binary format.
Parameters:
- data: Serialized object data
Returns:
object: Deserialized Python object
"""Functions for generating random values for testing and packet crafting.
def randstring(length: int) -> str:
"""
Generate random string of specified length.
Parameters:
- length: String length
Returns:
str: Random string
"""
def randbytes(length: int) -> bytes:
"""
Generate random bytes of specified length.
Parameters:
- length: Number of bytes
Returns:
bytes: Random bytes
"""
class RandMAC:
"""Random MAC address generator."""
def __call__(self) -> str:
"""Generate random MAC address."""
class RandIP:
"""Random IP address generator."""
def __init__(self, net: str = "0.0.0.0/0"):
"""
Parameters:
- net: Network range for random IPs
"""
def __call__(self) -> str:
"""Generate random IP address."""
class RandShort:
"""Random 16-bit integer generator."""
def __init__(self, min: int = 0, max: int = 65535):
"""
Parameters:
- min: Minimum value
- max: Maximum value
"""
def __call__(self) -> int:
"""Generate random short integer."""Functions for managing Scapy sessions and state.
def save_session(fname: str, session: dict = None, pickleProto: int = -1) -> None:
"""
Save current Scapy session to file.
Parameters:
- fname: Output filename
- session: Session dictionary to save (None for current)
- pickleProto: Pickle protocol version
"""
def load_session(fname: str) -> None:
"""
Load Scapy session from file.
Parameters:
- fname: Session file to load
"""
def update_session(fname: str) -> None:
"""
Update current session with data from file.
Parameters:
- fname: Session file to load updates from
"""
def restart() -> None:
"""
Restart Scapy session, clearing all state.
"""Exception classes and error handling utilities.
class Scapy_Exception(Exception):
"""Base exception class for all Scapy errors."""
class ScapyInvalidPlatformException(Scapy_Exception):
"""Exception for unsupported platform operations."""
class ScapyNoDstMacException(Scapy_Exception):
"""Exception when destination MAC cannot be determined."""
def warning(msg: str) -> None:
"""
Display warning message.
Parameters:
- msg: Warning message to display
"""Logging configuration and utilities.
import logging
# Scapy loggers
log_scapy: logging.Logger # Main Scapy logger
log_runtime: logging.Logger # Runtime events logger
log_interactive: logging.Logger # Interactive session logger
log_loading: logging.Logger # Module loading loggerfrom scapy.all import *
# Check current configuration
print(f"Default interface: {conf.iface}")
print(f"IPv6 enabled: {conf.ipv6_enabled}")
print(f"Verbosity level: {conf.verb}")
# Modify configuration
conf.verb = 2 # Increase verbosity
conf.timeout = 5 # Set default timeout to 5 seconds
# Configure multiple settings
conf.configure(
verb=1,
timeout=3,
retry=5,
color_theme="colorful"
)
# List available interfaces
interfaces = get_if_list()
print(f"Available interfaces: {interfaces}")
# Get interface information
if interfaces:
iface = interfaces[0]
ip_addr = get_if_addr(iface)
mac_addr = get_if_hwaddr(iface)
print(f"Interface {iface}: IP={ip_addr}, MAC={mac_addr}")# MAC address operations
mac_str = "aa:bb:cc:dd:ee:ff"
mac_bytes = mac2str(mac_str)
mac_back = str2mac(mac_bytes)
print(f"MAC: {mac_str} -> {mac_bytes.hex()} -> {mac_back}")
# IP address operations
ip_str = "192.168.1.1"
ip_int = atol(ip_str)
ip_back = ltoa(ip_int)
print(f"IP: {ip_str} -> {ip_int} -> {ip_back}")
# Validation
addresses = ["192.168.1.1", "256.1.1.1", "aa:bb:cc:dd:ee:ff", "invalid:mac"]
for addr in addresses:
if ":" in addr:
valid = valid_mac(addr)
addr_type = "MAC"
else:
valid = valid_ip(addr)
addr_type = "IP"
print(f"{addr_type} {addr}: {'valid' if valid else 'invalid'}")
# Network validation
networks = ["192.168.1.0/24", "10.0.0.0/8", "invalid/network"]
for net in networks:
valid = valid_net(net)
print(f"Network {net}: {'valid' if valid else 'invalid'}")# Create sample packet
pkt = IP(dst="8.8.8.8") / TCP(dport=80) / Raw(b"GET / HTTP/1.1\\r\\n\\r\\n")
# Display packet in different formats
print("Standard hex dump:")
hexdump(bytes(pkt))
print("\\nColored hex dump:")
print(chexdump(bytes(pkt)))
print("\\nSingle line hex:")
print(linehexdump(bytes(pkt)))
# Sanitize data for display
raw_data = b"Hello\\x00\\x01\\x02World\\xff"
sanitized = sane(raw_data, color=True)
print(f"Sanitized: {sanitized}")# Generate random values for testing
rand_mac = RandMAC()
rand_ip = RandIP("192.168.1.0/24")
rand_port = RandShort(1024, 65535)
print("Random values:")
for i in range(5):
mac = rand_mac()
ip = rand_ip()
port = rand_port()
print(f" MAC: {mac}, IP: {ip}, Port: {port}")
# Generate random strings and bytes
random_str = randstring(10)
random_data = randbytes(16)
print(f"Random string: {random_str}")
print(f"Random bytes: {random_data.hex()}")# Save current session
variables_to_save = {
'my_packets': packets,
'target_ips': ["192.168.1.1", "192.168.1.2"],
'config_backup': {'verb': conf.verb, 'timeout': conf.timeout}
}
save_session("my_session.scapy", variables_to_save)
# Load session later
load_session("my_session.scapy")
# Working with temporary files
temp_file = get_temp_file(autoext=".pcap")
print(f"Using temporary file: {temp_file}")
# Write some packets to temp file
test_packets = [IP(dst=f"192.168.1.{i}")/ICMP() for i in range(1, 11)]
wrpcap(temp_file, test_packets)
# Read back and verify
loaded_packets = rdpcap(temp_file)
print(f"Wrote {len(test_packets)} packets, loaded {len(loaded_packets)} packets")# Calculate checksums for data
test_data = b"Hello, World!"
inet_checksum = checksum(test_data)
fletcher_checksum = fletcher16_checksum(test_data)
print(f"Data: {test_data}")
print(f"Internet checksum: 0x{inet_checksum:04x}")
print(f"Fletcher-16 checksum: 0x{fletcher_checksum:04x}")
# Verify packet checksums
ip_pkt = IP(dst="8.8.8.8") / UDP(dport=53) / Raw(b"test")
print(f"IP checksum: 0x{ip_pkt.chksum:04x}")
print(f"UDP checksum: 0x{ip_pkt[UDP].chksum:04x}")import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
# Use Scapy loggers
log_scapy.info("Starting packet analysis")
log_runtime.debug("Processing packet batch")
# Error handling example
try:
# Attempt operation that might fail
invalid_pkt = IP(dst="invalid.address") / ICMP()
send(invalid_pkt)
except ScapyNoDstMacException as e:
warning(f"Could not determine destination MAC: {e}")
except Scapy_Exception as e:
print(f"Scapy error: {e}")
except Exception as e:
print(f"General error: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-scapy