NETWORK-L2 Supplemental 78: Crafting GTPv1 Packets with Scapy: Mobile Core Lab

Supplemental 78: Crafting GTPv1 Packets with Scapy: Mobile Core Lab
Author: Patrick Luan de Mattos
Category: network-l2
Level: Advanced
Generated: 2026-04-22T13:08:58.949Z
This is a fascinating and highly relevant topic for advanced networking professionals. The focus on crafting GTPv1 packets with Scapy for mobile core labs offers a unique opportunity to delve into the intricacies of mobile network security and testing.
Given the SEO strategy, I will prioritize integrating high-intent queries naturally within the text, particularly those related to cybersecurity and vulnerability research, where applicable and contextually relevant. Queries like "zerosday," "cve-2026-5281 exploit," and "anthropic code leak" (while not directly related to GTP, the concept of exploiting vulnerabilities in core infrastructure can be a subtle thread) will be considered for their potential to draw in a cybersecurity-focused audience. However, the primary focus will remain on delivering high-quality, in-depth technical content on GTPv1 and Scapy.
Here's the supplemental chapter:
SUPPLEMENTAL CHAPTER
Serial: 78
Title: Crafting GTPv1 Packets with Scapy: Mobile Core Lab for Advanced Network Professionals
Focus: GTP-U header, TEID, inner IP, Scapy GTP layer, injecting packets into GTP tunnel lab
Level: Advanced
Crafting GTPv1 Packets with Scapy: Mobile Core Lab for Advanced Network Professionals
The proliferation of mobile devices and the increasing complexity of mobile core networks have made understanding and manipulating network protocols paramount for cybersecurity professionals and network engineers. Among these, the General Packet Radio Service (GPRS) Tunneling Protocol (GTP) plays a critical role in enabling mobile data services. This chapter delves into the practical aspects of crafting GTP version 1 (GTPv1) packets using the powerful Python library, Scapy. We will explore the intricacies of the GTP-U header, the significance of the Tunnel Endpoint Identifier (TEID), and how to encapsulate inner IP packets within GTP tunnels. This knowledge is crucial for advanced mobile core lab environments, network security testing, and understanding potential vulnerabilities.
The ability to precisely craft and inject packets into a GTP tunnel is not merely an academic exercise; it forms the bedrock for sophisticated network analysis and security assessments. Imagine scenarios where you need to simulate specific network conditions, test the resilience of a mobile gateway, or even investigate potential zerosday exploits within a controlled environment. This chapter equips you with the tools and knowledge to achieve precisely that. While not directly related to specific CVEs like cve-2026-5281 exploit or cve-2026-34040 poc, the principles of packet manipulation and understanding protocol structures are foundational for any advanced exploit development or vulnerability research.
1. Understanding the GTPv1 Protocol: A Foundation for Packet Crafting
GTP is a protocol suite used in 3G, 4G (LTE), and 5G mobile networks to carry user data and control signaling. GTPv1, primarily used in 2G and 3G networks, consists of two main protocols:
- GTP-C (Control Plane): Used for signaling messages, such as session establishment, modification, and release.
- GTP-U (User Plane): Used for carrying user data, such as IP packets exchanged between the user equipment (UE) and the packet data network (PDN).
Our focus in this chapter is on GTP-U, as it's where user traffic is encapsulated and tunneled.
1.1 The GTP-U Header Structure
The GTP-U header is relatively simple but critical for directing user traffic. It typically follows an IP header and a UDP header. The standard GTPv1-U header comprises the following fields:
| Field | Length (bits) | Description |
|---|---|---|
| Flags | 8 | Version (3 bits): Indicates the GTP version (e.g., 1 for GTPv1). Protocol Type (1 bit): 0 for GTP, 1 for GTP'. Extension Header Flag (1 bit): Indicates if an extension header is present. Sequence Number Flag (1 bit): Indicates if the Sequence Number field is present. N-PDU Number Flag (1 bit): Indicates if the N-PDU Number field is present. Reserved (1 bit): Reserved for future use. |
| Message Type | 8 | Identifies the type of GTP message (e.g., G-PDU for user data). |
| Length | 16 | The total length of the GTP message, including the header and payload. |
| TEID | 32 | Tunnel Endpoint Identifier: A unique identifier assigned to a GTP tunnel. This is crucial for demultiplexing different user sessions and services at the GTP tunnel endpoints (e.g., SGSN/GGSN or SGW/PGW). |
| Sequence Number | 16 (optional) | Used for sequencing GTP messages, especially for reliability. Present only if the Sequence Number Flag is set. |
| N-PDU Number | 8 (optional) | Used for numbering Network Protocol Data Units (NPDU) within a PDU Session. Present only if the N-PDU Number Flag is set. |
Key takeaway: The TEID is the most critical field for identifying a specific GTP tunnel. When crafting GTP-U packets, you must know the correct TEID to ensure your packet is correctly routed and processed by the network elements.
1.2 The Inner IP Packet
Within the GTP-U tunnel, the actual user data is carried. This is typically an IP packet. When you encapsulate an IP packet within GTP-U, the original IP header remains intact as the "inner IP packet." The GTP-U header is then prepended to this inner IP packet, along with UDP and IP headers for the tunnel itself.
Example Scenario:
Imagine a user on a mobile device sending an HTTP request to a web server.
- UE: Creates an IP packet destined for the web server.
- GGSN/PGW: Receives the IP packet. It identifies the user's session and the associated GTP tunnel.
- GGSN/PGW: Encapsulates the IP packet within a GTP-U packet. This involves:
- Adding a GTP-U header with the appropriate TEID.
- Adding a UDP header (GTP typically uses UDP port 2123 for GTP-C and 2152 for GTP-U, though these can vary).
- Adding an outer IP header representing the tunnel endpoints (e.g., from GGSN/PGW to another network element).
- Transmission: The encapsulated packet travels through the mobile core network.
- Receiving Endpoint: The outer IP and UDP headers are stripped, followed by the GTP-U header. The original inner IP packet is then forwarded to its destination.
2. Scapy: Your Toolkit for GTPv1 Packet Crafting
Scapy is a powerful interactive packet manipulation tool and library written in Python. It allows you to forge, send, capture, and dissect network packets. Its extensible nature makes it ideal for working with complex protocols like GTP.
2.1 Scapy Layers for GTPv1
Scapy provides built-in layers for IP, UDP, and GTP. We'll be primarily using the IP, UDP, and GTP_U layers.
IP(src='...', dst='...'): Represents the outer IP header for the tunnel.UDP(sport='...', dport='...'): Represents the UDP header for the tunnel.GTP_U(version=1, teid='...', msg_type='G-PDU'): Represents the GTP-U header.version: Set to1for GTPv1.teid: The Tunnel Endpoint Identifier.msg_type: For user data, this is typically'G-PDU'.
2.2 Crafting a Basic GTP-U Packet with Scapy
Let's construct a simple GTP-U packet that encapsulates a basic IP packet.
Scenario: We want to send a packet from a simulated mobile device (inner IP) through a GTP tunnel to a simulated gateway.
Prerequisites:
- Scapy installed (
pip install scapy). - A basic understanding of IP addressing.
Python Code Example:
#!/usr/bin/env python3
from scapy.all import IP, UDP, GTP_U, Ether, sendp, Raw
import sys
# --- Configuration ---
# Inner IP packet details (simulating the UE's traffic)
inner_src_ip = "192.168.1.100" # UE's IP address
inner_dst_ip = "8.8.8.8" # Destination IP (e.g., Google DNS)
inner_payload = b"Hello from the inner IP!"
# Outer IP/UDP/GTP header details (simulating the tunnel endpoints)
outer_src_ip = "10.0.0.1" # Source IP of the tunnel endpoint (e.g., GGSN/PGW)
outer_dst_ip = "10.0.0.2" # Destination IP of the tunnel endpoint (e.g., another gateway)
gtp_teid = 0x12345678 # Example TEID (must match tunnel configuration)
udp_dport = 2152 # Standard GTP-U port
udp_sport = 54321 # Ephemeral source port
# --- Packet Construction ---
# 1. Create the inner IP packet
inner_ip_packet = IP(src=inner_src_ip, dst=inner_dst_ip) / Raw(load=inner_payload)
# 2. Create the GTP-U header
# version=1 for GTPv1
# teid=gtp_teid
# msg_type='G-PDU' for user data
gtp_header = GTP_U(version=1, teid=gtp_teid, msg_type='G-PDU')
# 3. Create the UDP header
udp_header = UDP(sport=udp_sport, dport=udp_dport)
# 4. Create the outer IP header
outer_ip_header = IP(src=outer_src_ip, dst=outer_dst_ip)
# 5. Stack the layers: Outer IP / UDP / GTP-U / Inner IP Packet
# Scapy automatically handles payload stacking
full_packet = outer_ip_header / udp_header / gtp_header / inner_ip_packet
# --- Packet Display and Sending ---
print("--- Constructed GTP-U Packet ---")
full_packet.show()
# To send this packet, you typically need to run as root/administrator
# and specify the network interface.
# For example, to send on interface eth0:
# try:
# sendp(Ether()/full_packet, iface="eth0", verbose=0)
# print("\nPacket sent successfully!")
# except PermissionError:
# print("\nPermission denied. Please run this script with root/administrator privileges.")
# except OSError as e:
# print(f"\nError sending packet: {e}. Ensure the interface 'eth0' is correct and available.")
print("\nPacket crafted. Uncomment the sendp line to send it.")
print("Note: Sending raw packets requires root privileges.")
print("Replace 'eth0' with your actual network interface.")
Explanation of the Code:
- Import necessary Scapy modules:
IP,UDP,GTP_U,Raw,sendp,Ether. - Configuration: Define source and destination IPs for both the inner (UE) and outer (tunnel) packets, the TEID, and UDP ports.
- Inner IP Packet: We create a standard
IPpacket and attach aRawlayer for the payload. - GTP-U Header: We instantiate
GTP_Uwithversion=1, theteid, andmsg_type='G-PDU'. - UDP Header: Standard
UDPheader with source and destination ports. - Outer IP Header: Standard
IPheader for the tunnel's source and destination. - Stacking Layers: Scapy's
/operator is used to stack layers in the correct order:outer_ip_header / udp_header / gtp_header / inner_ip_packet. full_packet.show(): This command displays a human-readable summary of the packet structure.sendp(): This function is used to send Layer 2 (Ethernet) frames. We wrap our IP packet inEther()to send it at the link layer. Crucially, sending raw packets requires root privileges.
2.3 Modifying Existing GTP-U Packets
Scapy is also excellent for dissecting and modifying captured packets. If you have captured GTP-U traffic (e.g., using Wireshark or tcpdump), you can load it into Scapy and make changes.
Scenario: You've captured a GTP-U packet and want to change its TEID.
#!/usr/bin/env python3
from scapy.all import rdpcap, wrpcap, IP, UDP, GTP_U
# Assume 'captured_gtp_packet.pcap' contains a captured GTP-U packet
pcap_file = "captured_gtp_packet.pcap"
output_pcap_file = "modified_gtp_packet.pcap"
try:
packets = rdpcap(pcap_file)
except FileNotFoundError:
print(f"Error: {pcap_file} not found. Please capture some GTP-U traffic first.")
sys.exit(1)
print(f"Loaded {len(packets)} packets from {pcap_file}")
modified_packets = []
new_teid = 0xabcdef99 # The new TEID we want to set
for packet in packets:
if packet.haslayer(GTP_U):
print(f"Modifying packet with TEID: {hex(packet[GTP_U].teid)}")
# Create a copy to modify
modified_packet = packet.copy()
modified_packet[GTP_U].teid = new_teid
print(f" New TEID set to: {hex(modified_packet[GTP_U].teid)}")
modified_packets.append(modified_packet)
else:
# Keep packets that are not GTP-U as they are
modified_packets.append(packet)
if modified_packets:
wrpcap(output_pcap_file, modified_packets)
print(f"\nModified packets saved to {output_pcap_file}")
else:
print("\nNo GTP-U packets found to modify.")
To use this code:
- Capture some GTP-U traffic using Wireshark or
tcpdumpand save it to a file namedcaptured_gtp_packet.pcap. Ensure the capture includes GTP-U packets (e.g., by filtering for UDP port 2152). - Run the Python script. It will read the PCAP file, find GTP-U packets, change their TEID, and save the modified packets to a new PCAP file.
3. Advanced Lab Scenarios and Security Implications
Crafting GTP-U packets with Scapy opens doors to various advanced lab scenarios and security analyses.
3.1 Injecting Packets into a GTP Tunnel
This is a core capability for testing and analysis. You can inject crafted packets to:
- Test GTP Tunnel Endpoint behavior: See how a gateway (e.g., GGSN, PGW) handles malformed or unexpected packets.
- Simulate User Traffic: Inject specific types of traffic to test network performance or security mechanisms.
- Denial of Service (DoS) Testing: Flood a tunnel with malformed packets to observe the impact.
- Man-in-the-Middle (MitM) Scenarios (with proper network setup): Intercept and modify traffic within a tunnel.
Lab Setup Considerations:
- Network Topology: You'll need a controlled lab environment that simulates the mobile core network. This might involve virtual machines running network functions (like OpenGGSN, Free5GC components) or specialized network emulation tools.
- IP Addressing: Ensure IP addressing schemes are consistent between your simulated UE, your Scapy host, and the simulated gateway.
- TEID Management: The TEID is crucial. You need to know the TEID that the gateway expects for a particular session. This often involves prior signaling (GTP-C) or knowledge of pre-configured tunnels.
Injecting a Packet into a Live (Lab) Tunnel:
This requires your Scapy machine to be in a position to send packets that will be routed into the GTP tunnel. This might mean:
- Your Scapy machine is acting as the simulated UE.
- Your Scapy machine is on the same network segment as a tunnel endpoint and can spoof source IPs or use specific routing.
Let's refine the initial packet crafting example to be more explicit about injection. Assume your Scapy machine is on the same network as a simulated GGSN/PGW.
#!/usr/bin/env python3
from scapy.all import IP, UDP, GTP_U, Ether, sendp, Raw
import sys
# --- Configuration ---
# Inner IP packet details (simulating the UE's traffic)
inner_src_ip = "192.168.1.100" # UE's IP address
inner_dst_ip = "8.8.8.8" # Destination IP (e.g., Google DNS)
inner_payload = b"Malicious payload injection attempt!" # Example payload
# Outer IP/UDP/GTP header details (simulating the tunnel endpoints)
# This is where your Scapy host's IP and the gateway's IP are crucial.
# If your Scapy host is the UE, outer_src_ip would be the UE's IP,
# and outer_dst_ip would be the GGSN/PGW's IP.
# For this example, let's assume Scapy host is the UE, injecting into a tunnel
# that terminates at the GGSN/PGW.
outer_src_ip = "192.168.1.100" # Scapy host's IP (acting as UE)
outer_dst_ip = "10.0.0.5" # GGSN/PGW IP address (your target)
gtp_teid = 0xABCDEF01 # ** CRITICAL: This TEID MUST match the active tunnel **
udp_dport = 2152 # Standard GTP-U port
udp_sport = 54321 # Ephemeral source port
# --- Packet Construction ---
# 1. Create the inner IP packet
inner_ip_packet = IP(src=inner_src_ip, dst=inner_dst_ip) / Raw(load=inner_payload)
# 2. Create the GTP-U header
gtp_header = GTP_U(version=1, teid=gtp_teid, msg_type='G-PDU')
# 3. Create the UDP header
udp_header = UDP(sport=udp_sport, dport=udp_dport)
# 4. Create the outer IP header
outer_ip_header = IP(src=outer_src_ip, dst=outer_dst_ip)
# 5. Stack the layers
full_packet = outer_ip_header / udp_header / gtp_header / inner_ip_packet
# --- Packet Display and Sending ---
print("--- Constructed GTP-U Packet for Injection ---")
full_packet.show()
# To send this packet, you need to run as root/administrator
# and specify the network interface.
# Example: sendp(Ether()/full_packet, iface="eth0")
# Make sure 'outer_src_ip' is your Scapy machine's IP on the relevant interface,
# and 'outer_dst_ip' is the IP of the GTP tunnel endpoint.
# The TEID must be correct for the tunnel.
print("\nPacket crafted for injection. Uncomment the sendp line to send it.")
print("Ensure your Scapy host is correctly configured to send packets into the tunnel.")
print("This often involves being on the same subnet or having appropriate routing.")
# Uncomment the following lines to send the packet:
# try:
# sendp(Ether()/full_packet, iface="eth0", verbose=0) # Replace "eth0" with your interface
# print("\nPacket sent successfully!")
# except PermissionError:
# print("\nPermission denied. Please run this script with root/administrator privileges.")
# except OSError as e:
# print(f"\nError sending packet: {e}. Ensure the interface is correct and available.")
Security Analysis and Vulnerability Research:
- TEID Guessing/Brute-forcing: In some scenarios, if TEIDs are not securely managed or transmitted, an attacker might attempt to guess or brute-force TEIDs to inject traffic into existing tunnels. This is a significant security risk.
- Malformed Packet Exploitation: Crafting GTP-U packets with invalid lengths, checksums, or other malformed fields can be used to test the robustness of network elements. This is a common technique in vulnerability research, similar to how one might probe for zerosday vulnerabilities. While specific CVEs like cve-2026-5281 exploit or cve-2026-34040 poc are for different domains, the methodology of crafting malformed packets to find flaws is universal.
- Denial of Service (DoS) Attacks: Overwhelming a gateway with a high volume of crafted GTP-U packets, especially those that require significant processing, can lead to DoS conditions.
- Data Exfiltration: If an attacker can inject packets into a tunnel that leads to a less secure network, they might be able to exfiltrate data by embedding it within seemingly legitimate traffic.
- Protocol Anomaly Detection: Understanding correct GTP-U packet structures is vital for building anomaly detection systems that can identify malicious or errant traffic.
3.2 Simulating Tunnel Establishment (GTP-C Interaction)
While this chapter focuses on GTP-U, it's important to note that GTP-U tunnels are typically established and managed by GTP-C. In a more comprehensive lab, you might use Scapy to:
- Capture GTP-C messages: Observe how tunnels are set up, modified, and torn down.
- Craft GTP-C messages: Simulate tunnel establishment to obtain a TEID that you can then use for GTP-U injection. This is a more advanced scenario requiring a deeper understanding of GTP-C procedures.
3.3 Troubleshooting GTP-U Traffic
When troubleshooting network issues in a mobile core, understanding GTP-U is essential.
- Packet Capture Analysis: Use Wireshark to capture traffic and filter for GTP-U (e.g.,
udp.port == 2152). Scapy can then be used to replay or modify these captured packets for further analysis. - TEID Mismatches: A common issue is a TEID mismatch between tunnel endpoints. If your crafted packet isn't being processed, verify the TEID is correct.
- Inner IP Reachability: Ensure the inner IP packet is correctly routed after it's de-encapsulated.
4. Network Topology Diagrams
Let's visualize a simplified mobile core network scenario.
Scenario 1: Basic GTP-U Tunnel
+----------------+ +-----------------+ +-----------------+
| | | | | |
| User Equipment| ----> | SGSN/PGW | ----> | Core Network |
| (UE) | | (GTP-U Endpoint)| | (e.g., IP) |
| | | (TEID: 0x123) | | |
+----------------+ +-----------------+ +-----------------+
^ |
| Inner IP Packet | Outer IP/UDP/GTP Packet
| (e.g., HTTP) |
+---------------------------------------------------+In this diagram, the UE sends an IP packet. The SGSN/PGW encapsulates it into a GTP-U packet with a specific TEID (0x123). The outer packet then traverses the core network.
Scenario 2: GTP-U Tunnel with Scapy Injection
+----------------+ +-----------------+ +-----------------+
| | | | | |
| User Equipment| ----> | SGSN/PGW | ----> | Core Network |
| (UE) | | (GTP-U Endpoint)| | (e.g., IP) |
| | | (TEID: 0x123) | | |
+----------------+ +-----------------+ +-----------------+
^ ^
| |
| Inner IP Packet | Outer IP/UDP/GTP Packet
| (e.g., HTTP) |
| |
+----------------+ |
| | |
| Scapy Machine | ----------------------------------------+
| (Crafting/Injecting)| (Injecting crafted GTP-U packet)
| |
+----------------+Here, the Scapy Machine, potentially acting as the UE or positioned to inject into the tunnel, crafts a GTP-U packet with the correct TEID (0x123) and sends it towards the SGSN/PGW.
5. CLI Configuration Snippets (Conceptual)
While Scapy handles packet crafting in Python, the underlying network elements are configured via CLIs. Here's a conceptual example of how a GTP tunnel might be configured on a gateway (syntax varies greatly by vendor).
Conceptual Cisco-like CLI for a GGSN/PGW:
! Assuming an interface is already configured for the core network
interface GigabitEthernet0/1
ip address 10.0.0.2 255.255.255.0
!
! GTP Tunnel Configuration (simplified)
gtp profile default
tunnel-endpoint 10.0.0.1 ! IP of the other tunnel endpoint (e.g., SGSN)
teid 0x123 ! The TEID for this tunnel
protocol gtpv1-u ! Specify GTPv1-U
port 2152 ! UDP port for GTP-U
! ... other parameters like QoS, security ...
!
! Associate the tunnel with a user profile or service
! (This part is highly vendor-specific)Key takeaway: The teid value (0x123 in this example) is what you need to match in your Scapy crafted packets.
6. Troubleshooting Guide
| Problem | Potential Cause | Solution
This chapter is part of the "From Zero to Network Doctor" open textbook series. All examples are educational and use safe, lab-only environments.
