The Internet was built for cooperation, not defence. Packets cross networks owned by strangers, and anyone on the path can read, change, drop or forge them. Network security is the set of tools that let two parties communicate safely over such a network: cryptography to hide and protect data, certificates to prove identity, and firewalls, intrusion detection and VPNs to control what traffic flows where.
TLS (Transport Layer Security) is the protocol that puts the "S" in HTTPS, and it ties most of these ideas together. Interviewers commonly ask "what happens during a TLS handshake", "what is the difference between symmetric and asymmetric encryption", "how does a browser know a certificate is genuine", "what changed in TLS 1.3", "how does Diffie-Hellman work", "what is a man-in-the-middle attack", and "stateful versus stateless firewall". This lesson builds the cryptography from the ground up in plain terms, then uses it to explain TLS, then covers attacks and defences.
The CIA triad: what "secure" means
Security goals are usually stated as three properties, called the CIA triad:
- Confidentiality: only the intended parties can read the data. Achieved with encryption. Violated by eavesdropping.
- Integrity: the data has not been changed in transit or storage, and any change is detected. Achieved with hashes, MACs and signatures. Violated by tampering.
- Availability: the system is reachable and working when needed. Achieved with redundancy, rate limiting and DDoS protection. Violated by denial-of-service attacks.
Two more properties come up constantly in networking:
- Authentication: you are talking to who you think you are talking to. Achieved with certificates, passwords, keys.
- Non-repudiation: the sender cannot later deny having sent a message. Achieved with digital signatures.
A useful habit in interviews: when someone describes an attack, name which property it breaks. Eavesdropping on Wi-Fi breaks confidentiality. Changing a bank transfer amount breaks integrity. A DDoS breaks availability. Phishing a login page breaks authentication.
Cryptography building blocks
You do not need the mathematics, but you must know what each tool does, what it does not do, and the names of the common algorithms.
Symmetric encryption
In symmetric encryption, the same secret key both encrypts and decrypts:
plaintext --[encrypt with key K]--> ciphertext --[decrypt with key K]--> plaintext
- Fast: modern CPUs have dedicated AES instructions and encrypt gigabytes per second.
- Problem: both sides need the same key, and you cannot just send it over the network in the clear. This is the key distribution problem.
- Algorithms: AES (Advanced Encryption Standard, 128 or 256-bit keys) and ChaCha20 (fast on devices without AES hardware, such as older phones). Old and broken: DES, 3DES, RC4.
Modern protocols use AEAD modes (authenticated encryption with associated data), such as AES-GCM and ChaCha20-Poly1305. An AEAD cipher encrypts and produces an authentication tag in one step, so it gives confidentiality and integrity together. If an attacker flips a single bit of ciphertext, decryption fails instead of producing silently corrupted plaintext.
Asymmetric (public-key) encryption
In asymmetric cryptography, each party has a key pair: a public key shared with everyone and a private key kept secret. They are mathematically linked, but you cannot practically derive the private key from the public one.
- Encrypt with someone's public key, and only their private key can decrypt. Anyone can lock the box; only the owner can open it.
- Sign with your private key, and anyone can verify with your public key (see signatures below).
Algorithms: RSA (based on the difficulty of factoring large numbers; 2048-bit keys or larger today) and elliptic-curve cryptography (ECC), such as ECDSA and Ed25519 for signatures and X25519 for key exchange. ECC achieves similar strength with much smaller keys: a 256-bit elliptic-curve key is roughly as strong as a 3072-bit RSA key.
Public-key operations are hundreds to thousands of times slower than symmetric ones. So real protocols use a hybrid design: public-key cryptography only to agree on a key and prove identity, then fast symmetric encryption for the actual data. TLS is exactly this.
| Symmetric | Asymmetric | |
|---|---|---|
| Keys | One shared secret | Public + private pair |
| Speed | Very fast | Slow |
| Main problem | Distributing the key | Speed, and trusting the public key |
| Used for | Bulk data encryption | Key exchange, signatures, identity |
| Examples | AES-GCM, ChaCha20-Poly1305 | RSA, ECDSA, Ed25519, X25519 |
Hashing
A cryptographic hash function turns input of any size into a fixed-size digest (fingerprint). SHA-256 always produces 256 bits (64 hex characters). A good hash has these properties:
- Deterministic: the same input always gives the same digest.
- One-way (pre-image resistant): given a digest, you cannot find an input that produces it.
- Collision resistant: you cannot find two different inputs with the same digest.
- Avalanche effect: a tiny change in input changes the output completely.
The avalanche effect is easy to see. Changing one letter's case:
SHA-256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
SHA-256("Hello") = 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
Hashing is not encryption: there is no key and no way back. Uses include file integrity checks (download checksums), digital signatures (you sign the hash, not the whole document), and data structures such as Git commits.
Current: SHA-256, SHA-384, SHA-3, BLAKE2/BLAKE3. Broken for security use: MD5 and SHA-1 (practical collisions exist).
Common mistake
Never store passwords with plain SHA-256. Fast hashes let attackers try billions of guesses per second. Use a deliberately slow, salted password hashing function: bcrypt, scrypt or Argon2. A salt is a random value stored with each hash so that identical passwords produce different hashes and precomputed tables are useless.
Message authentication codes (MACs)
A plain hash proves nothing about who made it: an attacker who changes a message can just recompute its hash. A MAC (message authentication code) mixes in a shared secret key, so only someone with the key can produce a valid tag.
The most common construction is HMAC (hash-based MAC), such as HMAC-SHA256:
tag = HMAC-SHA256(key = "secret-key", message = "amount=500&to=asha")
= c77ce65795fa6939d4439798b358f01ef966efc9b3dcd7e64640f902f757ce8c
The sender transmits the message plus the tag. The receiver, who knows the key, recomputes the tag and compares. If an attacker changes 500 to 5000, they cannot produce a matching tag without the key. Webhooks (for example payment provider callbacks) commonly use HMAC signatures in a header so you can verify the request is genuine.
A MAC gives integrity and authentication but not non-repudiation: both sides have the key, so either could have created the tag.
Digital signatures
A digital signature is the public-key version of a MAC:
Signing (sender, uses PRIVATE key):
digest = SHA-256(message)
signature = Sign(private_key, digest)
send: message + signature
Verifying (anyone, uses sender's PUBLIC key):
digest' = SHA-256(message)
Verify(public_key, digest', signature) -> valid / invalid
Because only the holder of the private key can produce the signature, it proves who signed it (authentication), that it was not altered (integrity), and the signer cannot deny it (non-repudiation). Anyone with the public key can verify, without needing a shared secret.
Signatures are what make certificates, software updates, DNSSEC and JWTs trustworthy.
| Tool | Key | Gives | Example |
|---|---|---|---|
| Hash | None | Integrity against accidents only | SHA-256 checksum of a download |
| MAC | Shared secret | Integrity + authentication | HMAC on a webhook |
| Signature | Private signs, public verifies | Integrity + authentication + non-repudiation | Certificate signed by a CA |
| Encryption | Symmetric or public key | Confidentiality | AES-GCM on TLS records |
Interview tip
A common trap: "you encrypt with the private key to sign". Avoid that phrasing. Say "you sign with the private key and verify with the public key". For RSA the maths looks similar, but for ECDSA and Ed25519 signing is not encryption at all.
Diffie-Hellman key exchange
Diffie-Hellman (DH) solves the key distribution problem: two parties who have never met agree on a shared secret over a public channel, even though an eavesdropper sees every message.
The idea with paint
The classic analogy:
- Alice and Bob publicly agree on a common colour, yellow.
- Each picks a secret colour: Alice red, Bob blue.
- Each mixes the common colour with their secret: Alice sends orange (yellow + red), Bob sends green (yellow + blue). An eavesdropper sees yellow, orange and green.
- Alice adds her red to Bob's green; Bob adds his blue to Alice's orange. Both get yellow + red + blue, the same brown.
- The eavesdropper cannot "unmix" orange to get red, so cannot make the brown.
Mixing paint is easy; unmixing is hard. DH uses a mathematical operation with the same property: modular exponentiation is easy, but reversing it (the discrete logarithm problem) is infeasible for large numbers.
Worked example with tiny numbers
x mod p means the remainder after dividing x by p.
Public values (everyone, including the attacker, knows them): prime p = 23, generator g = 5.
Step 1. Secrets. Alice picks secret a = 6. Bob picks secret b = 15.
Step 2. Public values.
- Alice computes
A = g^a mod p = 5^6 mod 23.5^6 = 15625, and15625 = 23 × 679 + 8, soA = 8. - Bob computes
B = g^b mod p = 5^15 mod 23 = 19. (Step by step:5^2 = 25 mod 23 = 2;5^4 = 2^2 = 4;5^8 = 4^2 = 16;5^15 = 5^8 × 5^4 × 5^2 × 5^1 = 16 × 4 × 2 × 5 = 640;640 = 23 × 27 + 19, so19.)
Alice sends 8; Bob sends 19. The attacker sees p = 23, g = 5, A = 8, B = 19.
Step 3. Shared secret.
- Alice computes
B^a mod p = 19^6 mod 23.19 mod 23 = -4, so19^6has the same remainder as(-4)^6 = 4096.4096 = 23 × 178 + 2, so the result is2. - Bob computes
A^b mod p = 8^15 mod 23.8^2 = 64 mod 23 = 18;8^4 = 18^2 = 324 mod 23 = 2;8^8 = 2^2 = 4;8^15 = 8^8 × 8^4 × 8^2 × 8 = 4 × 2 × 18 × 8 = 1152;1152 = 23 × 50 + 2, so2.
Both get shared secret = 2, without ever sending it. This works because both equal g^(ab) mod p = 5^90 mod 23.
Why the attacker is stuck: to get the secret, they need a or b, which means solving 5^a mod 23 = 8 for a. With p = 23 they can try all 22 values and find a = 6. With a 2048-bit prime, or with elliptic-curve DH (ECDHE on curve X25519), there is no known feasible way.
What Diffie-Hellman does not do
DH alone gives no authentication. A man in the middle can run one DH exchange with Alice and another with Bob, and relay (and read) everything. This is why TLS combines DH with certificates and signatures: the server signs its DH value so the client knows it came from the real server.
Forward secrecy
In TLS, the "E" in ECDHE and DHE means ephemeral: fresh DH secrets are generated for every connection and thrown away afterwards. This gives forward secrecy: if the server's long-term private key is stolen next year, past recorded sessions still cannot be decrypted, because their DH secrets no longer exist anywhere.
The older RSA key exchange (removed in TLS 1.3) worked differently: the client encrypted a random secret with the server's RSA public key. Anyone who later stole the private key could decrypt every recorded session. That is the main reason TLS 1.3 dropped it.
Certificates and the chain of trust
DH needs authentication, and authentication needs the client to know the server's real public key. How does your browser know that a public key really belongs to bank.example.com and not to an attacker on the café Wi-Fi?
What a certificate is
An X.509 certificate is a document binding a public key to an identity, signed by a trusted third party. Key fields:
Certificate
Subject: CN=www.example.com
Subject Alt Names: www.example.com, example.com <- names covered
Issuer: CN=Example Intermediate CA R3
Validity: 2026-09-01 to 2026-11-30
Public key: EC P-256 (the server's public key)
Key usage: digital signature
Serial number: 04:a1:...
Signature: ECDSA-SHA256 by the issuer's private key
The browser checks the requested host name against the Subject Alternative Names (SAN) list (the old Common Name field is ignored by modern browsers). A wildcard such as *.example.com covers one level: api.example.com but not v2.api.example.com and not example.com itself.
Certificate authorities and the chain
A certificate authority (CA) is an organisation trusted to verify that whoever requests a certificate really controls the domain, then sign the certificate. For an ordinary (domain-validated) certificate, the CA checks control by asking you to place a file on the website or a TXT record in DNS. Let's Encrypt automates this with the ACME protocol.
CAs do not sign server certificates directly with their most precious key. They use a hierarchy:
+---------------------------+
| Root CA certificate | self-signed; shipped inside the OS /
| (key kept offline) | browser "trust store"
+-------------+-------------+
| signs
+-------------v-------------+
| Intermediate CA cert | sent by the server during the handshake
+-------------+-------------+
| signs
+-------------v-------------+
| Leaf (server) certificate | www.example.com, sent by the server
+---------------------------+
To validate, the browser:
- Receives the leaf and intermediate certificates from the server.
- Checks the leaf's signature with the intermediate's public key.
- Checks the intermediate's signature with the root's public key.
- Confirms the root is in its trust store (a list of about 100 to 150 root CAs preinstalled by the OS or browser vendor).
- Checks that every certificate is within its validity dates, that the host name matches a SAN, that the certificates are allowed to be used this way, and that none is revoked.
If any check fails, you see a full-page certificate warning.
Why intermediates? The root key can stay offline in a vault. If an intermediate key is compromised, only that intermediate is revoked, not the whole root.
Revocation
If a private key leaks, the certificate must be revoked before it expires:
- CRL (certificate revocation list): a signed list of revoked serial numbers. Lists grow large.
- OCSP (Online Certificate Status Protocol): ask the CA "is this serial still valid?". Leaks browsing history to the CA and adds latency.
- OCSP stapling: the server fetches a signed, time-stamped OCSP response and "staples" it into the handshake.
Revocation has always been unreliable in practice, so the industry is moving to short-lived certificates (Let's Encrypt uses 90 days, with shorter options) so a stolen key is useful only briefly.
Certificate Transparency (CT) adds a safety net: CAs must log every certificate they issue in public, append-only logs, and browsers require proof of logging. Domain owners monitor the logs and spot certificates issued for their domains without permission.
The TLS handshake
TLS sits between TCP and the application. Before any HTTP is sent, client and server run a handshake to:
- Agree on the protocol version and cipher suite (the set of algorithms).
- Authenticate the server (and optionally the client) with certificates.
- Agree on shared symmetric keys through (EC)DHE.
After that, the record protocol encrypts application data with the agreed AEAD cipher.
The versions: SSL 2.0 and 3.0 and TLS 1.0 and 1.1 are deprecated and insecure. TLS 1.2 (2008) is still widely supported. TLS 1.3 (RFC 8446, 2018) is the modern default.
TLS 1.2 handshake (ECDHE)
Client Server
| |
|--- ClientHello ------------------------------>| versions, cipher suites,
| (client random, suites, extensions: SNI) | client random
| |
|<-- ServerHello -------------------------------| chosen suite, server random
|<-- Certificate -------------------------------| leaf + intermediates
|<-- ServerKeyExchange -------------------------| server ECDHE public value,
| (signed with certificate's private key) | signed
|<-- ServerHelloDone ---------------------------|
| (1st round trip done)
|--- ClientKeyExchange ------------------------>| client ECDHE public value
|--- ChangeCipherSpec ------------------------->| "switching to encryption"
|--- Finished (encrypted) --------------------->| hash of whole handshake
| |
|<-- ChangeCipherSpec --------------------------|
|<-- Finished (encrypted) ----------------------|
| (2nd round trip done)
|=== encrypted HTTP request ===================>|
Step by step:
- ClientHello: the client sends the TLS versions and cipher suites it supports, a 32-byte random number, and extensions. SNI (Server Name Indication) names the host it wants, so a server hosting many sites can pick the right certificate.
- ServerHello: the server picks a version and suite, for example
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, and sends its own random number. - Certificate: the server sends its certificate chain.
- ServerKeyExchange: the server sends its ephemeral ECDHE public value, signed with the certificate's private key. This signature is what stops a man in the middle from substituting their own DH value.
- ServerHelloDone.
- The client validates the chain and the signature, then sends ClientKeyExchange with its own ECDHE public value.
- Both sides now compute the same pre-master secret from DH, and derive the session keys from it plus both random numbers.
- Each side sends ChangeCipherSpec and an encrypted Finished message containing a hash of every handshake message. If an attacker altered anything (for example removed strong cipher suites to force a weak one, a downgrade attack), the hashes will not match and the handshake fails.
Cost: two round trips before the first byte of HTTP. Add one for TCP, so a new HTTPS connection over TLS 1.2 costs three round trips. On a 100 ms mobile link, that is 300 ms before the request is even sent.
Reading the suite name TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: key exchange ECDHE, server authentication by RSA signature, bulk encryption AES-128 in GCM mode, SHA-256 for key derivation.
TLS 1.3 handshake
TLS 1.3 redesigned the handshake for speed and safety:
Client Server
| |
|--- ClientHello ------------------------------>|
| + key_share (client ECDHE public value, |
| guessed group, e.g. X25519) |
| + supported suites, SNI, ALPN |
| |
|<-- ServerHello + key_share -------------------| keys derived NOW;
|<-- {EncryptedExtensions} ---------------------| everything below
|<-- {Certificate} -----------------------------| is encrypted
|<-- {CertificateVerify} -----------------------| signature over handshake
|<-- {Finished} --------------------------------|
| (1 round trip done)
|--- {Finished} ------------------------------->|
|=== {encrypted HTTP request} =================>| sent right away
What changed:
- One round trip. The client guesses the key-exchange group and sends its key share in the very first message. The server replies with its share, and both can derive keys immediately. (If the guess is wrong, the server sends a HelloRetryRequest, costing one more round trip; rare in practice.)
- Most of the handshake is encrypted, including the server's certificate, so eavesdroppers learn less.
- Only forward-secret key exchange: static RSA key exchange and plain DH are gone. Every connection uses (EC)DHE.
- Fewer, stronger cipher suites: just five, all AEAD, for example
TLS_AES_128_GCM_SHA256andTLS_CHACHA20_POLY1305_SHA256. Suite names no longer include the key exchange or signature algorithm, which are negotiated separately. - Removed weak features: compression (CRIME attack), renegotiation, CBC mode ciphers, RC4, SHA-1, MD5.
- 0-RTT resumption: a client that connected before can send application data in its very first flight using a pre-shared key from the earlier session.
Common mistake
0-RTT data can be replayed: an attacker who records the first flight can resend it, and the server may process it twice. Servers should accept only idempotent requests (such as GET) as 0-RTT data. Say this if 0-RTT comes up in an interview.
| TLS 1.2 | TLS 1.3 | |
|---|---|---|
| Full handshake | 2 RTT | 1 RTT |
| Resumption | 1 RTT (session id or ticket) | 1 RTT, or 0-RTT with replay risk |
| Key exchange | RSA, DHE, ECDHE | (EC)DHE only, always forward secret |
| Certificate visible to eavesdroppers | Yes | No (encrypted) |
| Cipher suites | Dozens, some weak | 5 AEAD suites |
| Downgrade protection | Finished hash | Finished hash plus special values in server random |
HTTPS in practice
HTTPS is simply HTTP sent inside a TLS connection, normally on port 443. It gives:
- Confidentiality: path, query string, headers, cookies and body are encrypted.
- Integrity: no one can inject ads or malware into the page.
- Server authentication: you are talking to the real owner of the domain.
What HTTPS does not hide: the server's IP address, the SNI host name (sent in plain text in ClientHello, unless the newer Encrypted Client Hello extension is used), the plain-DNS lookup unless DoH/DoT is used, and traffic timing and sizes.
HSTS (HTTP Strict Transport Security) closes a gap. If a user types example.com, the browser first tries plain http://, and an attacker can intercept that first request and keep the user on HTTP (an SSL stripping attack). The response header Strict-Transport-Security: max-age=31536000; includeSubDomains tells the browser to use HTTPS only for this site for a year. Sites can also join the browser's built-in HSTS preload list so even the very first visit uses HTTPS.
Mutual TLS (mTLS) is TLS where the client also presents a certificate. It is common between microservices and in zero-trust networks: both sides prove their identity.
Interview tip
To answer "explain the TLS handshake" well, structure it as three goals: negotiate algorithms, authenticate the server via its certificate chain and a signature over the key exchange, and derive shared keys with ephemeral Diffie-Hellman. Then mention 2 RTT for TLS 1.2 versus 1 RTT for 1.3, and forward secrecy.
Common attacks
Man-in-the-middle (MITM)
In a man-in-the-middle attack, the attacker sits between two parties, relaying and possibly changing traffic while each side believes it is talking directly to the other. Ways to get into the middle include a malicious Wi-Fi hotspot, ARP spoofing on the local network, DNS spoofing, or a compromised router.
TLS defeats MITM as long as certificate validation is done correctly: the attacker cannot present a valid certificate for bank.example.com without the bank's private key or a misbehaving CA. MITM succeeds when users click through certificate warnings, when apps disable certificate checks ("trust all certificates" in code, a common bug), or when an attacker installs their own root CA on the victim's device. Corporate TLS inspection proxies work exactly that way, with the company's root CA installed on employee machines.
ARP spoofing
ARP (Address Resolution Protocol) maps IP addresses to MAC addresses on a local network, as covered in the data link layer lesson. ARP has no authentication: hosts accept unsolicited replies.
The attack:
- The attacker on the same LAN sends forged ARP replies to the victim: "the gateway
192.168.1.1is at MACaa:aa:aa:aa:aa:aa" (the attacker's MAC). - It sends the gateway a matching lie about the victim's IP.
- Both now send their frames to the attacker, who forwards them (so nothing seems broken) while reading or altering them.
Defences: Dynamic ARP Inspection on managed switches (checks ARP replies against a DHCP snooping table), static ARP entries for critical hosts, network segmentation, and, most importantly, end-to-end encryption such as TLS, which makes the intercepted traffic useless.
DNS spoofing
Covered in detail in the DNS lesson: the attacker makes a victim resolve a name to the wrong IP, by poisoning a resolver cache, by answering faster than the real resolver on a local network, or by hijacking the victim's resolver settings. Defences: DNSSEC, DoH/DoT, and again TLS certificate validation, since the fake server cannot present a valid certificate.
Denial of service: DoS and DDoS
A denial-of-service (DoS) attack makes a service unavailable. A distributed DoS (DDoS) uses many machines, often a botnet of infected devices, so blocking one source does not help. Categories:
- Volumetric: saturate the bandwidth with sheer traffic, often via amplification (DNS, NTP, memcached reflection using spoofed source addresses).
- Protocol: exhaust state in servers, firewalls or load balancers, for example SYN floods.
- Application layer (L7): send expensive but legitimate-looking requests (searches, logins) that exhaust CPU or database capacity.
Defences: anycast networks and scrubbing services that absorb and filter attack traffic (CDNs and DDoS protection providers), rate limiting, caching, autoscaling, and WAF rules for application-layer floods.
SYN flood
A SYN flood abuses the TCP three-way handshake:
- The attacker sends a flood of SYN packets, usually with spoofed source IPs.
- For each, the server replies SYN-ACK and stores a half-open connection in its SYN queue (backlog), waiting for the final ACK.
- The ACKs never come. The queue fills, and legitimate clients' SYNs are dropped.
The main defence is SYN cookies: when the queue is full, the server stores nothing. Instead, it encodes the connection details into the initial sequence number of its SYN-ACK (a keyed hash of the addresses, ports and a timestamp). A legitimate client's ACK returns that number plus one, and the server reconstructs the connection from it. Linux enables this with net.ipv4.tcp_syncookies. Other defences: larger backlogs, shorter SYN-ACK timeouts and upstream filtering.
Replay attacks
In a replay attack, the attacker records a valid message and resends it later, for example a captured "transfer 500 rupees" request. Encryption alone does not stop this, because the attacker does not need to read the message, just repeat it.
Defences: nonces (one-time random numbers the server tracks), timestamps with a short acceptance window, sequence numbers (TLS records have implicit sequence numbers, so a replayed record fails authentication), and idempotency keys at the application level.
XSS and CSRF, briefly
These are web application attacks, but they often come up alongside network security.
- XSS (cross-site scripting): an attacker gets their JavaScript to run on your site, for example by storing
<script>in a comment that is rendered without escaping. The script runs with the victim's privileges on your origin: it can read the page, act as the user, and steal non-HttpOnlycookies. Defences: escape output by context, a Content-Security-Policy header restricting script sources,HttpOnlycookies, and frameworks that escape by default. - CSRF (cross-site request forgery): a malicious site makes the victim's browser send a request to your site, such as an auto-submitting form that POSTs to
/transfer, and the browser attaches the victim's cookies automatically. Defences:SameSite=LaxorStrictcookies, anti-CSRF tokens (a random value in the form that the attacker's site cannot read), and checking theOriginheader.
The difference in one line: XSS exploits the user's trust in a site (attacker code runs on the site); CSRF exploits the site's trust in the user's browser (the browser sends authenticated requests the user did not intend).
Firewalls
A firewall enforces rules about which traffic may pass between networks or into a host. Rules are evaluated in order, usually ending with a default deny.
Packet-filtering (stateless) firewalls
A stateless packet filter looks at each packet in isolation: source and destination IP, protocol, source and destination port, sometimes TCP flags. Example rules:
# action proto source dest dport
1 allow tcp any 203.0.113.10 443
2 allow tcp 10.0.0.0/8 203.0.113.10 22
3 deny any any any any
Fast and simple, but stateless filters cannot tell a genuine reply from an unsolicited packet. To let replies back to your outbound connections, you must allow broad ranges of high ports, which attackers can abuse. Router ACLs and cloud network ACLs (such as AWS NACLs) are stateless.
Stateful firewalls
A stateful firewall tracks connections in a state table. When an internal host opens a connection to 198.51.100.7:443, the firewall records it, and automatically allows the matching return packets. Unsolicited inbound packets that match no entry are dropped. Packets that do not fit the TCP state machine (an ACK with no prior SYN) can also be rejected.
Linux iptables/nftables with connection tracking (ct state established,related accept) and cloud security groups (such as AWS security groups) are stateful.
Application-layer firewalls and proxies
An application-layer firewall (or next-generation firewall) understands protocols such as HTTP, DNS or SMTP, and can block by URL, user, application or content. A WAF (web application firewall) specialises in HTTP: it inspects requests for SQL injection, XSS patterns, malicious bots and abusive rates. Deeper inspection costs more CPU and adds latency, and for HTTPS the device must terminate TLS to see inside.
| Type | Looks at | Strength | Weakness |
|---|---|---|---|
| Stateless packet filter | Headers of each packet | Very fast, simple | No connection context, coarse rules |
| Stateful | Headers + connection state | Allows replies safely, blocks unsolicited traffic | State table can be exhausted |
| Application / WAF | Full application payload | Blocks attacks inside allowed ports | Slower, must decrypt TLS, needs tuning |
IDS and IPS
- An IDS (intrusion detection system) watches traffic (often a mirrored copy) and alerts on suspicious patterns. It does not block. Examples: Snort, Suricata, Zeek.
- An IPS (intrusion prevention system) sits inline and blocks malicious traffic as it passes.
Both detect attacks by signatures (known attack patterns, like antivirus) or anomalies (deviation from normal behaviour, which can catch new attacks but produces more false positives). An IPS must be tuned carefully: a false positive blocks legitimate users.
VPNs
A VPN (virtual private network) creates an encrypted tunnel over an untrusted network, so remote devices or sites behave as if they were on the same private network. The original packet is encrypted and wrapped inside a new packet addressed to the VPN gateway, which unwraps and forwards it.
[laptop 10.8.0.5] ==== encrypted tunnel over Internet ==== [VPN gateway]
inner packet: 10.8.0.5 -> 10.0.1.20 (private server) |
outer packet: 49.36.x.x -> 203.0.113.1 (gateway) +--> 10.0.1.20
Two main uses: site-to-site (connect office networks over the Internet) and remote access (employees reaching the company network from home). Consumer VPNs instead route all your traffic through the provider, hiding it from your local network but trusting the provider.
IPsec versus TLS-based VPNs
IPsec works at the network layer. It protects IP packets with:
- AH (Authentication Header): integrity and authentication only, no encryption; rarely used today because it breaks through NAT.
- ESP (Encapsulating Security Payload): encryption plus integrity; the normal choice.
- IKE (Internet Key Exchange), usually IKEv2, on UDP 500 (and 4500 when traversing NAT), negotiates keys.
- Transport mode protects the payload between two hosts; tunnel mode wraps the whole original packet, used for site-to-site VPNs.
TLS-based VPNs (often called SSL VPNs; OpenVPN and many commercial remote-access products) run over TLS, usually on TCP or UDP 443. Because port 443 is almost never blocked, they pass through hotel and corporate firewalls easily, and clientless versions even run in a browser.
WireGuard is a newer, very small VPN protocol over UDP using modern fixed cryptography (Curve25519, ChaCha20-Poly1305). It is fast and simple to configure, and has become a popular choice.
| IPsec | TLS VPN | WireGuard | |
|---|---|---|---|
| Layer | Network (3) | Above transport | Network, over UDP |
| Typical use | Site-to-site, OS-native remote access | Remote access through strict firewalls | Both; modern setups |
| Firewall friendliness | Needs UDP 500/4500 and ESP | Excellent (port 443) | Needs one UDP port |
| Complexity | High | Medium | Low |
SSH and key-based authentication
SSH (Secure Shell) gives encrypted remote login, command execution, file transfer (SFTP, SCP) and port forwarding, on TCP port 22. It replaced Telnet and rlogin, which sent passwords in plain text. The application protocols lesson compares it with Telnet and FTP.
An SSH session has two authentication steps:
- Server authentication. The server proves its identity with its host key. The first time you connect, the client shows the key's fingerprint and asks you to accept it (trust on first use), then stores it in
~/.ssh/known_hosts. If the key changes later, SSH shows a loud "REMOTE HOST IDENTIFICATION HAS CHANGED" warning, which could mean a MITM attack or simply a rebuilt server. - User authentication. By password, or better, by public key.
How public-key login works
# 1. On your laptop: create a key pair (private key stays here)
ssh-keygen -t ed25519 -C "you@laptop"
# -> ~/.ssh/id_ed25519 (private, keep secret, protect with passphrase)
# -> ~/.ssh/id_ed25519.pub (public, safe to share)
# 2. Put the public key on the server, in ~/.ssh/authorized_keys
ssh-copy-id user@server.example.com
# 3. Log in; no password is sent
ssh user@server.example.com
During login:
- Client and server do a key exchange (ECDH, typically curve25519) and set up an encrypted channel. The server signs the exchange with its host key.
- The client says "I'd like to authenticate with this public key".
- The server checks the key is listed in
authorized_keys. - The client signs data unique to this session (including the session identifier) with its private key.
- The server verifies the signature with the stored public key. Success means the client holds the private key, without the private key ever leaving the laptop.
Why keys beat passwords: nothing secret crosses the network, there is nothing to guess with brute force, and a compromised server learns only your public key. Best practice is to disable password login (PasswordAuthentication no in sshd_config), protect private keys with a passphrase and use ssh-agent to avoid retyping it.
Interview questions
Q1. What is the difference between symmetric and asymmetric encryption?
Symmetric encryption uses one shared key for both directions and is fast, but the key must somehow be shared securely. Asymmetric encryption uses a public/private key pair, which solves key distribution and enables signatures, but is much slower. Protocols like TLS use asymmetric cryptography to authenticate and agree on a key, then symmetric encryption for the data.
Q2. How do hashing, MACs and digital signatures differ?
A hash is a keyless fingerprint that detects accidental changes but proves nothing about who made it. A MAC such as HMAC uses a shared secret key, so it gives integrity and authentication between parties who share the key. A digital signature uses a private key to sign and a public key to verify, adding non-repudiation and letting anyone verify.
Q3. Explain Diffie-Hellman.
Both sides agree on public values p and g, pick private secrets a and b, and exchange g^a mod p and g^b mod p. Each raises the other's value to its own secret and obtains g^(ab) mod p. An eavesdropper would have to solve the discrete logarithm problem to find the secret. DH alone is vulnerable to MITM, so TLS authenticates it with a certificate signature.
Q4. What is forward secrecy?
It means a future compromise of the server's long-term private key does not expose past sessions. It is achieved with ephemeral Diffie-Hellman: each session's key-exchange secrets are discarded after use. TLS 1.3 requires it.
Q5. Walk through the TLS 1.3 handshake.
The client sends ClientHello with supported suites and a key share for a guessed group. The server replies with ServerHello and its key share; both derive handshake keys. The server then sends, encrypted, its certificate, a CertificateVerify signature over the handshake and Finished. The client verifies these, sends Finished, and can send application data, all in one round trip.
Q6. What are the main differences between TLS 1.2 and 1.3?
TLS 1.3 takes one round trip instead of two, encrypts most of the handshake including the certificate, removes non-forward-secret key exchange and weak ciphers, and reduces cipher suites to five AEAD suites. It also adds 0-RTT resumption, which has replay risks.
Q7. How does a browser verify a server's certificate?
It builds a chain from the leaf certificate through intermediates to a root in its trust store, verifying each signature. It checks that the host name matches a Subject Alternative Name, that the certificates are within their validity period and allowed usage, and checks revocation status and Certificate Transparency proofs.
Q8. What is a man-in-the-middle attack, and how does TLS prevent it?
An attacker secretly relays and possibly alters traffic between two parties. TLS prevents it because the attacker cannot produce a valid certificate and signature for the real domain, so validation fails. It succeeds only if validation is skipped, the user ignores warnings, or a rogue root CA is trusted.
Q9. How does a SYN flood work, and what are SYN cookies?
The attacker sends many SYNs, often with spoofed sources, and never completes the handshake, filling the server's queue of half-open connections. With SYN cookies, the server stores nothing and encodes the connection state in its initial sequence number; a real client's ACK returns it so the server can rebuild the connection.
Q10. Stateless versus stateful firewall?
A stateless firewall judges each packet independently by headers, so it is fast but must open broad port ranges for replies. A stateful firewall tracks connections and automatically allows replies to established connections while dropping unsolicited packets. Application firewalls go further and inspect payloads.
Q11. What is the difference between an IDS and an IPS?
An IDS monitors traffic and raises alerts but does not block. An IPS sits inline and drops malicious traffic. Both use signatures and anomaly detection; an IPS needs careful tuning because false positives block real users.
Q12. Compare IPsec and TLS VPNs.
IPsec secures IP packets at the network layer, uses IKE for key exchange and ESP for encryption, and is common for site-to-site links. TLS VPNs run over TLS on port 443, so they traverse restrictive firewalls easily and suit remote access.
Q13. How does SSH key authentication work?
The user's public key is stored in the server's authorized_keys. During login the client signs session-specific data with its private key, and the server verifies the signature with the stored public key. The private key never leaves the client, so there is nothing to intercept or brute-force.
Q14. What is the difference between XSS and CSRF?
XSS injects attacker JavaScript into a trusted site, which then runs with the user's privileges. CSRF makes the user's browser send an unwanted authenticated request to a site from another site. XSS is mitigated by output escaping and CSP; CSRF by SameSite cookies and anti-CSRF tokens.
Q15. What does HSTS protect against?
SSL stripping, where an attacker intercepts the user's first plain-HTTP request and keeps them on HTTP. HSTS tells the browser to use HTTPS only for the site for a given period, and the preload list extends this to the first visit.
Key takeaways
- Security goals: confidentiality, integrity, availability, plus authentication and non-repudiation. Name the property an attack breaks.
- Symmetric crypto is fast; asymmetric crypto solves key exchange and signatures. TLS is hybrid.
- Hash = fingerprint, MAC = keyed fingerprint, signature = private-key proof anyone can verify.
- Diffie-Hellman agrees on a secret in public (
p = 23,g = 5, secrets 6 and 15 give shared secret 2); ephemeral DH gives forward secrecy. - Certificates bind keys to names; browsers validate a chain up to a trusted root.
- TLS 1.2 takes 2 RTT; TLS 1.3 takes 1 RTT, encrypts the certificate and always provides forward secrecy. 0-RTT can be replayed.
- Know MITM, ARP spoofing, DNS spoofing, DDoS, SYN floods and replay, each with a defence.
- Firewalls range from stateless filters to stateful and application-aware; IDS alerts, IPS blocks.
- VPNs tunnel traffic (IPsec, TLS VPN, WireGuard); SSH keys authenticate by signature, never by sending a secret.
Next lesson
Continue with What happens when you type a URL.

