Lesson 11 · 40 minutes
Decide who can reach a service
- Say where a firewall, a NAT device, a proxy and a VPN sit and what each does
- Show with ss and curl the difference between 127.0.0.1 and 0.0.0.0
- Name the client address that an application sees behind a reverse proxy
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A small team runs three services on one server: a public web front (a reverse proxy), a private application behind it, and an admin panel. A new colleague says: "Only the front should be open." You check which service listens on which address, and what the application believes about the client when a request comes through the proxy. Lesson 12 then builds a router with a firewall and NAT.
Recall
Your logging proxy from lesson 10 could read plain HTTP, but not HTTPS. Why?
It only copied bytes. The TLS keys exist in the client and the server only, so the copied bytes stay encrypted. A proxy that must read HTTPS must end the TLS session itself.
In lesson 5 your server accepted connections on 127.0.0.1. Who could connect to it?
Only programs on this machine. A client on another machine could not reach the loopback address.
The idea
Four devices appear on every network diagram. Each does one job at a different place.
| Device | Sits | Job |
|---|---|---|
| Firewall | On a host or between networks | Allows or blocks packets by rule |
| NAT | On the router at the edge | Rewrites addresses so that many private hosts share one public address |
| Proxy | Between a client and a server | Takes a request and makes a new request for you |
| VPN | Between you and a remote network | Wraps your traffic in an encrypted tunnel |
Firewall. A rule matches the source address, the destination port or the protocol, and then allows, drops or rejects. Two ideas matter most. Default deny: the last rule blocks everything, and you list only what you allow, because a list of things to block always misses something. Stateful filtering: the firewall remembers the connections that started from inside, and lets the replies come back without a separate rule.
NAT (network address translation). Your home devices have private addresses (lesson 2). The router replaces the private source address of each outgoing packet with its one public address, and remembers the mapping to send replies back to the right device. NAT is not a firewall: it saves addresses, it does not enforce a policy. Lesson 12 builds a firewall rule and NAT in a private router lab.
Proxy. A forward proxy serves the clients: they send their requests to it, and it fetches for them. Companies use it to filter and log web use. A reverse proxy serves the servers: clients think it is the site, and it passes the requests to the real servers behind it. It can end TLS and balance load. A proxy that ends TLS holds the keys, so the client must trust its certificate. Your proxy.py from lesson 10 had this shape. The server behind it sees the address of the proxy, so the proxy adds the real client address in a header, X-Forwarded-For.
- Client → Firewall: GET / on the web port: allowed
- Attacker → Firewall (blocked): any other port, dropped
- Firewall → Reverse proxy: only allowed traffic passes
- Reverse proxy → App server: GET + X-Forwarded-For: client address
VPN. A VPN builds an encrypted tunnel to a gateway. Traffic between you and the gateway is protected from the local network, for example a hotel Wi-Fi. From the gateway the traffic goes out as normal. A VPN does not hide you from the sites that you sign in to, and it does not clean an infected machine. It moves the trust from your local network to the VPN operator. This course does not build a tunnel.
The last idea needs no device. A program chooses the address that it binds to. 127.0.0.1 accepts connections from this machine only. 0.0.0.0 accepts them on every address of the machine. You test this next.
Worked example
1. Start two servers
Make a folder pub with one test page, and serve it twice. The first server binds to the loopback. The second binds to all addresses, so the folder must hold nothing secret: never serve a folder that has keys, such as ~/krlab/networking.
cd ~/krlab/networking
mkdir -p pub
echo "public test page" > pub/index.html
cd pub
python3 -m http.server 8030 --bind 127.0.0.1cd ~/krlab/networking/pub
python3 -m http.server 8031 --bind 0.0.0.02. Compare them with ss
In a third terminal, ss -tln lists the TCP sockets that listen, with numbers. grep -E keeps the lines for the two ports.
ss -tln | grep -E '803[01]'LISTEN 0 5 127.0.0.1:8030 0.0.0.0:*
LISTEN 0 5 0.0.0.0:8031 0.0.0.0:* Look at the local address. 127.0.0.1:8030 is private to this machine. 0.0.0.0:8031 means "all addresses".
3. Connect through the network address
Use the address of your own network interface from lesson 2, so that the request reaches your own machine as another machine's would. The example uses 192.168.1.50; use yours. -m 3 gives up after three seconds. -w prints the status code.
curl -sS -m 3 http://192.168.1.50:8030/
curl -sS -m 3 -o /dev/null -w '%{http_code}\n' http://192.168.1.50:8031/curl: (7) Failed to connect to 192.168.1.50 port 8030 after 0 ms: Could not connect to server
200The server bound to the loopback refuses the connection. The server bound to 0.0.0.0 answers, and any machine in your network could read the files in pub.
Stop both servers with Ctrl+C.
Your turn
Check the three services of the scenario. There are no steps here: use ss and curl as in the worked example, on different ports.
cd ~/krlab/networkingSave edge.py in the lab folder and start it with python3 edge.py. It opens two ports to your whole network while it runs. Use a network that you trust, and stop it as soon as you have your answers. It runs a reverse proxy on port 8082, an application on port 8083 and an admin panel on port 8084. The application answers with the client address that it sees and the X-Forwarded-For header. The proxy adds the address of its own client to that header. Leave it running.
edge.py
import http.client
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Quiet(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def reply(self, text):
body = (text + "\n").encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
class App(Quiet): # the real application: private
def do_GET(self):
xff = self.headers.get("X-Forwarded-For", "none")
self.reply(f"app sees peer={self.client_address[0]} xff={xff}")
class Admin(Quiet): # an admin panel
def do_GET(self):
self.reply("admin panel")
class Proxy(Quiet): # the reverse proxy: public
def do_GET(self):
xff = self.headers.get("X-Forwarded-For")
client = self.client_address[0]
upstream = http.client.HTTPConnection("127.0.0.1", 8083, timeout=3)
upstream.request("GET", self.path, headers={"X-Forwarded-For": f"{xff}, {client}" if xff else client})
self.reply(upstream.getresponse().read().decode().strip())
for address, port, handler in [("127.0.0.1", 8083, App), ("0.0.0.0", 8084, Admin), ("0.0.0.0", 8082, Proxy)]:
server = ThreadingHTTPServer((address, port), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
print("three services are up. Press Ctrl+C to stop.", flush=True)
threading.Event().wait()In a second terminal, list the listening sockets for the ports 8082 to 8084 and read the bind address of each. Ask each port with curl. Then send a request through the proxy with a forged header, X-Forwarded-For: 198.51.100.7, and read what the application reports. Only the proxy should be open to other machines.
Stop edge.py. Then decide: which port must you change to bind to 127.0.0.1, and which address in the xff list can the client forge?
Check yourself
A database is bound to 0.0.0.0 on a cloud server. The owner says "there is a firewall". What do you check?
Check the rules for that port, on the host and in the cloud network settings: is the policy default deny, and is the port open to the whole internet or to one address? 0.0.0.0 is not a fault when a rule limits who can connect, but it removes one layer. Bind to the narrowest address that works.
What is the difference between a forward proxy and a reverse proxy?
A forward proxy serves the clients: they are set up to send their requests to it, and it fetches for them. A reverse proxy serves the servers: clients think it is the site, and it passes the requests on. The client knows about a forward proxy and does not know about a reverse one.
Which address in an X-Forwarded-For list can the application trust, and which can the client forge?
The client can write the first part, because the proxy keeps what the client sent. The proxy adds the real address of its own client at the end, so the last entry is the only one that your own proxy wrote. Trust only entries that your own proxies added.
Field notes
- Test from outside. A rule list tells you what should happen; a connection from another host tells you what does happen. Test only systems you own.
- Container tools often publish ports on
0.0.0.0and add their own firewall rules, soufwmay not block them. Publish local services with127.0.0.1:port:port. - Keep an admin panel off the public proxy. Bind it to
127.0.0.1or to a management network, and reach it through an SSH tunnel or a VPN.