Computer Networks and Security
How the Internet moves data and how to keep it safe: layering, Ethernet and switches, IP, routing and NAT, UDP and TCP with congestion control, DNS, HTTP/2 and HTTP/3, Wi-Fi, then cryptography, TLS 1.3, passwords, web and network attacks with their defences, firewalls and VPNs. Protocol details follow the current RFCs.
Lessons
- Packet switching: Hosts send data as packets that routers store and forward link by link, sharing each link among everyone's packets, which uses links far better than reserving a circuit for each conversation but means packets can wait in queues, or be dropped when a queue is full.
- Delay, loss and throughput: At each hop a packet's delay is processing plus queueing plus transmission $L/R$ plus propagation $d/s$, so a 1500-byte packet takes 120 microseconds to push onto a 100 Mbit/s link however far it then travels, and a path's throughput is set by its slowest link.
- Layering and encapsulation: The network's job is split into layers, application, transport, network, link and physical, each using only the one below, and on the way down each layer wraps what it was given in its own header, so a frame on the wire is an Ethernet header around an IP header around a TCP header around the application's bytes.
- Detecting bit errors: Noise flips bits on a link, so the sender adds check bits computed from the data, and a parity bit catches any single flipped bit, the Internet checksum adds 16-bit words in ones' complement, and a CRC, the remainder of a polynomial division, catches every burst of errors no longer than its check bits.
- Ethernet frames and MAC addresses: An Ethernet frame carries a 6-byte destination MAC address, a 6-byte source, a 2-byte type saying what is inside (0x0800 for IPv4), 46 to 1500 bytes of data and a 4-byte CRC, and a MAC address names a network card rather than a place, with all ones meaning everyone on the link.
- Switches and self-learning: A switch learns which port leads to each MAC address from the source addresses of the frames it sees, sends a frame only out the port it has learned for the destination and floods it out every other port when it does not know, so a LAN builds its own forwarding table with no configuration.
- Wireless links and Wi-Fi: A radio signal fades with distance and through walls, and a station can neither hear a collision while it transmits nor hear a hidden station on the far side of the access point, so Wi-Fi avoids collisions instead of detecting them, waiting a random backoff before it sends and expecting an acknowledgement for every frame.
- IPv4 addresses and CIDR: An IPv4 address is 32 bits written as four decimal bytes, and a prefix length /n says the first n bits name the network and the rest the host, so 192.168.1.0/24 holds $2^8 = 256$ addresses, 254 usable after the network and broadcast addresses, and borrowing host bits splits a block into smaller subnets.
- The IP datagram, TTL and ICMP: Every IPv4 packet starts with a header of at least 20 bytes carrying the source and destination addresses, a protocol number saying what is inside (6 for TCP, 17 for UDP, 1 for ICMP) and a time to live that each router lowers by one, discarding the packet at zero and sending back an ICMP message, which is how traceroute maps a path.
- Forwarding and longest prefix match: A router looks up each packet's destination in a table of prefixes and sends it out the link of the longest prefix that matches, so a specific route such as `10.1.2.0/24` overrides a broad one such as `10.0.0.0/8`, and `0.0.0.0/0` is the default route that matches everything.
- ARP and the first hop: IP addresses name the two ends of a whole path but each link delivers by MAC address, so a host sends anything off its subnet to its default gateway and finds the gateway's MAC address by broadcasting an ARP request, which is why the MAC addresses change at every hop while the IP addresses stay.
- DHCP, getting an address: A host that joins a network has no address and knows no server, so it broadcasts a DHCP Discover from 0.0.0.0, and in four messages, Discover, Offer, Request, Acknowledge, it leases an address along with the subnet mask, default gateway and DNS servers, renewing the lease before it runs out.
- Link-state routing: In link-state routing every router floods the costs of its own links to all the others, so each one holds the whole map and runs Dijkstra's algorithm to find its shortest path to every destination, as OSPF does inside one network.
- Distance-vector routing: In distance-vector routing each router knows only its neighbours' distance estimates and updates its own with the Bellman-Ford equation $D_x(y) = \min_v \{ c(x,v) + D_v(y) \}$, which needs no global map but spreads good news fast and bad news slowly, as the count-to-infinity problem shows.
- Routing between networks with BGP: The Internet is tens of thousands of autonomous systems, each routing inside itself as it likes, and BGP lets them announce which prefixes they can reach along with the whole path of systems, so each chooses routes by business policy as much as by length and refuses any path that already contains itself.
- Private addresses and NAT: IPv4 has only about 4.3 billion addresses, so homes and offices use the private ranges `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16`, and a NAT router rewrites each outgoing packet's source address and port to its own public address and a fresh port, keeping a table to send replies back, so a connection from outside has no entry to follow unless one is set up.
- IPv6: An IPv6 address is 128 bits written as eight groups of four hex digits, with leading zeros dropped and one run of zero groups shortened to ::, enough for every device to have a public address, and its fixed 40-byte header drops the checksum and leaves fragmentation to the sender.
- Ports and UDP: The transport layer delivers to a process rather than a host by adding 16-bit source and destination ports, and UDP adds nothing more than a length and a checksum in an 8-byte header, which suits DNS lookups and live audio that would rather lose a packet than wait for it.
- Building reliable transfer: Over a channel that corrupts and loses packets, checksums, acknowledgements, a timeout with retransmission and sequence numbers to spot duplicates are enough for reliability, but stop-and-wait sends one packet per round trip, so a 1500-byte packet on a 1 Gbit/s link with a 30 ms round trip keeps the link busy only 0.04% of the time.
- Go-Back-N and Selective Repeat: Letting up to $N$ unacknowledged packets be in flight multiplies utilisation by about $N$, and after a loss Go-Back-N resends everything from the lost packet on while Selective Repeat resends only the lost one, at the cost of the receiver buffering packets that arrive out of order.
- TCP connections and the handshake: TCP numbers bytes rather than packets, opens each connection with a three-way handshake, SYN, SYN-ACK, ACK, in which each side picks an unpredictable initial sequence number, and every acknowledgement number names the next byte expected, which is what connect and accept do underneath.
- Closing a connection and TCP's states: Each direction of a TCP connection closes on its own with a FIN and an ACK, and the side that closes first waits in TIME-WAIT for twice the maximum segment lifetime, so its last ACK can be resent and stray old segments die before the same address and port pair is reused.
- TCP timeouts and fast retransmit: TCP keeps a smoothed estimate of the round-trip time and sets its timeout to that estimate plus four times its variation, and because a timeout is slow it also resends a segment as soon as three duplicate acknowledgements show that later data arrived without it.
- Flow control: A TCP receiver advertises in every segment how much buffer it has free, and the sender never keeps more unacknowledged bytes out than that window, so a fast sender cannot overrun a slow reader, and a window of zero pauses the sender until a probe finds room.
- Congestion control: TCP also limits itself with a congestion window that doubles every round trip in slow start up to a threshold, then grows by one segment per round trip, halves after a loss found by duplicate acknowledgements and falls to one segment after a timeout, an additive-increase multiplicative-decrease sawtooth that shares a bottleneck fairly.
- CUBIC, BBR and ECN: On fast long paths Reno's one segment per round trip takes far too long to refill the window, so CUBIC, the default on most systems, grows it as a cubic function of time since the last loss, while BBR models the path's bandwidth and round-trip time instead of treating loss as the signal, and ECN lets routers mark packets rather than drop them.
- DNS: DNS turns names into addresses through a hierarchy of root, top-level domain and authoritative servers, which a recursive resolver asks on your behalf, mostly over UDP port 53, caching each answer for its time to live, with record types such as A, AAAA, CNAME, MX and NS.
- HTTP requests and responses: HTTP is a stateless exchange in which a client sends a method, a target and headers and the server answers with a status code, headers and a body, so safe and idempotent methods can be retried, and a cookie is how a server recognises the same client from one request to the next.
- HTTP/1.1, HTTP/2 and HTTP/3: Each new TCP connection costs a round trip before the first request, so HTTP/1.1 keeps connections open, HTTP/2 multiplexes many requests over one connection, and HTTP/3 runs over QUIC on UDP to set up transport and encryption together in one round trip and to keep one lost packet from stalling every request.
- Caches and CDNs: A response marked with a Cache-Control lifetime can be reused without asking the server again, and a content delivery network keeps copies on servers near users and steers each user to a nearby one through DNS or anycast, which cuts round trips that no faster link could.
- Threat models: Security starts by naming what must be protected, confidentiality, integrity or availability, and against whom, and on a network the attacker is assumed able to read, drop, change and inject any packet, so a defence has to work even when the network itself is hostile.
- Symmetric encryption: With a shared secret key, a block cipher such as AES scrambles 128-bit blocks, and a mode such as counter mode with a fresh nonce turns it into a cipher for messages of any length, because encrypting identical blocks identically, as ECB mode does, leaks the pattern of the data.
- Hashes and MACs: A cryptographic hash such as SHA-256 maps any input to 256 bits so that finding an input with a given hash, or two inputs with the same hash, is infeasible, and mixing in a secret key, as HMAC does, gives a message authentication code that only key holders can compute, which detects tampering that a checksum would miss.
- Authenticated encryption: Encryption alone hides a message but does not stop an attacker flipping its bits, so modern protocols use an AEAD such as AES-GCM or ChaCha20-Poly1305, which encrypts and authenticates together and rejects anything altered, as long as a nonce is never reused with the same key.
- Public-key encryption with RSA: RSA publishes $n = pq$ and $e$ and keeps $d$ with $ed \equiv 1 \pmod{(p-1)(q-1)}$, so anyone can compute $c = m^e \bmod n$ but only the key holder can undo it with $c^d \bmod n$, and its safety rests on factoring $n$ being hard.
- Diffie-Hellman key exchange: Two parties who have never met agree on a secret over a public channel by publishing $g^a \bmod p$ and $g^b \bmod p$ and each raising the other's number to their own secret to get $g^{ab} \bmod p$, which an eavesdropper cannot find but a man in the middle can hijack unless the exchange is authenticated.
- Signatures and certificates: A signature made with a private key lets anyone check with the public key that a message came unchanged from the key holder, and a certificate is a certificate authority's signature binding a domain name to a public key, so a browser trusts a server's key by following a chain of signatures up to a root it already holds.
- The TLS 1.3 handshake: In TLS 1.3 the client's hello carries a key share and the server answers with its own share, its certificate and a signature over the handshake so far, so after one round trip both sides hold fresh keys, the client knows it reached the real server, and everything after is encrypted and authenticated.
- Passwords and authentication: A server should store not passwords but salted, deliberately slow hashes of them, such as Argon2id, scrypt or bcrypt, so a stolen database must be attacked one guess at a time for each account, and a second factor or a passkey means a stolen password alone does not get in.
- Injection, when data becomes code: SQL injection and shell command injection share one flaw with the buffer overflow, untrusted input reaching a place where it is read as code or control data, and the defence is to keep the two apart with parameterised queries, argument lists instead of shell strings and bounded copies.
- Cross-site scripting: The same-origin policy keeps one site's scripts away from another's data, so an attacker who gets a script into a trusted page runs with that page's full authority, and the defence is to encode output for where it lands, backed by a content security policy and HttpOnly cookies.
- Cross-site request forgery: A browser can attach a site's cookies to a request that another page started, so a forged request looks like the user's own, and the defences are SameSite cookies, anti-forgery tokens that another origin cannot read, and checking where a request came from.
- Denial of service: A denial-of-service attack exhausts a resource instead of breaking in, as when a SYN flood fills a server's table of half-open connections or a reflection attack turns small spoofed requests into large replies, and the defences are SYN cookies, filtering spoofed source addresses, rate limits and capacity spread over many sites.
- When the network lies: ARP, DNS and BGP were all built to believe what they are told, so a forged answer can redirect traffic at the link, the name or the route, and each now has a defence that checks the claim, dynamic ARP inspection, DNSSEC and RPKI, while TLS keeps a redirected connection from being read.
- Firewalls: A packet filter checks each packet against an ordered list of rules on addresses, protocol and ports, the first match deciding, and a stateful firewall remembers connections started from inside so it can let their replies in while denying everything else by default.
- VPNs and tunnels: A VPN wraps each whole IP packet, encrypted and authenticated, inside another packet addressed to the VPN server, so the local network sees only traffic to that server, while the server and everything beyond it still see the traffic as usual.
- One web request, end to end: Opening a page on a laptop that just joined a network takes DHCP for an address, ARP for the gateway, DNS for the server's address, a TCP handshake, a TLS handshake and finally an HTTP request, each one carried down through every layer and across every hop.