So far we have built a network that works. This lecture starts from the unpleasant observation that the Internet is not a friendly place, and adds three things that are missing. First the transport layer - because almost every attack and almost every defence is conducted there, at the level of ports and TCP flags. Then filtering with iptables, that is, what happens when the firewall is no longer a Cisco router but a Linux machine. And finally the cryptography behind a simple SSH session: how two computers that have never met manage to agree on a secret key, in plain view of everybody.
1Recap5 min
- An ACL is an ordered list, read up to the first match.
- At the end there is an invisible
deny any. - The list must be applied to an interface and a direction to exist at all.
- Extended lists can filter by protocol and port - that is, by layer 4.
- An ACL is stateless: it does not remember that we asked first.
That last point is exactly where we left off, dissatisfied. Today we see what a device that does remember sessions amounts to - but to understand what it remembers, we must first understand what a session is.
Learning outcomes
- Explain what the transport layer adds on top of IP and why ports exist
- Choose between TCP and UDP for a given application, with reasons
- Read a three-way handshake and say what each flag does
- Recognise the three families of attack and explain how a SYN flood works
- Write correct iptables rules, on the right chain
- Build a complete firewall, with a default DROP policy
- Explain what authentication, confidentiality and integrity each guarantee, separately
- Describe the Diffie-Hellman exchange and say what it does not solve
2The transport layer: why ports exist10 min
So far, a packet arrives at the right computer. The IP address does exactly that: it identifies the machine.
But on that machine there are running, at the same time, a browser, a mail client, a game and three background updates. When a packet arrives, the operating system must know which application it belongs to. The IP address says nothing about that.
So layer 4 adds one more number: the port. Every layer introduces a new kind of address - layer 2 the MAC address, layer 3 the IP address, layer 4 the port. Without ports, a computer could run only one network application at a time.
192.168.1.10:49152.
A connection is completely identified by four numbers: the source socket and the destination
socket. Two connections may have the same destination and the same source address but different
source ports - which is why you can open ten tabs to the same site without them getting mixed
up.| Role of the transport layer | What it means | TCP | UDP |
|---|---|---|---|
| Segmentation | divides the application stream into pieces that fit in a packet | yes | yes |
| Addressing | identifies the application by port number | yes | yes |
| Multiplexing | several applications on the same IP address | yes | yes |
| Reliability | retransmits what was lost, reorders what arrived out of order | yes | no |
| Flow control | stops a fast sender from drowning a slow receiver | yes | no |
| Connection setup | establishes a session before the transfer itself | yes | no |
- Connection-oriented: a session is established before the transfer
- Reliable: the data arrives, guaranteed and in order
- Flow, congestion and error control
- A header of at least 20 bytes
- SSH, HTTP, SMTP, file transfer, databases
- Connectionless: you send it and that is that
- Unreliable: segments may be lost or arrive in a different order
- No flow or congestion control
- An 8-byte header - source, destination, length, checksum
- DNS, DHCP, VoIP, IPTV, games, streaming
The port ranges
| Range | Name | Who uses them |
|---|---|---|
| 0 – 1023 | well-known | standard services: 22 SSH, 25 SMTP, 53 DNS, 80 HTTP, 443 HTTPS. On Linux, only privileged processes may listen here. |
| 1024 – 49151 | registered | well-known but unofficial applications: 3306 MySQL, 3389 RDP, 8080 HTTP proxy |
| 49152 – 65535 | dynamic / ephemeral | the source ports chosen automatically by the operating system for each new connection |
192.168.1.10:51423 → 93.184.216.34:80. The destination port is known (80), but the
source port is unpredictable.That is why a firewall rule for the return traffic cannot specify the destination port - it changes with every connection. You need either
established or session tracking. This is, in
concrete terms, the limitation we ran into at the end of the last lecture.Look at the second command. The three connections have the same local address but different source ports - and that alone is what keeps them apart. And the last line is a connection in the other direction: somebody is connected by SSH to our machine, so the local port is 22, the well-known one.
3The TCP header, field by field9 min
Almost every mechanism discussed below - retransmission, flow control, the handshake, the SYN flood
attack, the established option - is written, quite literally, in this 20-byte
header.
| Flag | Role | Where you meet it |
|---|---|---|
SYN | asks to synchronise sequence numbers - opens the connection | SYN flood, --syn in iptables |
ACK | acknowledges data received; activates the acknowledgment field | established in ACLs |
FIN | announces that the sender has finished transmitting | normal closing |
RST | closes the connection brutally; the answer to an invalid packet | REJECT in iptables |
4Opening and closing a connection11 min
A TCP connection is opened through an exchange of three segments, in which each end communicates its initial sequence number and acknowledges the other's. It is closed, however, through four - and the reason for that asymmetry says something about how TCP is conceived.
5The three families of attack11 min
Any network connected to the Internet is, permanently, the target of automated attempts. You do not need to be interesting: the scans are continuous and blind. Attacks fall into three families, according to their purpose.
| Family | Purpose | Examples | What helps |
|---|---|---|---|
| Reconnaissance | finding out what exists and what is running | ping sweep, port scan, sniffing, DNS and whois queries | filtering ICMP, DROP instead of REJECT |
| Denial (DoS/DDoS) | making the service unavailable | SYN flood, smurf, DNS amplification | rate limiting, SYN cookies |
| Access | obtaining undeserved privileges | password cracking, buffer overflow, man-in-the-middle | strong authentication, encryption |
REJECT discards the packet and sends an answer: "port closed". Polite - and
extremely useful to whoever is scanning, because it confirms that the machine exists.
DROP discards the packet silently. The scanner receives nothing and must wait
for a timeout on every port. A scan that would take one second takes minutes.
Inside the network, however, REJECT is preferable: your own applications get an
immediate error instead of waiting 30 seconds for nothing.
How a SYN flood works
| Type | How far up it looks | Does it remember sessions? | Example |
|---|---|---|---|
| Stateless | 3–4 | no - each packet is judged in isolation | ACLs on a router |
| Stateful | 3–4, with a connection table | yes | iptables with conntrack, Cisco ASA |
| Application-layer (proxy) | up to 7 | yes, plus the content | HTTP proxy, WAF |
A firewall does not solve all three families, but it cuts the first two efficiently: it can block vulnerable ports, stop connections being initiated from outside, refuse to answer ICMP echo, limit the number of half-open sessions and stop the directed broadcasts that make the smurf attack possible. Against access attacks it helps less: there, cryptography and authentication do the work, in section 10.
6iptables: tables and chains12 min
iptables is the user-space utility that configures Netfilter, the filtering framework in the Linux kernel. It lets a Linux machine filter packets, translate addresses and rewrite fields - that is, be a router and a firewall at the same time.
The chain is the checkpoint - where along the route. The table is the kind of instruction - what sort of decision is taken there: filtering, address translation or modification. One checkpoint may have several stacks.
| Table | What it contains |
|---|---|
filter | the rules that decide what passes and what is discarded; the default table, used if you do not write -t |
nat | the address translation rules - the subject of lecture 9 |
mangle | specialised alteration of packets: TTL, marks, ToS |
raw | exceptions from connection tracking |
The chains are the points along a packet's route at which rules are applied. The key to understanding iptables is knowing which chains each kind of packet passes through - and there are only three kinds.
If the recipient is the Linux machine itself (an SSH session to it, a page served by it) → INPUT.
If the recipient is somebody else and the machine is merely routing → FORWARD.
A rule placed on INPUT for transiting traffic will never apply - and you will get no error either.
7The anatomy of an iptables rule11 min
A rule always has two parts: a pattern - the conditions the packet must meet - and a target - what happens to it.
iptables -t filter -A INPUT -s 10.0.0.0/8 -p icmp -j DROP # └ table └ op └ chain └───── conditions ────┘ └ target # # -t filter the table (the default, may be omitted) # -A INPUT append to the end of the INPUT chain # -s 10... source: here the mask is NORMAL, not a wildcard! # -p icmp the protocol # -j DROP jump: what is done with the packet
0.0.0.255). In iptables the normal CIDR
notation (/24) or the classic mask is used. It is one of the few places where moving from
one ecosystem to the other really does produce silent mistakes.| Operation | Long form | What it does |
|---|---|---|
-A | --append | adds a rule at the end of the chain |
-I | --insert | inserts at a given position (the first by default) |
-D | --delete | deletes a rule |
-L -n -v --line-numbers | --list | displays the rules, with counters and line numbers |
-F | --flush | empties the chain |
-P | --policy | changes the default policy |
| Condition | What it checks |
|---|---|
-i eth0 / -o eth1 | the incoming / outgoing interface |
-s / -d | the source / destination address, in CIDR notation |
-p tcp --dport 22 | the protocol and the destination port |
-p tcp --syn | connection initiation segments alone |
-m state --state ESTABLISHED,RELATED | the session state, from the conntrack table |
-m limit --limit 25/s | the arrival rate - for anti-flood defence |
! -s 10.0.0.0/8 | negation of any condition, with an exclamation mark |
| Target | What it does |
|---|---|
ACCEPT | lets the packet through; evaluation of the chain stops |
DROP | discards it silently - the sender learns nothing |
REJECT | discards it and sends an ICMP message or a TCP RST |
LOG | records it in the system log and continues evaluation |
All the others are terminal: once applied, the packet has its verdict and the chain is no longer read. Just as with Cisco ACLs.
LOG decides nothing - it merely notes the packet and lets it travel on through the
list. That is why a logging rule is placed immediately above the DROP it is meant to
document, with exactly the same conditions.
Look at the first command. The pkts column is the exact equivalent of the match
counter in Cisco ACLs, and is used in the same way: rule 4 of INPUT has 0 packets, which means
nobody has yet reached the web server - or that a rule above is already catching the traffic.
iptables-save (or the
netfilter-persistent service), at the next boot the machine starts with empty chains and
ACCEPT policies - that is, with no firewall.The good part: if you have locked yourself out, a reboot rescues you. The bad part: if you thought you had configured a firewall, you had not.
8The default policy and a complete firewall10 min
Every predefined chain has a policy - the action applied to packets that matched no rule. It
is the equivalent of Cisco's implicit deny any, with one important difference: here it is
configurable, and its default is ACCEPT.
- "Permit everything not explicitly forbidden"
- You must anticipate every bad thing
- Any service started by accident is exposed
- A forgotten port stays open for ever
- "Forbid everything not explicitly permitted"
- You must enumerate what you want to work
- A new service does not work until you open it - and that is as it should be
- The only acceptable approach when facing the Internet
ACCEPT rules first and only then the DROP policy. If you do
it the other way round while working over SSH, the first command disconnects you from the machine
instantly.User-defined chains cannot have a default policy - their evaluation simply returns to the calling chain.
# 1. Clean up and start from scratch iptables -F iptables -X # 2. Loopback traffic - always first, otherwise local services break iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # 3. The rule that solves ALL the return traffic, in one line iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT # 4. The services we expose ourselves iptables -A INPUT -i eth1 -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT iptables -A INPUT -p tcp --dport 80 -j ACCEPT # 5. The LAN is allowed out to the Internet iptables -A FORWARD -i eth1 -o eth0 -s 192.168.1.0/24 -j ACCEPT # 6. Log what we are about to discard (LOG does not stop the scan) iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "IPTABLES-DROP: " # 7. ONLY NOW the policies iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT # 8. Save, otherwise everything disappears on reboot iptables-save > /etc/iptables/rules.v4
-m state --state ESTABLISHED,RELATED -j ACCEPT is exactly what we lacked with Cisco ACLs.
The kernel keeps a connection table (conntrack); any packet belonging to an already established
session is accepted automatically, whatever the port.RELATED goes further: it also accepts related traffic - the data connection of an
active FTP session, say, or ICMP error messages tied to an existing session. This is, concretely, the
difference between stateless and stateful.A private network has a Linux router. Configure an antispoofing policy: packets with private addresses may neither come in from the Internet nor go out to it.
See the solution
iptables -A FORWARD -i eth0 -s 192.168.0.0/16 -j DROP iptables -A FORWARD -i eth0 -s 172.16.0.0/12 -j DROP iptables -A FORWARD -i eth0 -s 10.0.0.0/8 -j DROP iptables -A FORWARD -o eth0 -d 192.168.0.0/16 -j DROP iptables -A FORWARD -o eth0 -d 172.16.0.0/12 -j DROP iptables -A FORWARD -o eth0 -d 10.0.0.0/8 -j DROP
The rules go on FORWARD, because this is traffic that transits the router.
The interface condition is essential: -i eth0 means "arriving from the Internet".
Without it, you would also block legitimate internal traffic between two private subnets - which is
exactly the traffic the router is there to carry.
Topology: a Linux router with eth0 towards the Internet, eth1 towards a
server (142.31.16.9) and eth2 towards the LAN
(142.31.16.128/25). The administrator works from 214.13.177.2, out on the
Internet. The starting configuration is: INPUT: policy ACCEPT, rule -i eth0 -j DROP;
FORWARD: policy DROP, rule -i eth0 -j ACCEPT.
See the four tickets and the solutions
#1 - The LAN hosts cannot reach the server. The cause: the FORWARD chain policy is DROP, and the only rule permits traffic arriving on eth0 - that is, from the Internet.
iptables -P FORWARD ACCEPT
#2 - Only LAN hosts are allowed to the server HTTP.
iptables -F FORWARD iptables -A FORWARD -s 142.31.16.128/25 -d 142.31.16.9 -p tcp --dport 80 -j ACCEPT iptables -A FORWARD -d 142.31.16.9 -p tcp --dport 80 -j DROP
The order is essential: the permissive, more specific rule must sit above the restrictive one. Exactly the same rule as with ACLs.
#3 - Only the administrator may SSH to the router. Being traffic destined for the router, the chain is INPUT, not FORWARD.
iptables -F INPUT iptables -A INPUT -s 214.13.177.2 -p tcp --dport 22 -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j DROP
#4 - TCP sessions may be initiated only from inside. The first attempt,
iptables -A FORWARD -p tcp --syn -j DROP, is wrong: it also blocks connections started
from the LAN. It must be narrowed to traffic coming in from the Internet:
iptables -A FORWARD -i eth0 -p tcp --syn -j DROP
Notice that the modern solution would be quite different - a single line with
--state ESTABLISHED,RELATED - and that it also covers UDP and ICMP, which
--syn does not touch at all.
9The architecture of the perimeter6 min
Where exactly does the firewall go relative to the edge router? The decision is most often imposed by the Internet provider, but the principles are clear.
| Architecture | When it is used | Notes |
|---|---|---|
| Router in front, firewall behind | medium and large networks | the commonest: the router covers the routing requirements the firewall cannot meet |
| Firewall in front, router behind | very strict security requirements | the internal router is protected, but the firewall must do routing as well |
| A single device | small networks, static routing | simple and cheap; a single point of failure |
IDS and IPS
A firewall decides on the basis of headers. For inspecting the content, a separate device is added, and the difference between the two variants is purely one of positioning.
- Placed in the path of the traffic, in series
- It can stop dangerous packets
- It becomes a potential bottleneck
- If it fails, it can interrupt all traffic
- A false positive cuts off legitimate traffic
- It receives a copy of the traffic, in parallel
- It only reports; it can stop nothing
- It does not affect network performance
- If it fails, the traffic flows undisturbed
- A false positive generates only an alarm
The choice is not "which is better" but "what happens when it gets it wrong". In a network where availability matters more than the risk, IDS. In one where a single wrong packet is unacceptable, IPS.
10SSH and the three security concepts13 min
Telnet transmits everything in the clear, the password included. Anybody listening to the traffic obtains it - no effort is required, only access to a mirrored switch port or a wireless network. SSH solves the problem on three distinct fronts, which are worth understanding separately, because they recur, under other names, in every security discussion.
| Concept | The question it answers | The mechanism in SSH |
|---|---|---|
| Authentication | Are the two parties who they claim to be? | a password or asymmetric keys |
| Confidentiality | Can anybody else read the message? | symmetric encryption (AES, ChaCha20) |
| Integrity | Was the message altered along the way? | a MAC - message authentication code |
They are independent, and solving one does not touch the others.
A message may be perfectly encrypted and still sent by an impostor - encryption says nothing about who is writing. A message may be correctly signed and still readable by everybody. And an encrypted message may be altered in transit without the attacker understanding what they are altering, which is quite enough to do harm.
That is why any serious protocol deals with all three, through different mechanisms.
Confidentiality: the problem of the shared key
Symmetric encryption - the same key at both ends - is fast and efficient. It has, however, a problem that looks impossible: how do the two ends come to hold the same key, if the only channel available is the very one they want to protect?
The answer is the Diffie-Hellman exchange, published in 1976, and it is one of the most elegant ideas in computing: the two ends construct a shared key without it ever being transmitted.
They agree publicly on a base colour - yellow. Each secretly adds a colour of their own and sends the mixture. An observer sees the two mixtures but cannot separate the colours in them.
Each then adds their own secret colour to the mixture received. Both arrive at exactly the same final colour - yellow plus his secret plus her secret. The observer has the yellow and the two mixtures but cannot produce the final colour, because one of the secrets would be needed.
Play with the values. Change the client's secret: the shared key changes - but stays
identical at both ends, although neither secret ever left its computer. What travels over the
channel is only p, g, A and B.
The security rests on the fact that, although A = ga mod p is computed instantly, the
reverse journey - recovering a from A - is the discrete logarithm
problem, for which no fast algorithm is known. With the toy numbers above it can be broken by
trial and error; with a 2048-bit p, it cannot.
An attacker placed in the middle can run two separate DH exchanges - one with the client, one with the server - and decrypt, read and re-encrypt all the traffic. This is the man-in-the-middle attack, and the remedy lies not in DH but in authentication: which is why SSH asks you, on the first connection, whether you recognise the fingerprint of the server's key. That message everybody accepts without reading is precisely the defence against this attack.
Authentication: password or key
Authentication takes place after the encrypted channel exists. That appears to solve the password problem - but not entirely:
- the server must see the password in order to validate it; if the server is compromised, the password is compromised - and it is usually reused elsewhere;
- passwords secure enough to be safe are hard to remember, so users choose weak ones;
- a password can be guessed by repeated attempts, and the Internet has infinite patience.
Hence the preference for asymmetric keys. A key pair has the property that what is encrypted
with one can be decrypted only with the other: K⁺(K⁻(M)) = M and
K⁻(K⁺(M)) = M. The client keeps its private key - which never leaves its computer - and
the public key is configured on the server.
- The secure session is established through Diffie-Hellman.
- The client requests authentication for a particular user.
- The server sends a challenge: a random string the client must sign.
- The client encrypts it with its private key. The result is called the authenticator.
- The server verifies it using the preconfigured public key. If the result matches the string sent, the client holds the private key - and is therefore who it claims to be.
Notice what never happened in those five steps: the private key was not transmitted. The server does not know it and cannot find it out. A compromised server does not compromise your identity on other servers - unlike a password.
The same principle - asymmetric for the key exchange, symmetric for the data - underlies TLS and every HTTPS connection you open.
Integrity: the MAC
A MAC (Message Authentication Code) is, in essence, a hash computed with a key. The sender computes it over the message and sends it alongside; the receiver recomputes it with the same key and compares. If the values differ, the message was altered along the way.
The key is essential. A plain hash would not help: the attacker would alter the message and recompute the hash. Without the key, they cannot produce a valid MAC for the altered message.
It does not show the content, does not show the password, does not show the commands executed, and does not allow the traffic to be altered without both ends noticing immediately.
11Common mistakes4 min
- "My iptables rule has no effect at all" Almost certainly it is on the wrong chain: INPUT instead of FORWARD, or the other way round. Ask who the recipient in the IP header is. The machine itself → INPUT. Somebody else → FORWARD.
- "I set the DROP policy and got disconnected"
The policy took effect before the rule that permitted your SSH.
All the ACCEPT rules first, then
-P DROP. On remote machines, test with a second session open. - "The firewall disappeared after a reboot"
The rules live in kernel memory and do not save themselves.
iptables-save, or thenetfilter-persistentservice. - "I used the Cisco wildcard in iptables"
-s 10.0.0.0/0.0.0.255does not mean what you think. iptables uses the normal mask or CIDR.-s 10.0.0.0/24. Check withiptables -L -n, which displays the resulting prefix. - "I blocked ICMP entirely, to be safe"
You also blocked the fragmentation needed messages, essential for MTU discovery. The
result: connections that open and then freeze inexplicably.
Block only
echo-requestfrom outside; let the ICMP error messages through. - "Diffie-Hellman protects me from everything" It protects you from somebody listening. Not from somebody sitting in the middle. Check the key fingerprint on the first connection. It is the only moment when it matters.
- "I mixed up DROP and REJECT" REJECT confirms to the attacker that the machine exists. DROP towards the outside, REJECT towards the inside - so that your own applications do not wait for nothing.
12Summary and glossary5 min
- Layer 4 adds the port; the pair IP + port is called a socket.
- TCP is reliable and connection-oriented; UDP is fast and offers no guarantees. The choice depends on the application.
- The handshake takes three segments; closing takes four, because each direction closes separately.
- A SYN flood fills the queue of half-open connections; the defences are SYN cookies and rate limiting.
- In iptables, the chain says where, the table says what kind of decision.
- INPUT = for the machine, FORWARD = through the machine, OUTPUT = from the machine.
- The correct policy is
DROP, and the ACCEPT rules go before it. --state ESTABLISHED,RELATEDsolves all the return traffic in one line.- Authentication, confidentiality, integrity are three distinct problems, with three distinct mechanisms.
- Diffie-Hellman solves the key exchange, not the identity of the other end.
13Self-check questions6 min
14Further reading2 min
The next lecture uses exactly the same tools - ACLs on Cisco, iptables on Linux - but for something
other than filtering: address translation and the building of tunnels. There you will
meet the nat table we postponed today, and you will understand how a private network can
browse the Internet with a single public address.
Laboratory 7 puts the security part into practice: SSH on the equipment, plus the defence against the layer 2 attacks from lecture 12.
- RFC 9293 - Transmission Control Protocol (the consolidated version of RFC 793)
- RFC 4987 - TCP SYN Flooding Attacks and Common Mitigations
- RFC 4251–4254 - the SSH architecture
- The
iptables(8)andiptables-extensions(8)manuals - William Stallings, Cryptography and Network Security - the chapters on Diffie-Hellman and MACs