Sub topic 7
Layer 5: Session, managing dialogues
This chapter assumes you know the layers below it. That means frames and MAC addresses at Layer 2, IP routing at Layer 3, and TCP connections and ports at Layer 4. You should also be comfortable running Python and shell commands.
What the Session layer is for
Layer 4 gives two hosts a reliable byte stream or a datagram service. It does not know what the two programs are doing with that stream. Layer 5 is the part of the OSI model that deals with that question. A session is an organized dialogue between two applications. It has a start, a period of exchange, and an end, and it can last longer or shorter than any one transport connection.
The OSI definition gives the layer three jobs:
- Dialogue control. Decide whose turn it is to send. The model allows full duplex (both sides send at once), half duplex (they alternate), and a token mechanism that grants the right to send to one side.
- Synchronization. Insert checkpoints into a long transfer. If the transport breaks, the sides resume from the last confirmed checkpoint instead of restarting.
- Session establishment, maintenance, and release. Set up the dialogue, keep it alive, and close it in an orderly way, or recover it after a failure.
Where Layer 5 actually lives
OSI is a reference model. The TCP/IP stack in real use has no separate session layer. Session behavior is built into applications, libraries, or protocols that sit above TCP. A useful rule is that if a protocol tracks who you are and what you were doing across several requests, it does session work. That is true whichever layer a textbook assigns it to.
| Protocol or mechanism | Session-like behavior |
|---|---|
| NetBIOS session service (TCP 139) | Opens named sessions between Windows hosts and carries SMB over them |
| SMB | Authenticates a user once, then reuses that session for many file operations |
| RPC | Binds a client to a server and tracks calls within that binding |
| SOCKS5 | Negotiates authentication, then relays a stream for the client |
| SIP | Sets up, modifies, and tears down call sessions, while media travels separately |
| HTTP cookies and tokens | Add a session on top of a stateless protocol |
| TLS session resumption | Reuses negotiated keys across connections. Some sources file this under Layer 5 and others under Layer 6 |
Sources disagree on several of these placements, and that is expected. Do not treat any single table as ground truth. When you answer a question about "the layer" of a protocol, name the function you mean.
Session, connection, and request
Three terms are easy to confuse.
- A request is one message and its reply, for example one HTTP GET.
- A connection is a Layer 4 association, for example one TCP stream identified by the two IP addresses and two ports.
- A session is the longer-lived context between a user or program and a service.
They do not map one to one. A browser may open several TCP connections that all belong to one logged-in session. A single TCP connection may carry requests from several sessions, as with a proxy. A session can also outlive its connection. A mobile app that loses Wi-Fi and reconnects over cellular opens a new TCP connection, and the server can still recognize it as the same session.
The diagram shows why the session layer is a separate idea. The transport connection broke, but the dialogue continued because the session state (the ID and the last checkpoint) was stored above TCP.
A working example: a session over stateless HTTP
HTTP does not remember earlier requests. Web applications add a session by giving each client an identifier and keeping state on the server under that identifier. The script below starts a local HTTP server and a client with a cookie jar. The server hands out a session ID on the first request and counts visits for that ID. Nothing leaves your machine.
import http.cookiejar
import http.cookies
import http.server
import secrets
import threading
import urllib.request
sessions = {} # session ID -> state kept on the server
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
cookie = http.cookies.SimpleCookie(self.headers.get("Cookie", ""))
sid = cookie["sid"].value if "sid" in cookie else None
if sid not in sessions:
sid = secrets.token_hex(16) # unpredictable ID
sessions[sid] = {"visits": 0}
sessions[sid]["visits"] += 1
body = f"visit {sessions[sid]['visits']} in session {sid[:8]}\n".encode()
self.send_response(200)
self.send_header("Set-Cookie", f"sid={sid}; HttpOnly")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass # keep the output clean
server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
for _ in range(3):
with opener.open(f"http://127.0.0.1:{port}/") as reply:
print(reply.read().decode().strip())
server.shutdown()The three lines of output show the visit count rising from 1 to 3 under the same eight-character ID prefix. The ID itself differs on every run. Each opener.open call is an independent request. The client sends the cookie back, and the server matches it to its stored state. That lookup is the session. Delete the line HTTPCookieProcessor(jar) from the opener setup and every request starts a new session, so the count stays at 1.
Keeping sessions alive and ending them
Sessions need rules about how long they last. Real systems use several mechanisms, and each has its own failure mode.
- Idle timeouts. The server discards state after a period with no traffic. If a user returns after the timeout, the session ID no longer matches anything, and the user is asked to log in again.
- Keepalives. A periodic small message shows the peer is still there. TCP has a keepalive option, but it is off by default on most systems and its first probe often waits two hours. Application protocols, such as SSH with
ServerAliveInterval, usually send their own. - Explicit teardown. A logout or a protocol-level close message lets both sides free resources at once. Without it, state lingers until a timeout removes it.
- Recovery. A reconnecting client presents a token or a resume offset, as in the diagram.
Stateful middleboxes cause a common problem. NAT devices and firewalls track TCP connections and delete idle entries, often after a few minutes to an hour. If a session sits quiet longer than that, the next packet is dropped or reset even though both applications still consider the session open. An SSH session that freezes after lunch is the classic case. A keepalive shorter than the middlebox timeout fixes it.
You can set TCP keepalive on a Python socket. The constants for tuning the timers are Linux-specific, so the example guards them.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, "TCP_KEEPIDLE"): # Linux
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) # idle seconds before first probe
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10) # seconds between probes
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) # failed probes before giving up
print("keepalive enabled:", s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) == 1)
s.close()Common errors and gotchas
- Calling a TCP connection a session. The two live at different scopes. A closed connection does not always end a session, and an open connection does not prove a valid one.
- Assuming HTTP is stateful. HTTP is stateless. Any apparent login state comes from cookies, tokens, or server-side storage.
- Predictable or reused session IDs. A guessable ID allows session hijacking. Generate IDs from a cryptographic random source, as
secrets.token_hexdoes above. Issue a new ID after login to prevent session fixation, where an attacker plants a known ID before the victim authenticates. - Sending IDs over plain HTTP. Anyone on the path can read the cookie. Use TLS, and add the
SecureandHttpOnlycookie flags in production. The demo omitsSecurebecause it runs over plain HTTP on localhost. - Server-side state that does not scale. If session data lives in one server's memory, a load balancer that sends the next request to a different server loses the session. Fixes are sticky routing or a shared session store.
- Blaming the wrong layer. Intermittent logouts are often a load balancer or timeout configuration, not a network fault.
Spotting session problems when troubleshooting
When the lower layers are healthy and the problem remains, look at session behavior. The earlier bottom-up sequence would show ping working and nc -zv connecting, yet the application misbehaves. Typical session-level symptoms are:
- Users are logged out at fixed intervals. This suggests an idle or absolute timeout.
- A connection works for a few minutes and then stalls. This suggests a NAT or firewall idle timer.
- Requests succeed on one server and fail on another. This suggests session state is not shared.
- A file transfer restarts from zero after a drop. This suggests the application has no checkpoint or resume feature.
On Linux, ss -tno shows TCP sockets with their keepalive timers, which helps confirm whether keepalives are active on a stalled connection.
Exercise
A user connects to a web application through a load balancer. They log in successfully, but about every third click sends them back to the login page. ping and nc -zv to the load balancer both succeed. Which layer's behavior is the most likely cause, what is the probable mechanism, and name one fix.
Show answer
The Session layer function (state kept across requests). Layers 3 and 4 are healthy, since ping and the TCP connection work. The load balancer is probably spreading requests across several servers, and the session state is stored in the memory of only one of them, so requests that land on another server find no matching session ID. Fixes: enable sticky sessions on the load balancer, or move session data to a store shared by all servers, such as a database or cache.
Exercise
Explain why a session can survive the loss of a TCP connection, and state what the client must present to the server to resume.
Show answer
A session is context (an ID and state such as a checkpoint) stored by the application above the transport. TCP only carries bytes, so when a connection breaks the stored context remains on the server until it times out. The client opens a new TCP connection and presents the session identifier, such as a cookie or token, and optionally a resume position. The server matches it to the saved state and continues.