Session Layer
The Session Layer, Layer 5 of the OSI model, manages communication sessions between networked devices. A session is a logical channel that enables two nodes to exchange data in an organized manner. This layer ensures reliable communication by controlling when conversations start and end, maintaining context for accurate data interpretation.
Beyond opening and closing sessions, the Session Layer provides synchronization and checkpointing mechanisms. It inserts markers in data streams so interrupted sessions can resume from the last checkpoint instead of restarting. This is particularly beneficial for long-running processes such as file transfers, database queries, or video streaming, as it enhances efficiency and reliability by reducing retransmissions.
While many modern protocols integrate session management into the Transport or Application layers, the Session Layer conceptually separates these responsibilities. It also interacts with authentication and security mechanisms to control access, ensuring only authorized applications or users can communicate. By handling these tasks, the Session Layer establishes a framework for reliable, organized, and stateful communication between devices.
Socket
A socket is a software interface that enables processes or applications to communicate with the Transport Layer of a network stack. It serves as an endpoint for sending and receiving data, providing a standardized way for programs to establish connections, transmit information, and interact with network services.
Each socket is uniquely identified by a combination of an IP address and a port number, defining the communication channel between two devices. Using sockets, applications can leverage transport protocols like TCP or UDP to exchange data reliably or quickly, depending on the protocol. This approach allows applications to avoid managing low-level details such as packet transmission, routing, and error handling directly.
Active Socket
The client uses an active socket to initiate a TCP connection. The process involves:
- Create a socket
- Connect to a server
nc # Netcat, a networking utility used to read/write data over TCP or UDP
192.168.1.1 # Target IP address (usually a local network device like a router or server)
1234 # Target port number to connect to on the remote system
(Client) nc 192.168.1.1 1234
Passive Socket
The server uses a passive socket to wait for incoming TCP connections. The process involves:
- Create a socket
- Bind IP and Port
- Listen to connections
- Accept a connection
nc # Netcat, networking utility for reading/writing data over TCP or UDP
-l # Listen mode, wait for an incoming connection instead of initiating one
1234 # Local port number to listen on
(Server) nc -l 1234
Authentication
Authentication verifies that a claimed identity is valid by ensuring the person, device, or system is who or what it claims to be. This serves as a critical security measure, preventing unauthorized access to sensitive data, applications, or systems.
Authentication can use various methods, including knowledge-based credentials (such as passwords or PINs), possession-based credentials (such as security tokens or smart cards), and inherent characteristics (such as fingerprints, facial recognition, or iris scans). By accurately verifying identities, authentication protects resources and establishes trust between users, devices, and systems in digital environments.
Authorization
Authorization determines whether a verified user, device, or system has the necessary permissions to access a resource or perform a specific action. After authentication confirms the identity, authorization enforces rules and policies to control what the entity can do, such as reading files, executing commands, or accessing certain network services.
This process is managed through methods such as access control lists, role-based access controls, and policy-based systems. Effective authorization ensures that even authenticated users are restricted to only permitted operations, protecting sensitive data, maintaining system integrity, and preventing unauthorized actions in digital environments.
Cyberattacks
- Session Hijacking: A threat actor accesses the user’s account using a stolen or leaked valid (existing) session identifier
- Session Fixation: A threat actor may trick a user into using a known session identifier to log in. after logging in, the session identifier is used to gain access to the user’s account.
- Session Replay: A threat actor may re-use a stolen or leaked session identifier to access the user’s account
PCAP Example
The client requested web content from the server, the client created a session for handling the connection.
Client initiates Session
The client browser creates an active socket to communicate with the server
| Layer | Protocol | PDU | Info | Ports | IPs | MACs |
| Application Layer | HTTP | Data | GET / HTTP/1.1 Host: 10.0.0.2 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Upgrade-Insecure-Requests: 1 | |||
| Presentation Layer | Raw | Data | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | |||
| Session Layer | Socket | Data | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | |||
| Transport Layer | TCP | Segments | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | Src Port: 35310 Dst Port: 80 | ||
| Network Layer | IP | Packets | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | Src Port: 35310 Dst Port: 80 | Src IP: 10.0.0.3 Dst IP: 10.0.0.2 | |
| Data Link Layer | Ethernet | Frames | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | Src Port: 35310 Dst Port: 80 | Src IP: 10.0.0.3 Dst IP: 10.0.0.2 | Src MAC: bc:35:db:cf:1b:03 Dst MAC: bc:f2:b8:57:86:02 |
| Physical Layer | Coax | Bits | 01001000 01010100 01010100 01010000 00101111 00110001 00101110 00110000 00100000 | 01001000 01010100 | 01001000 01010100 | 01001000 01010100 |


Server Accepts Session
The server has a passive socket that accepts the client’s connection
| Layer | Protocol | PDU | Info | Ports | IPs | MACs |
| Physical Layer | Coax | Bits | 01001000 01010100 01010100 01010000 00101111 00110001 00101110 00110000 00100000 | 01001000 01010100 | 01001000 01010100 | 01001000 01010100 |
| Data Link Layer | Ethernet | Frames | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | Src Port: 35310 Dst Port: 80 | Src IP: 10.0.0.3 Dst IP: 10.0.0.2 | Src MAC: bc:35:db:cf:1b:03 Dst MAC: bc:f2:b8:57:86:02 |
| Network Layer | IP | Packets | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | Src Port: 35310 Dst Port: 80 | Src IP: 10.0.0.3 Dst IP: 10.0.0.2 | |
| Transport Layer | TCP | Segments | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | Src Port: 35310 Dst Port: 80 | ||
| Session Layer | Socket | Data | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | |||
| Presentation Layer | Raw | Data | GET / HTTP/1.1\r\nHost: 10.0.0.2\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1 | |||
| Application Layer | HTTP | Data | GET / HTTP/1.1 Host: 10.0.0.2 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Upgrade-Insecure-Requests: 1 |
from http.server import SimpleHTTPRequestHandler # Import the built-in HTTP request handler
from socketserver import TCPServer # Import a basic TCP server implementation
from io import BytesIO # Import BytesIO to handle bytes in memory (for gzip compression)
from gzip import GzipFile # Import GzipFile to compress HTTP response
from datetime import datetime # Import datetime to generate timestamps for logging
from contextlib import suppress # Import suppress to prevent crasheswith suppress(Exception): # Try importing network interface details
from netifaces import gateways, ifaddresses, AF_INET, AF_LINK # Network interface utilities
print(“The default network interface is: “, gateways()[‘default’][AF_INET][1]) # Display default network interface name
print(“The default network interface mac address is: “, ifaddresses(gateways()[‘default’][AF_INET][1])[AF_LINK]) # Display MAC address of the default network interfaceclass Server(SimpleHTTPRequestHandler): # Define a custom HTTP server
def do_GET(self): # Handle HTTP GET requests
compressed = False # Track whether gzip compression is used
content = b'<HTML><h1>Hello World!</h1></HTML>’ # HTTP response body (bytes)if len(content) > 0: # Only attempt compression if content exists
if ‘accept-encoding’ in self.headers: # Check if client sent Accept-Encoding header
if ‘gzip’ in self.headers[‘accept-encoding’]: # Client supports gzip
bytes_ = BytesIO() # Create an in-memory byte buffer
with GzipFile(fileobj=bytes_, mode=’w’, compresslevel=5) as f: # Gzip wrapper
f.write(content) # Compress the response body
content = bytes_.getvalue() # Replace content with compressed bytes
compressed = True # Mark response as compressedself.send_response(200) # Send HTTP 200 OK status
if compressed:
self.send_header(‘content-encoding’, ‘gzip’) # Notify client of gzip encoding
self.send_header(‘content-length’, len(content)) # Send content length header
self.end_headers() # End HTTP headers
self.wfile.write(content) # Write response body to clientdef log_message(self, format, *args): # Override default request logging
print(“[{}] – {}:{} – {} {}”.format( # Custom log format
datetime.now().strftime(“%m/%d/%Y %H:%M:%S”), # Timestamp
self.client_address[0], # Client IP address
self.client_address[1], # Client source port
args[0], # HTTP method
args[1] # Requested path
))TCPServer((‘0.0.0.0’, 80), Server).serve_forever() # Start server on all interfaces, port 80
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
from io import BytesIO
from gzip import GzipFile
from datetime import datetime
from contextlib import suppress
with suppress(Exception):
from netifaces import gateways, ifaddresses, AF_INET, AF_LINK
print("The default network interface is: ",gateways()['default'][AF_INET][1])
print("The default network interface mac address is: ",ifaddresses(gateways()['default'][AF_INET][1])[AF_LINK])
class Server(SimpleHTTPRequestHandler):
def do_GET(self):
compressed = False
content = b'<HTML><h1>Hello World!</h1></HTML>'
if len(content) > 0:
if 'accept-encoding' in self.headers:
if 'gzip' in self.headers['accept-encoding']:
bytes_ = BytesIO()
with GzipFile(fileobj=bytes_, mode='w', compresslevel=5) as f:
f.write(content)
f.close()
content = bytes_.getvalue()
compressed = True
self.send_response(200)
if compressed:
self.send_header('content-encoding', 'gzip')
self.send_header('content-length', len(content))
self.end_headers()
self.wfile.write(content)
def log_message(self, format, *args):
print("[{}] - {}:{} - {} {}".format(datetime.now().strftime("%m/%d/%Y %H:%M:%S"), self.client_address[0],self.client_address[1],args[0],args[1]))
TCPServer(('0.0.0.0', 80), Server).serve_forever()
Server Sends the Data
The server sends data to the client
| Layer | Protocol | PDU | Info | Ports | IPs | MACs |
| Application Layer | HTTP | Data | HTTP/1.0 200 OK Server: SimpleHTTP/0.6 Python/3.11.6 Date: Sun, 18 Aug 2024 02:54:42 GMT content-encoding: gzip content-length: 49 <HTML><h1>Hello World!</h1></HTML> | |||
| Presentation Layer | GZIP | Data | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | |||
| Session Layer | Socket | Data | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | |||
| Transport Layer | TCP | Segments | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | Src Port: 80 Dst Port: 35310 | ||
| Network Layer | IP | Packets | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | Src Port: 80 Dst Port: 35310 | Src IP: 10.0.0.2 Dst IP: 10.0.0.3 | |
| Data Link Layer | Ethernet | Frames | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | Src Port: 80 Dst Port: 35310 | Src IP: 10.0.0.2 Dst IP: 10.0.0.3 | Src MAC: bc:f2:b8:57:86:02 Dst MAC: bc:35:db:cf:1b:03 |
| Physical Layer | Coax | Bits | 01001000 01010100 01010100 01010000 00101111 00110001 00101110 00110000 00100000 | 01001000 01010100 | 01001000 01010100 | 01001000 01010100 |
from http.server import SimpleHTTPRequestHandler # Import the built-in HTTP request handler
from socketserver import TCPServer # Import a basic TCP server implementation
from io import BytesIO # Import BytesIO to handle bytes in memory (for gzip compression)
from gzip import GzipFile # Import GzipFile to compress HTTP response
from datetime import datetime # Import datetime to generate timestamps for logging
from contextlib import suppress # Import suppress to prevent crasheswith suppress(Exception): # Try importing network interface details
from netifaces import gateways, ifaddresses, AF_INET, AF_LINK # Network interface utilities
print(“The default network interface is: “, gateways()[‘default’][AF_INET][1]) # Display default network interface name
print(“The default network interface mac address is: “, ifaddresses(gateways()[‘default’][AF_INET][1])[AF_LINK]) # Display MAC address of the default network interfaceclass Server(SimpleHTTPRequestHandler): # Define a custom HTTP server
def do_GET(self): # Handle HTTP GET requests
compressed = False # Track whether gzip compression is used
content = b'<HTML><h1>Hello World!</h1></HTML>’ # HTTP response body (bytes)if len(content) > 0: # Only attempt compression if content exists
if ‘accept-encoding’ in self.headers: # Check if client sent Accept-Encoding header
if ‘gzip’ in self.headers[‘accept-encoding’]: # Client supports gzip
bytes_ = BytesIO() # Create an in-memory byte buffer
with GzipFile(fileobj=bytes_, mode=’w’, compresslevel=5) as f: # Gzip wrapper
f.write(content) # Compress the response body
content = bytes_.getvalue() # Replace content with compressed bytes
compressed = True # Mark response as compressedself.send_response(200) # Send HTTP 200 OK status
if compressed:
self.send_header(‘content-encoding’, ‘gzip’) # Notify client of gzip encoding
self.send_header(‘content-length’, len(content)) # Send content length header
self.end_headers() # End HTTP headers
self.wfile.write(content) # Write response body to clientdef log_message(self, format, *args): # Override default request logging
print(“[{}] – {}:{} – {} {}”.format( # Custom log format
datetime.now().strftime(“%m/%d/%Y %H:%M:%S”), # Timestamp
self.client_address[0], # Client IP address
self.client_address[1], # Client source port
args[0], # HTTP method
args[1] # Requested path
))TCPServer((‘0.0.0.0’, 80), Server).serve_forever() # Start server on all interfaces, port 80
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
from io import BytesIO
from gzip import GzipFile
from datetime import datetime
from contextlib import suppress
with suppress(Exception):
from netifaces import gateways, ifaddresses, AF_INET, AF_LINK
print("The default network interface is: ",gateways()['default'][AF_INET][1])
print("The default network interface mac address is: ",ifaddresses(gateways()['default'][AF_INET][1])[AF_LINK])
class Server(SimpleHTTPRequestHandler):
def do_GET(self):
compressed = False
content = b'<HTML><h1>Hello World!</h1></HTML>'
if len(content) > 0:
if 'accept-encoding' in self.headers:
if 'gzip' in self.headers['accept-encoding']:
bytes_ = BytesIO()
with GzipFile(fileobj=bytes_, mode='w', compresslevel=5) as f:
f.write(content)
f.close()
content = bytes_.getvalue()
compressed = True
self.send_response(200)
if compressed:
self.send_header('content-encoding', 'gzip')
self.send_header('content-length', len(content))
self.end_headers()
self.wfile.write(content)
def log_message(self, format, *args):
print("[{}] - {}:{} - {} {}".format(datetime.now().strftime("%m/%d/%Y %H:%M:%S"), self.client_address[0],self.client_address[1],args[0],args[1]))
TCPServer(('0.0.0.0', 80), Server).serve_forever()
Client Receives Data
The client receives the data within the session
| Layer | Protocol | PDU | Info | Ports | IPs | MACs |
| Physical Layer | Coax | Bits | 01001000 01010100 01010100 01010000 00101111 00110001 00101110 00110000 00100000 | 01001000 01010100 | 01001000 01010100 | 01001000 01010100 |
| Data Link Layer | Ethernet | Frames | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | Src Port: 80 Dst Port: 35310 | Src IP: 10.0.0.2 Dst IP: 10.0.0.3 | Src MAC: bc:f2:b8:57:86:02 Dst MAC: bc:35:db:cf:1b:03 |
| Network Layer | IP | Packets | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | Src Port: 80 Dst Port: 35310 | Src IP: 10.0.0.2 Dst IP: 10.0.0.3 | |
| Transport Layer | TCP | Segments | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | Src Port: 80 Dst Port: 35310 | ||
| Session Layer | Socket | Data | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | |||
| Presentation Layer | GZIP | Data | HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.11.6\r\nDate: Sun, 18 Aug 2024 02:54:42 GMT\r\ncontent-encoding: gzip\r\ncontent-length: 49\r\n\r\n….rb.f……….0..H…W../.IQ……..g..7″… | |||
| Application Layer | HTTP | Data | HTTP/1.0 200 OK Server: SimpleHTTP/0.6 Python/3.11.6 Date: Sun, 18 Aug 2024 02:54:42 GMT content-encoding: gzip content-length: 49 <HTML><h1>Hello World!</h1></HTML> |

