Skip to content
Tunnel Encapsulation
step 1/5

Reading — step 1 of 5

Read

~1 min readVPN Fundamentals

Tunnel Encapsulation

Inner packet (e.g., from app on the laptop):

[IP src=10.0.0.2 dst=10.0.0.1] [TCP] [HTTP data]

Outer packet (sent over the internet):

[IP src=client_pub dst=server_pub] [UDP src/dst=51820] [VPN_HEADER] [encrypt(inner)] [TAG]

The kernel reads inner from TUN. VPN code:

  1. Encrypts the inner packet with session key.
  2. Wraps with VPN header (counter, type).
  3. Sends as UDP datagram to peer's public IP.

Peer:

  1. Receives UDP datagram.
  2. Decrypts to recover inner packet.
  3. Writes inner packet to TUN.
  4. Kernel sees inner packet on TUN, routes to local network.

Effective bidirectional virtual link.

WireGuard packet types:

  • 1: Handshake initiation.
  • 2: Handshake response.
  • 3: Cookie reply (DOS defense).
  • 4: Transport data.

Transport data packet:

[type=4 (1 byte)] [reserved (3 bytes)] [receiver_index (4 bytes)] [counter (8 bytes)] [encrypted_data + tag]

receiver_index identifies which session this packet belongs to (each direction has its own session).

counter: per-packet, monotonically increasing. Also serves as nonce for ChaCha20-Poly1305 (pad with zeros to 12 bytes).

Replay protection: per-session, maintain a sliding window of recently-seen counters. Reject too-old counters.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…