Lesson 08 · 35 minutes
Speak HTTP by hand
- Read an HTTP request and response, line by line
- Send a request with curl and with a raw Python socket
- Explain status codes, headers and a cookie, and what each means for security
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 developer says: "Our shop works in the browser, but my script gets strange answers, and I do not know why." You do not have the browser session. You get a small test shop that runs on your own machine, and you must work like a browser without a browser: ask for pages, follow a redirect, sign in and read the headers. Then you report what the server really said.
Recall
Which transport protocol does HTTP use, and what happens before the first request?
HTTP uses TCP. The client and the server do the three-way handshake (SYN, SYN-ACK, ACK) first. Only then can the client send the request.
What does NXDOMAIN mean in a DNS answer?
The name does not exist. It is different from a name that exists but has no record of the type that you asked for.
The idea
HTTP is a text protocol on top of TCP. The client sends a request. The server sends back one response. Each message has the same three parts: a first line, headers (one Name: value per line), an empty line, and an optional body.
A request starts with a method, a path and a version:
GET /index.html HTTP/1.1
Host: example.comThe method says what the client wants to do:
| Method | Use |
|---|---|
GET | Read a resource. Must not change anything. |
HEAD | Like GET, but the answer has headers only. |
POST | Send data to the server, for example a form. |
PUT, DELETE | Replace or remove a resource. |
OPTIONS | Ask which methods are allowed. |
A response starts with a status code. The first digit is the class:
| Code | Meaning |
|---|---|
2xx | Success (200 OK) |
3xx | Go elsewhere (301, 302, with a Location header) |
4xx | The client made an error (401 not signed in, 403 forbidden, 404 not found) |
5xx | The server failed (500, 502) |
The Host header is required in HTTP/1.1. One server and one address can host many sites, and Host says which one you want.
A cookie is a small value that the server gives in a Set-Cookie header. The browser sends it back in a Cookie header on every later request. HTTP itself keeps no memory, so a cookie is how a site knows that two requests come from one signed-in user. Whoever holds the cookie is that user.
- Browser → Web server: GET /account
- Web server → Browser: 401, sign in first
- Browser → Web server: GET /login
- Web server → Browser: 200 + Set-Cookie: sid=...
- Browser → Web server: GET /account + Cookie
- Web server → Browser: 200, your account
Worked example
1. Start the local server
Use the folder and the page from lesson 5. Leave this running and open a second terminal.
cd ~/krlab/networking
python3 -m http.server 8000 --bind 127.0.0.12. Watch a request and a response with curl
curl transfers a URL. The option -v (verbose) shows both messages, -s hides the progress meter and -o /dev/null throws the body away. Curl writes the verbose text to its error output, and 2>&1 joins that to the normal output, so that grep -E '^[<>]' can keep the lines that start with < or >. Lines with > were sent, lines with < were received.
curl -sv -o /dev/null http://127.0.0.1:8000/ 2>&1 | grep -E '^[<>]'> GET / HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/8.18.0
> Accept: */*
>
< HTTP/1.0 200 OK
< Server: SimpleHTTP/0.6 Python/3.14.4
< Date: Sat, 21 Nov 2026 08:35:37 GMT
< Content-type: text/html
< Content-Length: 17
< Last-Modified: Sat, 21 Nov 2026 08:33:38 GMT
< The server answered HTTP/1.0, an older version. Content-Length: 17 is the size of the body, the 16 characters of hello from krlab and the new line. The Server header tells the world which software and version runs here. Remember that for the Field notes.
3. Ask only for the headers
-I sends a HEAD request.
curl -sI http://127.0.0.1:8000/The answer is the same list of headers with no body.
4. Make the server say "not found" and "not allowed"
-w prints a value of your choice after the transfer: %{http_code} is the status code. -X POST forces the method, and -i includes the response headers in the output.
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/nope.html
curl -si -X POST http://127.0.0.1:8000/ | head -1404
HTTP/1.0 501 Unsupported method ('POST')This simple server knows only GET and HEAD, so a POST gets 501. A real application would use 405 or accept the data.
5. Write the request yourself with a raw socket
A request is only text. Write raw.py. It sends the same request that curl sent, reads until the server closes the connection, and splits the answer at the empty line. The sign := in while chunk := s.recv(4096) assigns the bytes to chunk and tests them in one step. The loop ends when the server closes the connection and recv returns nothing.
raw.py
import socket
request = (
"GET / HTTP/1.1\r\n"
"Host: 127.0.0.1:8000\r\n"
"Connection: close\r\n"
"\r\n"
)
with socket.create_connection(("127.0.0.1", 8000), timeout=3) as s:
s.sendall(request.encode())
data = b""
while chunk := s.recv(4096):
data += chunk
head, _, body = data.partition(b"\r\n\r\n")
print(head.decode())
print("--- body ---")
print(body.decode())python3 raw.pyHTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.14.4
Date: Sat, 21 Nov 2026 08:35:37 GMT
Content-type: text/html
Content-Length: 17
Last-Modified: Sat, 21 Nov 2026 08:33:38 GMT
--- body ---
hello from krlabEach line ends with the two bytes \r\n, and an empty line ends the headers. A server that ignores this rule can be confused by a message that is cut in the wrong place. This is the basis of request smuggling attacks. Now stop the server with Ctrl+C.
6. See a cookie travel
Write cookie_server.py. It gives a cookie to a client that has none, and reports the cookie that it receives. It listens on port 8001. class H(BaseHTTPRequestHandler) tells the server what to do for each request: the method do_GET runs for every GET, self.headers holds the request headers and self.wfile.write sends the body.
cookie_server.py
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
seen = self.headers.get("Cookie")
self.send_response(200)
if not seen:
self.send_header("Set-Cookie", "sid=abc123; HttpOnly; SameSite=Strict")
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(f"cookie seen: {seen}\n".encode())
HTTPServer(("127.0.0.1", 8001), H).serve_forever()python3 cookie_server.pyIn the second terminal, -c saves cookies to a file (the "jar") and -b sends them back.
curl -si -c jar.txt http://127.0.0.1:8001/
curl -s -b jar.txt http://127.0.0.1:8001/HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.4
Date: Sat, 21 Nov 2026 08:35:38 GMT
Set-Cookie: sid=abc123; HttpOnly; SameSite=Strict
Content-Type: text/plain
cookie seen: None
cookie seen: sid=abc123The first request had no cookie, so the server set one. The second request sent it back. Stop the server with Ctrl+C.
Your turn
Do the check of the test shop. There are no steps here: use curl as in the worked example, on the pages of a different server.
Save the program below as shop.py and start it with python3 shop.py. It is a small shop on 127.0.0.1, port 8061. It has the paths /, /old, /new, /admin, /login and /account. Leave it running.
shop.py
from http.server import BaseHTTPRequestHandler, HTTPServer
class Shop(BaseHTTPRequestHandler):
server_version = "shop/1"
sys_version = ""
def respond(self, code, body, extra=None, send_body=True):
self.send_response(code)
self.send_header("X-Shop-Version", "2.4")
self.send_header("Content-Type", "text/plain")
for name, value in (extra or {}).items():
self.send_header(name, value)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if send_body:
self.wfile.write(body)
def route(self, send_body):
path, cookie = self.path, self.headers.get("Cookie", "")
if path == "/":
self.respond(200, b"welcome to the shop\n", send_body=send_body)
elif path == "/old":
self.respond(301, b"moved\n", {"Location": "/new"}, send_body)
elif path == "/new":
self.respond(200, b"the new page\n", send_body=send_body)
elif path == "/admin":
self.respond(403, b"forbidden\n", send_body=send_body)
elif path == "/login":
self.respond(200, b"signed in\n", {"Set-Cookie": "sid=k7q2; HttpOnly"}, send_body)
elif path == "/account" and "sid=k7q2" in cookie:
self.respond(200, b"account of mia\n", send_body=send_body)
elif path == "/account":
self.respond(401, b"sign in first\n", send_body=send_body)
else:
self.respond(404, b"not found\n", send_body=send_body)
def do_GET(self):
self.route(True)
def do_HEAD(self):
self.route(False)
def log_message(self, *args):
pass
print("shop on 127.0.0.1 port 8061. Press Ctrl+C to stop.", flush=True)
HTTPServer(("127.0.0.1", 8061), Shop).serve_forever()The developer says that the page /account "does not work" and that /old "is broken". In a second terminal, find out what the server does: ask /admin, ask /old and read where it sends you, ask /account with no cookie, then sign in at /login, keep the cookie, and ask /account again. Read all the headers, not only the body.
Stop the shop with Ctrl+C. Then write two sentences for the developer: what /account needs, and what /old does.
Check yourself
A request has no Host header. Why does an HTTP/1.1 server reject it?
One address can serve many sites. Without Host, the server does not know which site you mean. HTTP/1.1 makes the header required for this reason.
A scanner gets "403" for one path and "404" for another. What does the difference tell it?
403 says that the resource exists but you may not read it. 404 says that it does not exist. The first confirms that something is there. Some applications return 404 for both, to give nothing away.
Why is a stolen session cookie as bad as a stolen password?
The server uses the cookie as proof of identity on every request. Whoever sends the same cookie is treated as the same user, with no password check. The flags HttpOnly (script cannot read it) and Secure (sent only over HTTPS) reduce the ways to steal it.
Against a real web server, raw.py would hang after the headers if you removed "Connection: close". Why?
An HTTP/1.1 server keeps the connection open for the next request by default. It does not close it, so recv waits for data that never comes. The simple server here closes anyway (it speaks HTTP/1.0), but many real servers do not. A real client must read the exact length from Content-Length or from the chunk markers.
Field notes
- The
Serverheader and error pages tell an attacker your software and version. Remove or generalise them, but do not count this as a defence: patching is the defence. - Security headers belong in every response of a web application:
Strict-Transport-Security,Content-Security-Policy,X-Content-Type-Options, andSet-CookieflagsSecure,HttpOnly,SameSite. Check them withcurl -sIin a deploy test. GETmust be safe, but many applications change data onGET. A page that logs a user out or deletes a row onGETcan be triggered by an image tag on another site.- Never trust the
Host,X-Forwarded-FororUser-Agentheader as fact. The client writes them. Behind a proxy, take the client address from the proxy's header only when the request really came from that proxy. - HTTP/1.1 is defined in RFC 9110 (meaning) and RFC 9112 (message format). Disputes about "what is a valid request" are settled there, and request smuggling exists where two systems read the same bytes in two ways.