> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# VPNs & Tunneling

> Understand VPN technologies, tunneling protocols, and secure remote network access

# Module 15: VPNs & Tunneling

VPNs (Virtual Private Networks) create secure, encrypted connections over public networks. This module covers VPN types, tunneling protocols, and real-world implementations.

<Frame>
  <img src="https://mintcdn.com/devweeekends/X0Fp4X8lMl-ZftoO/images/courses/networking-mastery/vpn-tunnel.svg?fit=max&auto=format&n=X0Fp4X8lMl-ZftoO&q=85&s=b4bd478ddd000587f4956b195a873b25" alt="VPN Tunnel Architecture" width="1080" height="1080" data-path="images/courses/networking-mastery/vpn-tunnel.svg" />
</Frame>

<Info>
  **Estimated Time**: 3-4 hours\
  **Difficulty**: Intermediate\
  **Prerequisites**: Module 7 (Security basics), Module 10 (NAT)
</Info>

***

## 15.1 What is a VPN?

A VPN extends a private network across a public network, allowing users to send and receive data as if connected to the private network directly. The analogy is a sealed, private tunnel through a public highway. Cars (packets) entering the tunnel are visible to everyone on the highway -- but no one can see what is inside the tunnel or tamper with its contents. When a car exits the tunnel on the other end, it is on the private road (network) as if it had always been there.

### Without VPN

```
┌─────────────────┐                    ┌─────────────────┐
│ Remote Worker   │                    │ Company Network │
│ (Coffee Shop)   │                    │                 │
│                 │  ───INSECURE───►   │  Internal Apps  │
│ Public WiFi     │    (can be         │  Can't access!  │
│ (untrusted)     │   intercepted)     │                 │
└─────────────────┘                    └─────────────────┘
```

### With VPN

```
┌─────────────────┐                    ┌─────────────────┐
│ Remote Worker   │     Encrypted      │ Company Network │
│ (Coffee Shop)   │      Tunnel        │                 │
│                 │  ════════════════► │  Internal Apps  │
│ VPN Client      │    (secure)        │  Full access!   │
│                 │                    │  VPN Gateway    │
└─────────────────┘                    └─────────────────┘
```

***

## 15.2 VPN Types

### Remote Access VPN

Individual users connect to a corporate network.

```
┌──────────────┐
│ Employee A   │──┐
│ (Home)       │  │    ┌─────────────────┐
└──────────────┘  │    │                 │
                  ├───►│  VPN Gateway    │──► Corporate Network
┌──────────────┐  │    │                 │
│ Employee B   │──┘    └─────────────────┘
│ (Hotel)      │
└──────────────┘
```

**Use Cases:**

* Work from home
* Traveling employees
* Contractors accessing internal systems

***

### Site-to-Site VPN

Connects two networks together permanently.

```
┌─────────────────────┐         ┌─────────────────────┐
│   HQ Office         │         │   Branch Office     │
│   New York          │         │   London            │
│                     │         │                     │
│   ┌─────────────┐   │         │   ┌─────────────┐  │
│   │ VPN Gateway │◄══╪═════════╪══►│ VPN Gateway │  │
│   └─────────────┘   │ Always  │   └─────────────┘  │
│                     │   On    │                     │
│   192.168.1.0/24    │         │   192.168.2.0/24   │
└─────────────────────┘         └─────────────────────┘
```

**Use Cases:**

* Connect branch offices
* Connect on-premises to cloud (AWS VPN)
* Merge networks after acquisition

***

### Client-to-Site vs Site-to-Site

| Aspect     | Client-to-Site    | Site-to-Site           |
| ---------- | ----------------- | ---------------------- |
| Initiator  | Individual user   | Network device         |
| Connection | On-demand         | Permanent              |
| Software   | VPN client needed | Router/firewall config |
| Scale      | Per user          | Per network            |

***

## 15.3 Tunneling Protocols

### IPsec (Internet Protocol Security)

Industry standard for site-to-site VPNs.

**Two Modes:**

```
TRANSPORT MODE (host-to-host):
┌────────────────────────────────────────┐
│ Original IP Header │ IPsec │ Payload   │
└────────────────────────────────────────┘
                       (encrypted)

TUNNEL MODE (gateway-to-gateway):
┌──────────────────────────────────────────────────┐
│ New IP Header │ IPsec │ Original IP │ Payload   │
└──────────────────────────────────────────────────┘
                         (entire original packet encrypted)
```

**IPsec Components:**

| Component                                | Purpose                                        |
| ---------------------------------------- | ---------------------------------------------- |
| **IKE (Internet Key Exchange)**          | Negotiates security parameters, establishes SA |
| **ESP (Encapsulating Security Payload)** | Encryption + authentication                    |
| **AH (Authentication Header)**           | Authentication only (no encryption)            |
| **SA (Security Association)**            | Set of security parameters for the connection  |

**IPsec Phases:**

Think of the two phases like establishing diplomatic relations. Phase 1 is the countries agreeing on which language to speak and verifying each other's credentials (authentication). Phase 2 is negotiating the actual terms of the treaty (encryption parameters for the data tunnel). If Phase 1 fails, Phase 2 never starts.

```
Phase 1 (IKE SA):
- Authentication (pre-shared key or certificates)
- Establish secure channel for Phase 2

Phase 2 (IPsec SA):
- Negotiate encryption algorithms
- Establish tunnel for data
```

### What an IPsec packet looks like on the wire

```
Original packet (before IPsec):
  [IP: 192.168.1.10 -> 10.0.2.50][TCP][HTTP Data]

After IPsec tunnel mode:
  [New IP: 203.0.113.1 -> 198.51.100.1][ESP Header][Encrypted: original IP + TCP + HTTP Data][ESP Trailer]
                                                     ^--- everything inside is unreadable to anyone on the internet

An eavesdropper sees:
  Source: 203.0.113.1 (your gateway)
  Destination: 198.51.100.1 (remote gateway)
  Protocol: ESP (protocol number 50)
  Content: encrypted blob (cannot see original IPs, ports, or data)
```

***

### OpenVPN

Open-source, widely used for remote access.

**Characteristics:**

* Uses OpenSSL library
* TCP or UDP (UDP preferred)
* Port 1194 by default (can use 443 to bypass firewalls)
* Certificate-based authentication

```
┌─────────────────────────────────────────────────┐
│              OpenVPN Architecture               │
├─────────────────────────────────────────────────┤
│                                                 │
│  Client                           Server        │
│  ┌─────────────┐              ┌─────────────┐  │
│  │ .ovpn file  │              │ server.conf │  │
│  │ client.crt  │   TLS/SSL    │ server.crt  │  │
│  │ client.key  │◄────────────►│ server.key  │  │
│  │ ca.crt      │              │ ca.crt      │  │
│  └─────────────┘              └─────────────┘  │
│                                                 │
└─────────────────────────────────────────────────┘
```

***

### WireGuard

Modern, fast, simple VPN protocol. WireGuard has rapidly become the preferred choice for new VPN deployments due to its simplicity and performance.

**Advantages:**

* \~4,000 lines of code (vs 100,000+ for OpenVPN) -- a smaller codebase means fewer bugs and a smaller attack surface. The entire codebase is auditable by a single person.
* Built into the Linux kernel (since 5.6) -- no user-space daemons needed, which means better performance.
* Faster than IPsec and OpenVPN in most benchmarks -- lower latency and higher throughput due to its minimal, efficient design.
* Uses modern cryptography only (Curve25519, ChaCha20, Poly1305, BLAKE2s) -- no cipher negotiation, which eliminates downgrade attacks. The trade-off is that if any of these algorithms are ever broken, WireGuard must be updated (crypto agility is deliberately sacrificed for simplicity).

```bash theme={null}
# WireGuard configuration example
[Interface]
PrivateKey = <client-private-key>
Address = 10.0.0.2/24
DNS = 1.1.1.1

[Peer]
PublicKey = <server-public-key>
Endpoint = vpn.example.com:51820
AllowedIPs = 0.0.0.0/0  # Route all traffic through VPN
```

***

### SSL/TLS VPN

VPN over HTTPS - works through any firewall.

**Types:**

* **Portal VPN**: Browser-based access to web apps
* **Tunnel VPN**: Full network access (like OpenVPN)

**Advantage**: Uses port 443 (HTTPS) - almost never blocked.

***

### Protocol Comparison

| Protocol   | Speed     | Security   | Firewall Bypass           | Complexity |
| ---------- | --------- | ---------- | ------------------------- | ---------- |
| IPsec      | Fast      | High       | Poor (uses UDP 500, 4500) | Complex    |
| OpenVPN    | Medium    | High       | Good (can use TCP 443)    | Medium     |
| WireGuard  | Very Fast | High       | Medium (UDP only)         | Simple     |
| SSTP       | Medium    | High       | Excellent (TCP 443)       | Medium     |
| L2TP/IPsec | Medium    | Medium     | Poor                      | Medium     |
| PPTP       | Fast      | **Broken** | Good                      | Simple     |

<Warning>
  **Never use PPTP.** Its encryption has been broken and traffic can be decrypted.
</Warning>

***

## 15.4 Split Tunneling

### Full Tunnel

All traffic goes through VPN.

```
Your Device
    │
    ▼
┌─────────┐        ┌──────────────┐
│   VPN   │───────►│  VPN Server  │──► google.com
│ Client  │        │              │──► company.com
└─────────┘        │              │──► netflix.com
                   └──────────────┘
                   ALL traffic encrypted
```

**Pros:** Maximum security, all traffic protected
**Cons:** Slower, uses company bandwidth for everything

***

### Split Tunnel

Only specific traffic goes through VPN.

```
Your Device
    │
    ├───────────────────────────────────► google.com (direct)
    │                                     netflix.com (direct)
    ▼
┌─────────┐        ┌──────────────┐
│   VPN   │───────►│  VPN Server  │──► company.com (VPN)
│ Client  │        │              │
└─────────┘        └──────────────┘
```

**Configuration Example (WireGuard):**

```bash theme={null}
# Full tunnel - route everything
AllowedIPs = 0.0.0.0/0

# Split tunnel - only company network
AllowedIPs = 10.0.0.0/8, 192.168.1.0/24
```

**Pros:** Faster, saves bandwidth
**Cons:** Non-VPN traffic is unprotected

<Tip>
  **Practical scenario -- when split tunneling goes wrong**: An employee uses split tunnel VPN so personal browsing goes direct. But their company laptop also runs a local database GUI that connects to the corporate database over VPN. One day, malware on a website infects their machine via the direct (unprotected) path. Because the VPN tunnel is active, the malware can now reach the corporate database. This is the fundamental trade-off: split tunneling saves bandwidth but creates a bridge between the untrusted internet and the trusted corporate network. Mitigate this with endpoint security (antivirus, host firewall) and network segmentation that limits what VPN clients can access.
</Tip>

***

## 15.5 VPN in the Cloud

### AWS Site-to-Site VPN

Connect on-premises network to AWS VPC.

```
┌─────────────────────────────────────────────────────────────┐
│                          AWS                                 │
│  ┌─────────────────────────────────────────────────────┐    │
│  │                      VPC                             │    │
│  │   ┌─────────────┐         ┌─────────────┐           │    │
│  │   │   Private   │         │   Virtual   │           │    │
│  │   │   Subnet    │         │   Private   │           │    │
│  │   │ 10.0.1.0/24 │         │   Gateway   │           │    │
│  │   └─────────────┘         └──────┬──────┘           │    │
│  │                                  │                   │    │
│  └──────────────────────────────────┼───────────────────┘    │
│                                     │                        │
└─────────────────────────────────────┼────────────────────────┘
                                      │ VPN Connection
                                      │ (IPsec tunnels)
                                      │
┌─────────────────────────────────────┼────────────────────────┐
│             On-Premises             │                        │
│                   ┌─────────────────┴──────────────┐        │
│                   │      Customer Gateway          │        │
│                   │      (Your router/firewall)    │        │
│                   └────────────────────────────────┘        │
│                                                              │
│                    192.168.1.0/24                           │
└──────────────────────────────────────────────────────────────┘
```

**Components:**

* **Virtual Private Gateway (VGW)**: AWS side endpoint
* **Customer Gateway (CGW)**: Your side endpoint
* **VPN Connection**: Two IPsec tunnels (for redundancy)

***

### AWS Client VPN

For remote access to AWS resources.

```
┌────────────────────────────────────────────────────────────┐
│                         AWS                                 │
│  ┌───────────────────────────────────────────────────┐     │
│  │                    VPC                             │     │
│  │                                                    │     │
│  │   ┌────────────────────┐    ┌────────────────┐   │     │
│  │   │  Client VPN        │    │    Subnet      │   │     │
│  │   │  Endpoint          │───►│   Resources    │   │     │
│  │   │                    │    │                │   │     │
│  │   └─────────┬──────────┘    └────────────────┘   │     │
│  │             │                                     │     │
│  └─────────────┼─────────────────────────────────────┘     │
│                │                                            │
└────────────────┼────────────────────────────────────────────┘
                 │
    ┌────────────┴────────────┐
    │                         │
┌───┴────┐              ┌─────┴────┐
│ Remote │              │  Remote  │
│ User 1 │              │  User 2  │
└────────┘              └──────────┘
```

***

## 15.6 VPN Security Considerations

### Authentication Methods

| Method               | Security | Complexity |
| -------------------- | -------- | ---------- |
| Pre-Shared Key (PSK) | Medium   | Simple     |
| Certificates (PKI)   | High     | Complex    |
| Username/Password    | Medium   | Simple     |
| Multi-Factor (MFA)   | High     | Medium     |

### Best Practices

<CardGroup cols={2}>
  <Card title="Use Strong Encryption" icon="lock">
    AES-256, ChaCha20. Avoid 3DES, DES, or anything "export grade."
  </Card>

  <Card title="Enable MFA" icon="mobile">
    Add second factor for VPN authentication.
  </Card>

  <Card title="Certificate Auth" icon="certificate">
    Use certificates instead of pre-shared keys for better security.
  </Card>

  <Card title="Limit Access" icon="user-lock">
    Use split tunneling wisely. Apply least privilege.
  </Card>
</CardGroup>

***

## 15.7 Other Tunneling Methods

### SSH Tunneling

Create encrypted tunnels using SSH.

```bash theme={null}
# Local port forwarding
# Access remote_host:3306 via localhost:3306
ssh -L 3306:remote_host:3306 user@bastion

# Remote port forwarding  
# Expose local:8080 on remote:8080
ssh -R 8080:localhost:8080 user@remote

# Dynamic (SOCKS proxy)
ssh -D 1080 user@server
# Configure browser to use localhost:1080 as SOCKS proxy
```

**Use Cases:**

* Access database behind firewall
* Quick temporary secure access
* Bypass network restrictions

***

### GRE (Generic Routing Encapsulation)

Encapsulates various network layer protocols inside point-to-point links.

```
┌──────────────────────────────────────────────────────┐
│ Outer IP │ GRE Header │ Inner IP │ Original Payload │
└──────────────────────────────────────────────────────┘
```

**Note:** GRE provides no encryption. Often combined with IPsec.

***

### VXLAN (Virtual Extensible LAN)

Overlay network for data centers. Extends L2 network over L3.

```
┌───────────────────────────────────────────────────────────────┐
│ Outer IP │ UDP │ VXLAN │ Inner Ethernet │ Inner IP │ Payload │
└───────────────────────────────────────────────────────────────┘
```

**Use Case:** Connect VMs/containers across different physical networks as if on same L2 network.

***

## 15.8 Troubleshooting VPN Issues

<Accordion title="VPN won't connect">
  ```bash theme={null}
  # 1. Check if VPN port is reachable
  nc -zv vpn.example.com 1194

  # 2. Check firewall rules
  sudo iptables -L -n

  # 3. Verify credentials/certificates
  # Check certificate expiry
  openssl x509 -in client.crt -noout -dates

  # 4. Check VPN logs
  # OpenVPN: /var/log/openvpn.log
  # WireGuard: sudo wg show
  ```
</Accordion>

<Accordion title="Connected but can't reach resources">
  ```bash theme={null}
  # 1. Check if tunnel is up
  ip addr show tun0

  # 2. Check routing
  ip route | grep tun0

  # 3. Ping VPN gateway
  ping 10.0.0.1

  # 4. Check DNS
  nslookup internal-server.company.com

  # 5. Verify split tunnel config
  # Are the target routes included?
  ```
</Accordion>

<Accordion title="Slow VPN performance">
  ```bash theme={null}
  # 1. Test without VPN as baseline
  speedtest-cli

  # 2. Test with VPN
  speedtest-cli

  # 3. Check MTU issues
  ping -M do -s 1400 target

  # 4. Try TCP vs UDP (OpenVPN)
  # UDP is usually faster

  # 5. Change VPN server location
  # Closer server = lower latency
  ```
</Accordion>

***

## 15.9 Key Takeaways

<CardGroup cols={2}>
  <Card title="VPN = Secure Tunnel" icon="lock">
    Encrypts traffic over untrusted networks.
  </Card>

  <Card title="Choose Right Protocol" icon="list">
    WireGuard for speed, OpenVPN for compatibility, IPsec for site-to-site.
  </Card>

  <Card title="Split Tunnel Carefully" icon="code-branch">
    Balance security vs. performance based on use case.
  </Card>

  <Card title="Never Use PPTP" icon="ban">
    It's broken. Use modern protocols only.
  </Card>
</CardGroup>

***

## Next Module

<Card title="Module 16: Real-World Networking Scenarios" icon="arrow-right" href="/courses/networking-mastery/16-scenarios">
  Walk through complete networking scenarios from request to response.
</Card>
