🔑 The OSI Model
The OSI reference model
The OSI model (Open Systems Interconnection Model) is a reference model that structures the functionality of networks in seven layers and describes how data is communicated between different systems in a network. It was developed by the International Organization for Standardization (ISO) to standardize and simplify communication in networks.
The Seven Layers Of The OSI Model
Vizualisation of the OSI model
Layer 1: Physical Layer
Responsible for the transmission of raw data (bits) over a physical medium, such as cables or radio waves. It defines mechanical, electrical and functional specifications for the activation, maintenance and deactivation of physical connections.
Examples: network cables (Ethernet), wireless technologies (WLAN, Bluetooth), signal amplifiers.
Layer 2: Data Link Layer
Ensures the reliable transmission of data frames over a physical connection, detects and corrects errors on the physical layer and ensures the control of the data flow.
The data link layer is often divided into two sublayers:
- MAC (Media Access Control): Responsible for physical addressing (MAC addresses) and access to the transmission medium.
- LLC (Logical Link Control): Responsible for controlling the data flow and error detection.
Examples: Ethernet, switches, MAC addresses, Wi-Fi.
Layer 3: Network Layer
Manages the addressing and routing of data packets through different networks and ensures the correct delivery of the data to the destination. It uses logical addresses, such as IP addresses.
Examples: Router, IP (Internet Protocol), ICMP (Internet Control Message Protocol).
Layer 4: Transport Layer
Ensures reliable data transmission between end systems, controls data flow, segments data into smaller units and provides error correction and recovery of lost data. It offers either connection-oriented (e.g. TCP) or connectionless communication (e.g. UDP).
Examples: TCP (Transmission Control Protocol), UDP (User Datagram Protocol).
Layer 5: Session Layer
Establishes connections (sessions) between two end systems, manages them and ensures the synchronization of the data flow. It also ensures the resumption of interrupted sessions.
Examples: Session management in remote connections (e.g. SMB, NFS, RPC).
Layer 6: Presentation Layer
Translates the data into a standardized format and ensures that the data can be understood by both communication partners by converting different encodings and data formats (such as text, binary data, multimedia). It also takes care of encryption and compression.
Examples: Encryption (SSL/TLS), data compression, character set encoding (e.g. ASCII, Unicode).
Layer 7: Application Layer
This layer provides direct interfaces for applications to communicate with the network. This is where the interactions between the end user’s software and the network services occur.
Examples: HTTP, FTP, SMTP, DNS, POP3.
Data flow through the OSI model
When data is transmitted from a sender to a receiver, it passes through the various layers of the OSI model in a layer-by-layer process:
- At the sender: The data is processed from the application layer (layer 7) to the physical layer (layer 1) and converted into packets, segments, frames and finally bits that are transmitted over the physical medium.
- At the receiver: The received bits go through the reverse process and are passed from the physical layer back to the application layer, converting the data to its original form. As you might guess, the OSI model is structured like an onion.
Advantages of the OSI model
-
Standardization: The OSI model provides a standardized scheme to facilitate communication between different network devices and technologies.
-
Modularity: Each layer has clearly defined tasks and can be developed independently of other layers.
-
Troubleshooting: The separation into layers makes error diagnosis easier because it is clear which layer is responsible for which aspect of communication.
-
Interoperability: It enables devices from different manufacturers and technologies to communicate with each other.
Comparison to the TCP/IP model
The TCP/IP model, which dominates the Internet, is similar but has a simpler structure. It consists of only four layers (network access, Internet, transport and application) and is less formal and more flexible than the OSI model.
Structure of the TCP/IP model
How each OSI layer can be attacked
In the OSI model, there are potential attack vectors at each layer that can be exploited by cybercriminals. Here is an explanation of each layer of the model with a corresponding cyberattack and, where appropriate, Python code snippets to illustrate the attacks.
1. Physical Layer Attack
Attack: Jamming (Signal Interference)
- Description: An attacker disrupts physical transmissions by jamming radio signals or flooding the network. This is often done on wireless networks (e.g. Wi-Fi) to interrupt legitimate traffic.
Physical Layer Attack using Jamming (Signal Interference)
Defense:
- Frequency hopping: Wireless systems can switch to a different frequency band to avoid interference.
- WLAN security tools: Tools such as WIDS (Wireless Intrusion Detection Systems) can detect suspicious activity and increase network protection.
- Physical security: Restricting access to radio frequency hardware and protecting critical infrastructure from physical access.
2. Data Link Layer Attack
Attack: MAC spoofing
- Description: The attacker changes his MAC address to spoof the identity of another device on the network and gain access to network resources.
- Example in Python: Using a library such as Scapy, you can manipulate MAC addresses.
from scapy.all import *
def spoof_mac(interface, new_mac):
# Sets the MAC address of the specified network interface
os.system(f"ifconfig {interface} down")
os.system(f"ifconfig {interface} hw ether {new_mac}")
os.system(f"ifconfig {interface} up")
print(f"MAC address of {interface} was changed to {new_mac}.")
spoof_mac("eth0", "00:11:22:33:44:55")
Sequence Layer on the Link Layer Attack using MAC spoofing
Defense:
- Port Security: Many switches support MAC port security, which restricts network access to specific MAC addresses. Unknown or spoofed MAC addresses are blocked.
- Network Access Control (NAC): Used to authenticate devices against policies before they are granted access to the network. A fake device will not be trusted.
- Monitoring and detection: Continuously monitoring MAC addresses and alerting to suspicious changes can help detect attacks early.
3. Network Layer Attack
Attack: IP spoofing
- Description: In IP spoofing, an attacker changes their IP address to impersonate a trusted user. This is often used to bypass firewalls or for DDoS attacks.
- Example in Python: Again, Scapy can be used to send IP packets with fake IP addresses.
from scapy.all import *
# Sends an IP-Paket with a spoofed source-IP-Address
packet = IP(src="1.2.3.4", dst="8.8.8.8") / ICMP()
send(packet)
Sequence Diagram of a Network Layer Attack using IP Spoofing
Defense:
- Ingress and egress filtering: Internet service providers (ISPs) and network administrators can set up filters to block spoofed IP addresses (e.g. BCP 38). Only valid IP addresses are allowed through.
- Intrusion Detection Systems (IDS): Systems such as Snort can analyze suspicious network traffic and detect IP spoofing.
- Higher-level authentication: Protocols such as IPsec provide secure authentication and encryption that ensures data comes from the correct source.
4. Transport Layer Attack
Attack: SYN Flood
- Description: An attacker floods a target system with a large number of SYN requests without completing the connection in order to exhaust the server’s resources and deny access to legitimate users.
- Example in Python: A SYN flood can be simulated using Scapy.
from scapy.all import *
# SYN flooding attack
def syn_flood(target_ip, target_port):
for _ in range(1000):
ip = IP(src=RandIP(), dst=target_ip)
tcp = TCP(sport=RandShort(), dport=target_port, flags="S")
packet = ip/tcp
send(packet)
syn_flood("192.168.1.1", 80)
Sequence Diagram on a Transport Layer Attack using SYN Flood
Defense:
- SYN cookies: A mechanism that allows servers to not reserve resources for half-open connections by handling SYN packets without saving state.
- Connection limits: Firewalls and load balancers can be set up to limit the number of outstanding TCP connections.
- DDoS protection services: Services such as Cloudflare and Akamai provide protection against such attacks by redirecting and filtering traffic to distributed servers.
5. Session Layer Attack
Attack: Session Hijacking
- Description: An attacker takes over a user’s active session to gain access to their communications and data. This is often done by intercepting session tokens.
- Example in Python: In Python, a simple sniffer can be used to intercept session tokens.
from scapy.all import *
def sniff_sessions(interface):
sniff(iface=interface, prn=lambda x: x.show(), filter="tcp")
sniff_sessions("eth0")
This code intercepts TCP packets, which may also contain session tokens. The attacker would then attempt to steal and use the token.
Sequence Diagram of Session Layer Attack using Session Hijacking
Defense:
- Encryption (TLS/SSL): All traffic should be encrypted to prevent session token interception.
- Session timeouts and renewal: Sessions should expire after a certain time or be secured by periodically renewing the session token.
- Token protections: Implement Secure Cookies and HttpOnly flags to prevent session cookies from being stolen by JavaScript or over insecure connections.
6. Presentation Layer Attack
Attack: SSL Stripping
- Description: The attacker removes encryption by tricking the user into using HTTP instead of HTTPS, allowing sensitive data to be intercepted unencrypted.
- Example: SSL stripping requires special tools such as Bettercap or SSLstrip. Python can be used as a man-in-the-middle proxy to steal unencrypted data, but the code for SSL stripping is complex and requires manual proxy configuration.
Defense:
- HTTP Strict Transport Security (HSTS): Websites should enable HSTS to ensure the browser always uses HTTPS, even when an insecure connection is attempted.
- SSL/TLS Certificates: Ensure all web applications use a valid SSL/TLS certificate and avoid using Mixed Content (HTTP content on HTTPS pages).
- User Education: Users should be made aware to always look for the HTTPS certificate icon in their browser before entering sensitive data.
7. Application Layer Attack
Attack: Cross-Site Scripting (XSS)
- Description: An attacker injects malicious code (usually JavaScript) into a web application, which is then executed by the victim’s browser. This allows the attacker to steal sensitive data such as cookies.
- Example in Python: An example of XSS in a simple web framework such as Flask.
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def index():
name = request.args.get("name", "Guest")
# Vulnerability: Name is inserted unfiltered into HTML
return f"<h1>Hello, {name}</h1>"
if __name__ == "__main__":
app.run(debug=True)
An attacker could manipulate the URL to inject malicious JavaScript: http://localhost:5000/?name=<script>alert('XSS')</script>
. This would execute the script in the victim’s browser.
Sequence Diagram of an Application Layer Attack using XSS
Defense:
- Input validation: All user input should be thoroughly checked and filtered to prevent malicious code. Use libraries like DOMPurify to safely sanitize HTML.
-
Output Encoding: All user input should be securely embedded in HTML or JavaScript to ensure it is executed as text and not as code.
- Content Security Policy (CSP): CSP is an HTTP header-based method that allows restricting sources for scripts, images, and other resources to prevent malicious JavaScript from executing.