COMPUTER NETWORKS / 7. NETWORK SECURITY

Network Security — Firewalls, VPN, Attacks & Defense

How networks are attacked, protected, and secured in production


EXPLANATION

Network security is the practice of protecting your network and data from unauthorized access, attacks, and damage. Understanding attacks is prerequisite to building defenses.

Common Network Attacks:

Man-in-the-Middle (MITM): attacker positions themselves between client and server, relaying and potentially altering traffic. Defense: TLS (certificates prove server identity), HSTS (browsers force HTTPS), certificate pinning.

DDoS (Distributed Denial of Service): flooding a server with so much traffic it can't serve legitimate requests. Types: volumetric (UDP flood, ICMP flood), protocol (SYN flood exhausts connection table), application layer (HTTP flood). Defense: rate limiting, CDN, anycast, scrubbing centers.

SYN Flood: attacker sends thousands of SYN packets with spoofed source IPs. Server allocates state for each connection (SYN-RECEIVED) but never gets ACK. Connection table fills up. Defense: SYN cookies (server encodes state in the SYN-ACK without allocating memory).

DNS Spoofing / Cache Poisoning: inject false DNS records into a resolver's cache. Users who ask that resolver get the attacker's IP. Defense: DNSSEC (DNS records are signed with public key cryptography).

Port Scanning: systematically probing ports to discover which services are running. Not an attack itself but reconnaissance. Defense: firewall rules, fail2ban, rate limit connections per IP.

Firewalls: filter traffic based on rules:
• Packet filtering (Layer 3/4): allow/deny based on IP, port, protocol
• Stateful: tracks connection state, only allows established connections in
• Application (Layer 7): inspects HTTP content, blocks based on application rules
• Cloud: AWS Security Groups, GCP Firewall Rules

VPN (Virtual Private Network): creates an encrypted tunnel between two points. All traffic inside the tunnel appears to come from the VPN endpoint. Uses IPSec or OpenVPN (TLS over UDP). WireGuard is the modern, fast alternative.

Zero Trust Security: never trust, always verify. Even traffic inside your network must authenticate. Every service-to-service call is authenticated. Microsegmentation limits blast radius of breaches.

TLS best practices:
• TLS 1.3 only (1.0 and 1.1 are deprecated, broken)
• Strong cipher suites (AES-256-GCM, ChaCha20-Poly1305)
• Perfect Forward Secrecy (ECDHE key exchange — compromise of private key doesn't expose past sessions)
• HSTS with long max-age and includeSubDomains

DIAGRAM

FIREWALL ARCHITECTURE:
  Internet
      ↓
  [Firewall/WAF]  ← blocks SYN floods, bad IPs, known malware
      ↓
  DMZ (demilitarized zone)
  [Web Server / Load Balancer / CDN]
      ↓
  [Internal Firewall]  ← only allows app→DB on port 5432
      ↓
  Internal Network
  [App Servers]  [Databases]  [Internal Services]

  TLS ENCRYPTION:
  Without TLS:  Client → [username: alice, pw: secret123] → Server
                                    ↑ visible to anyone on network
  With TLS:     Client → [xK92#@mP0q...] → Server
                            ↑ encrypted, unreadable in transit

  COMMON ATTACK VECTORS:
  SYN Flood → fill connection table → legitimate users can't connect
  DNS Spoof  → redirect users to fake site → steal credentials
  MITM       → intercept/modify traffic → session hijacking
  Port Scan  → reconnaissance for vulnerabilities

CODE

PYTHON
1import ssl
2import socket
3import hashlib
4import hmac
5
6# ── Inspect TLS certificate ────────────────────────────
7def inspect_tls(hostname: str, port: int = 443):
8 context = ssl.create_default_context()
9 with socket.create_connection((hostname, port), timeout=5) as sock:
10 with context.wrap_socket(sock, server_hostname=hostname) as ssock:
11 cert = ssock.getpeercert()
12 cipher = ssock.cipher()
13 version = ssock.version()
14
15 print(f"
16{hostname} TLS Info:")
17 print(f" Protocol: {version}")
18 print(f" Cipher: {cipher[0]}")
19 print(f" Bits: {cipher[2]}")
20 print(f" Subject: {dict(cert['subject'][0])}")
21 print(f" Issuer: {dict(cert['issuer'][0])}")
22 print(f" Expires: {cert['notAfter']}")
23
24 # Check certificate fingerprint
25 der = ssl.get_server_certificate((hostname, port)).encode()
26 sha256 = hashlib.sha256(der).hexdigest()
27 print(f" SHA-256: {sha256[:32]}...")
28
29inspect_tls("github.com")
30inspect_tls("google.com")
31
32# ── HMAC for message integrity ─────────────────────────
33secret = b"your-secret-key"
34message = b"amount=1000&to=attacker"
35
36# Sign
37mac = hmac.new(secret, message, hashlib.sha256).hexdigest()
38print(f"
39Message: {message}")
40print(f"HMAC: {mac}")
41
42# Verify (constant-time comparison prevents timing attacks)
43received_mac = mac # in real life, this comes from the request
44is_valid = hmac.compare_digest(
45 hmac.new(secret, message, hashlib.sha256).hexdigest(),
46 received_mac
47)
48print(f"Valid: {is_valid}")
49
50# ── Rate limiter (token bucket concept) ───────────────
51from collections import defaultdict
52import time
53
54class RateLimiter:
55 def __init__(self, max_requests: int, window_seconds: int):
56 self.max = max_requests
57 self.window = window_seconds
58 self.requests: dict[str, list] = defaultdict(list)
59
60 def is_allowed(self, ip: str) -> bool:
61 now = time.time()
62 self.requests[ip] = [t for t in self.requests[ip] if now - t < self.window]
63 if len(self.requests[ip]) >= self.max:
64 return False
65 self.requests[ip].append(now)
66 return True
67
68limiter = RateLimiter(max_requests=5, window_seconds=10)
69for i in range(7):
70 allowed = limiter.is_allowed("192.168.1.1")
71 print(f"Request {i+1}: {'ALLOWED' if allowed else 'RATE LIMITED'}")
← PREV6. Sockets & WebSockets