Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 80 ยท Network Security

Common Network Attacks and Defenses

Understand sniffing, spoofing, man-in-the-middle, DNS poisoning and DDoS attacks conceptually, with defenses and a rate-based DDoS detector built on synthetic traffic.

Most network attacks are not clever mathematics. They exploit the fact that the original protocols assumed everyone on the network was friendly: addresses can be forged, local traffic can be overheard, name lookups carry no proof, and a server will answer anyone who asks. Knowing how these attacks work, at the level of ideas, tells you which defense belongs where.

This lesson stays on the defender's side. We explain each attack conceptually, name the signs it leaves and the controls that stop it, and then write a detector for volumetric floods using made-up traffic. Nothing here shows how to carry out an attack. For the basics of layers and protocols, see Networking Essentials for Defenders.

Sniffing

Sniffing means capturing packets that pass by. On shared media, such as open Wi-Fi, or via a compromised switch or router, traffic is visible to others. If a protocol is unencrypted (HTTP, FTP, Telnet, old email protocols), usernames, passwords and content are readable as plain text.

Defenses: encrypt in transit everywhere (TLS, SSH, VPNs; see TLS, Certificates and PKI), retire cleartext protocols, use switches that limit what each port sees, and protect physical access to network gear. Legitimate sniffing is also a defensive tool: administrators capture traffic to diagnose problems and to investigate incidents.

Spoofing

Spoofing is forging an identifier so traffic looks like it came from somewhere else.

  • IP spoofing: a packet carries a fake source address. It matters mainly for connectionless traffic (UDP, ICMP) and for floods, where the sender does not need the reply. ISPs and routers can fight it with ingress and egress filtering, dropping packets whose source address could not come from that side of the link.
  • ARP spoofing: on a local network, an attacker answers ARP requests claiming to own another device's address, usually the gateway, so that victims send their traffic through the attacker. Defenses include dynamic ARP inspection and port security on managed switches, static entries for critical devices, and encrypted protocols so intercepted traffic is useless.
  • Email and caller spoofing forge sender names, which is why SPF, DKIM and DMARC exist (see Phishing and Social Engineering).

Man-in-the-middle (MITM)

In a man-in-the-middle attack, the attacker sits between two parties, relaying messages and possibly reading or altering them, while each side believes it talks directly to the other.

flowchart LR
    U["User"] -- "thinks it talks to the bank" --> M(("Attacker<br/>in the path"))
    M -- "relays, reads, alters" --> B["Bank"]
    U -. "what should happen" .-> B

The attacker gets into the path through spoofing (ARP, DNS, rogue Wi-Fi) and then relays traffic.

Getting into the path is the hard part: a rogue access point named like the cafe's network, ARP spoofing, DNS poisoning or a compromised router are the usual ways. Once there, the strength of the attack depends entirely on the protocol. Against plain HTTP the attacker sees everything. Against TLS, the attacker must present a certificate that the client accepts, and a properly validated certificate chain makes that fail. This is why users should never click through certificate warnings, and why HSTS and certificate pinning exist (HTTP Security Headers). End-to-end authentication, not the network, is the real defense.

DNS attacks

DNS answers are unauthenticated by default, so several attacks exist:

  • Cache poisoning: the attacker tricks a resolver into storing a false answer for a name, such as bank.example, so that every client of that resolver is sent to a malicious address. Modern resolvers defend with random source ports and random transaction IDs, which makes blind forging statistically hard, and DNSSEC adds signatures to prove records are genuine.
  • Hijacking: taking over the domain registrar account or the DNS provider account, then changing records legitimately. Strong authentication and registry locks are the defense.
  • Tunneling and exfiltration: hiding data inside DNS queries to unusual names, which most firewalls allow. Detection looks for very long, high-entropy names or huge numbers of queries to one domain.
  • Amplification: a small spoofed query triggers a much larger response sent to the victim.

Denial of service

A denial-of-service (DoS) attack tries to make a service unavailable, attacking the "A" in the CIA triad. With many machines, often a botnet of infected devices, it becomes a distributed attack (DDoS). Attacks fall into three groups:

Type Target Example
Volumetric Bandwidth UDP floods, reflection and amplification (DNS, NTP)
Protocol Connection tables and devices SYN floods that leave half-open connections
Application The app itself Many expensive HTTP requests to search or login

Defenses work in layers: overprovisioned capacity and anycast networks that spread traffic across many sites, upstream scrubbing by a CDN or DDoS-protection provider, SYN cookies to survive SYN floods, rate limiting (API Security), caching, and a tested playbook that includes contacting your provider early. Importantly, you cannot filter what already saturates your own link; protection must sit upstream of it.

Other attacks to recognize

  • Port scanning and reconnaissance: probing for open services. Scans are noisy and easy to detect, as shown in Intrusion Detection and Network Monitoring.
  • Session hijacking: stealing a session token to impersonate a user (Sessions, Cookies and JWTs).
  • Replay: capturing valid messages and sending them again; countered by nonces, timestamps and expiry.
  • Rogue devices: unauthorized access points and DHCP servers; countered by network access control and monitoring.

Detecting a flood with a rate-based detector

A simple and effective approach to spotting floods is to count requests per source in a time window and compare them with normal behavior. The synthetic traffic below mixes ordinary clients, one aggressive scraper and a distributed flood in which each source is individually quiet, but the total rate explodes. Seeds make the output reproducible.

Python Per-source and total rate detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The single noisy client can simply be blocked or throttled. The distributed flood only shows up in the total and in the number of distinct sources, and blocking individual addresses does not help much. That requires upstream scrubbing or protections that act on behavior across the whole population, such as challenging unknown clients. Thresholds need baselines: set them from measured normal traffic, and revisit them after product launches, because a real success looks like an attack to a naive detector.

The second demo shows the other half of an effective defense, a sliding window counter that can throttle clients without storing every request:

Python Sliding-window throttle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Putting defenses together

No single measure handles this whole list. Notice how the same few controls keep appearing: encryption and authentication beat sniffing and MITM; filtering and segmentation limit spoofing and scanning (Firewalls, Segmentation and Zero Trust); signed DNS and strong registrar security protect names; capacity, rate limits and upstream providers handle floods; and monitoring ties everything together so that you notice what slipped through.

Web server attacks

The attacks above hit the network path. A web server also has its own typical weaknesses. This section names five that defenders meet often, explains why they work, and shows the fix in code. Everything runs locally on made-up data.

Website defacement

Defacement replaces a site's pages with the attacker's message. It is usually a symptom, not the attack itself: the attacker gained write access through a vulnerable CMS plugin, stolen administrator credentials, an exposed upload form or a misconfigured file share. The business impact is reputation and trust, and a defaced page often hides a deeper compromise (backdoors, stolen data). Defend by patching content-management software, restricting write access, using MFA for administration, deploying sites from version control rather than editing live files, and monitoring file integrity: compare file hashes with a known-good baseline and alert on any change (Hash Functions and Integrity).

HTTP response splitting and header injection

A server builds response headers from strings. If it copies user input into a header, such as a redirect target in Location: ..., and the input contains the carriage return and line feed characters (\r\n) that end a header line, the attacker can add headers or even start a second response. Consequences include setting cookies, poisoning caches, or planting content that is served to other users. The fix is to reject or strip CR and LF from anything placed in a header, to use the framework's header API (modern frameworks refuse newlines), and to validate redirect targets against an allow-list (Input Validation and Sanitization, HTTP Security Headers).

Python Header injection and the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

DNS hijacking

In DNS hijacking, the answers for a domain are changed so users reach the attacker's server. It can happen at several places: the registrar account (stolen password, no MFA), the domain's DNS hosting account, a compromised home router whose DNS settings were changed, malware on a device, or a rogue resolver. The padlock does not always save users, because attackers can obtain valid certificates when they control DNS. Defend with a registrar lock and MFA on registrar and DNS accounts, DNSSEC to sign records, monitoring for unexpected record changes and for certificates issued for your domain (Certificate Transparency), strong router passwords, and CAA records that say which CAs may issue (TLS, Certificates and PKI). The earlier section on DNS attacks covers cache poisoning and tunnelling.

SSH brute force

Any SSH server on the public internet receives constant password-guessing from bots, which shows up as thousands of Failed password lines in the log. The risk is real if passwords are weak or root login is allowed. The solution is to disable password logins and use keys, disable direct root login, restrict access by firewall or VPN, rate-limit or ban repeated failures with a tool such as fail2ban, and enable MFA for sensitive hosts (VPNs, Wi-Fi and Remote Access Security). Detection is simple log analysis:

Python Spot SSH password guessing in an auth log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Directory traversal on servers

Directory (path) traversal happens when a server builds a file path from user input without checking that the result stays inside the intended folder. Sequences such as ../ climb out of the web root, and URL-encoded or double-encoded variants try to slip past naive filters. The impact is reading configuration files, source code and credentials. Defend by resolving the final path and verifying that it is inside the allowed base directory, rather than searching for .. strings, by serving only known file identifiers, and by running the web server with minimal file permissions (Secure Coding Principles).

Python Safe file serving: resolve, then check the base

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The naive filter is fooled twice: the encoded version contains no literal .., and an absolute path makes join discard the base entirely. The safe version decodes, normalizes and compares against the base directory, so both attempts end up denied or confined inside it. The same "validate the resolved value" principle prevents many injection bugs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does HTTPS with proper certificate validation defeat most man-in-the-middle attacks on the path?

    Even if an attacker relays packets, the client checks that the certificate chain is valid for the domain. Without such a certificate, the attacker cannot impersonate the server.
  2. 2. A DNS resolver starts returning an attacker's address for a bank's domain for all its users. What is this attack called?

    The resolver's cache holds a false record. DNSSEC, random ports and random transaction IDs are defenses.
  3. 3. In the detector demo, why did the distributed flood not trigger the per-source rule?

    A DDoS spreads the load across many addresses, so per-source counts stay low. Total-rate and distinct-source measures reveal it.
  4. 4. Which defense is most effective against a volumetric flood that saturates your internet link?

    Traffic that already fills your link cannot be filtered after it arrives. Providers with large networks absorb and clean it before it reaches you.
  5. 5. Which pair is correct?

    ARP only operates on the local segment, and switch features such as dynamic ARP inspection check the mappings. The other pairs mix up attacks and defenses.

Summary

  • Sniffing, spoofing, MITM and DNS attacks exploit protocols that assumed trust; encryption plus authentication (TLS, SSH, DNSSEC) is the core remedy.
  • Local-network attacks such as ARP spoofing are countered by switch features, segmentation and encrypted protocols.
  • DoS attacks target availability: volumetric, protocol and application variants need layered defenses, including upstream scrubbing.
  • Detect floods with per-source and total-rate counters set from measured baselines; sliding windows and token buckets throttle abuse.
  • Attacks are conceptual building blocks: the defender's job is to cut each one with the right layer of control and watch for the rest.

Next: VPNs, Wi-Fi and Remote Access Security, where you'll secure the links people use from outside the office.