# The mechanism and defense of ARP spoofing and man-in-the-middle (MITM) attacks [2026] — detect and neutralize attacks that exploit L2 trust

> A systematic explanation of the king of L2 attacks, 'ARP spoofing,' and the man-in-the-middle (MITM) attacks built on it — from mechanism to detection and defense. It shows the root cause that ARP has no authentication, the flow of twisting a victim's traffic to route through you, and neutralization via Dynamic ARP Inspection, DHCP Snooping, 802.1X, and TLS, together with type-safe detection code. With legal procedures confined to an isolated lab, it turns offensive understanding into defensive design.

- Published: 2026-06-28
- Author: 友田 陽大
- Tags: セキュリティ, ネットワーク, TCP/IP, 脆弱性診断, ホワイトハッカー, 倫理的ハッキング
- URL: https://tomodahinata.com/en/blog/arp-spoofing-mitm-attack-detection-defense-guide
- Category: 実践ネットワーク攻撃と防御
- Pillar guide: https://tomodahinata.com/en/blog/network-penetration-testing-methodology-attack-defense-guide

## Key points

- ARP spoofing is an L2 attack that scatters fake ARP replies saying 'the MAC for this IP is me' and twists the victim-gateway traffic to route through you. The root cause is that ARP has no source authentication (first to say it wins).
- Once MITM succeeds, sniffing (reading plaintext), tampering (rewriting), and session hijacking become possible on the path. The precondition is being on the same segment (same LAN/Wi-Fi).
- Detection monitors 'one MAC claiming multiple IPs' and 'the gateway's MAC suddenly changing.' You can notice it with arpwatch, switch logs, or ARP-table monitoring on endpoints.
- The main prevention is L2 infrastructure control: a switch's Dynamic ARP Inspection (DAI) + DHCP Snooping physically drops fake ARP. 802.1X keeps unauthorized devices from connecting in the first place.
- The last line of defense is TLS. Even if the path is seized, correctly verified TLS keeps the contents unreadable, and any rewrite is detected. The zero-trust stance of 'don't trust the network' renders ARP attacks meaningless.

---

Someone on the same Wi-Fi, the same LAN, **quietly inserts themselves** between you and the internet — this is a **man-in-the-middle (MITM) attack**, and its most classic and powerful entry point is **ARP spoofing**. The attacker fires not a single bullet; they merely scatter "fake ARP replies" and place all of the victim's traffic in the palm of their hand.

Following [the big picture of network pentesting](/blog/network-penetration-testing-methodology-attack-defense-guide), this article explains the mechanism of ARP spoofing/MITM accurately and shows **detection and RFC/vendor-standard-compliant defense** together with type-safe code. The core is [TCP/IP's fundamental premise of trust](/blog/tcp-ip-protocol-suite-fundamentals-complete-guide) that "ARP has no authentication."

> **Thoroughness of the safe zone**: ARP spoofing is especially dangerous in that it **drags in the traffic of third parties on the same segment**. The procedures in this article are executed only within an [isolated lab](/blog/ethical-hacking-home-lab-kali-juice-shop-ctf-self-study-roadmap-guide) (your own 3 VMs on an internal network). **Trying it on a shared Wi-Fi at work, school, a café, or home violates others' secrecy of communications and clearly violates the Unauthorized Access Act and the Telecommunications Business Act.** Getting the "target" wrong is far more serious than getting the attack tool's "command" wrong. Always read the [legal article](/blog/ethical-hacker-law-japan-unauthorized-access-act-active-cyber-defense-disclosure-guide) first.

---

## 1. Why ARP can be tricked — "trust without authentication"

ARP (Address Resolution Protocol) is the L2 protocol that resolves "IP address → MAC address." A host wanting to communicate with `10.10.10.1` (the gateway) within the same LAN asks like this.

```text
[ Who has 10.10.10.1? Tell 10.10.10.10 ]   ← ブロードキャストで全員に質問
[ 10.10.10.1 is at aa:bb:cc:dd:ee:ff   ]   ← ゲートウェイが応答
```

The host saves this reply in its **ARP cache** and thereafter sends to that MAC. The problem is — **ARP has no mechanism whatsoever to verify the source.** Anyone can reply "I am 10.10.10.1," and can even scatter **unsolicited replies (Gratuitous ARP)**. The receiving side believes unconditionally and overwrites its cache. **"First to say it wins"** — this is the root of everything.

---

## 2. ARP spoofing → MITM succeeding

The attacker (`10.10.10.5`) lies to both the victim and the gateway, inserting themselves into the path.

```text
攻撃者が撒く2つの嘘（偽 ARP 応答）：
  ① 被害者(10.10.10.10) へ → 「10.10.10.1(GW) のMACは 攻撃者のMAC だよ」
  ② ゲートウェイ(10.10.10.1) へ → 「10.10.10.10(被害者) のMACは 攻撃者のMAC だよ」

結果、通信経路が捻じ曲がる：
  被害者 ──► [ 攻撃者 ] ──► ゲートウェイ ──► インターネット
         ◄──          ◄──
  （双方は「直接やり取りしている」と思い込んでいる）
```

The attacker who seizes the path can, by enabling IP forwarding to pass traffic through transparently, stay **unnoticed by the victim**, and on top of that:

- **Sniff**: read the flowing plaintext (HTTP, old protocols) as-is (→ [packet sniffing](/blog/packet-sniffing-wireshark-tls-encryption-defense-guide)).
- **Tamper**: rewrite responses (SSL stripping that peels off the redirect to HTTPS, etc.).
- **Session hijacking**: use it as a base to [seize a TCP session](/blog/tcp-session-hijacking-rst-injection-ip-spoofing-defense-guide).

> In labs, `arpspoof` (dsniff), `ettercap`/`bettercap` are used as teaching material. **This article does not show the attack-launch commands** — the purpose is understanding the mechanism, and we devote the pages to neutralization (defense). If reproduction is needed, do it only between your own VMs in an isolated lab, following each tool's official documentation.

---

## 3. Detection — watch for "MAC-IP contradictions"

ARP spoofing leaves indelible traces: **"one MAC address claiming multiple IPs"** and **"the gateway's MAC suddenly changing."** Monitor these and you can notice.

### 3.1 What to use first in the field

- **`arpwatch`**: a classic staple that learns MAC↔IP correspondences and alerts on changes.
- **ARP-table monitoring on endpoints**: `ip neigh` (Linux) / `arp -a`. Is the gateway's MAC the known value.
- **Switch logs**: a managed switch records drops via DAI (below).

### 3.2 The minimal detection logic to understand the mechanism (type-safe)

Let's write a pure function that detects "contradictions" from ARP-observation events. It's a visualization of the principle; in production it should ride on `arpwatch`/IDS.

```ts
/** 観測した1件のARPアナウンス（IP がこの MAC を主張した、の記録）。 */
interface ArpObservation {
  readonly ip: string;
  readonly mac: string;
  readonly timestamp: number;
}

interface ArpAnomaly {
  readonly kind: "mac-claims-multiple-ips" | "ip-mac-changed";
  readonly detail: string;
}

/**
 * ARP 観測列から、スプーフィングの兆候を検出する純粋関数。
 * - 同一 MAC が多数の IP を主張（経路に挿入しようとする攻撃者の典型）
 * - 既知の IP↔MAC 対応が別 MAC に変化（ゲートウェイ詐称の典型）
 * 副作用なし＝決定的でテスト容易。誤検知は既知の信頼マップで除外する。
 */
export function detectArpSpoofing(
  observations: readonly ArpObservation[],
  trustedIpToMac: ReadonlyMap<string, string>,
  ipCountThreshold = 3,
): readonly ArpAnomaly[] {
  const anomalies: ArpAnomaly[] = [];
  const ipsByMac = new Map<string, Set<string>>();

  for (const o of observations) {
    // (1) 信頼済みの IP↔MAC が変化していないか（ゲートウェイ詐称の検出）
    const trusted = trustedIpToMac.get(o.ip);
    if (trusted !== undefined && trusted !== o.mac) {
      anomalies.push({
        kind: "ip-mac-changed",
        detail: `${o.ip} expected ${trusted} but saw ${o.mac}`,
      });
    }
    // (2) 1つの MAC が複数 IP を主張していないか
    const ips = ipsByMac.get(o.mac) ?? new Set<string>();
    ips.add(o.ip);
    ipsByMac.set(o.mac, ips);
  }

  for (const [mac, ips] of ipsByMac) {
    if (ips.size >= ipCountThreshold) {
      anomalies.push({
        kind: "mac-claims-multiple-ips",
        detail: `${mac} claims ${ips.size} IPs: ${[...ips].join(", ")}`,
      });
    }
  }
  return anomalies;
}
```

By passing `trustedIpToMac` (known correct correspondences for the gateway, etc.), you **structurally reduce false positives** while reliably catching the most dangerous case of gateway impersonation. The benefit of cutting the detection logic into a pure function is that you can fix tests with golden vectors and safely tune the threshold during operations.

---

## 4. Defense — neutralize in three layers

ARP attacks are neutralized in three layers: **infrastructure control (prevention) → authentication (connection control) → encryption (last line of defense).**

### 4.1 L2 infrastructure control: Dynamic ARP Inspection + DHCP Snooping (the main play)

With managed-switch features, **physically drop fake ARP.** This is the most effective prevention.

- **DHCP Snooping**: the switch learns "which IP was legitimately assigned to which MAC on which port" as a trust table.
- **Dynamic ARP Inspection (DAI)**: it checks ARP replies against this trust table and **drops contradictory ARP (= spoofing) at the port.**

```text
[ Cisco IOS の概念例（ベンダ公式手順に従う） ]
  ip dhcp snooping
  ip dhcp snooping vlan 10
  ip arp inspection vlan 10           ← VLAN10 で DAI 有効化
  interface gi0/1
    ip dhcp snooping trust            ← アップリンク(GW側)だけ信頼
  ! 端末ポートは untrust のまま → 端末からの偽ARPは検査され落ちる
```

### 4.2 Connection control: 802.1X so they can't get in at all

With port-based authentication via [IEEE 802.1X](https://1.ieee802.org/security/802-1x/), **a device that doesn't pass authentication can't even connect to the LAN.** It cuts off the attacker's physical/wireless access itself — the entry point of zero trust.

### 4.3 The last line of defense: TLS — "even if the path is seized, protect the contents"

This is essentially important. **Even if the path is seized by ARP, correctly verified TLS neutralizes the attack.**

- **Sniffing**: with TLS encryption, all the attacker reads is ciphertext.
- **Tampering**: TLS guarantees integrity. A rewrite is detected and the connection drops.
- **Impersonation**: thanks to certificate verification, the attacker can't present the legitimate server's certificate.

There's a condition, though — **never disable certificate verification** (`rejectUnauthorized: false` is strictly forbidden). And to prevent SSL stripping that targets the moment before the HTTP→HTTPS upgrade, make **HSTS** (`Strict-Transport-Security`) effective.

```ts
import { request } from "node:https";

// ✅ TLS 検証は既定で有効。MITM 下でも証明書不一致で接続が落ちる＝安全側に倒れる
const req = request(
  { hostname: "api.example.com", port: 443, path: "/", method: "GET" },
  (res) => {
    // res.socket は TLSSocket。検証済みでなければここに到達しない
    res.resume();
  },
);
// ❌ 絶対にやってはいけない：rejectUnauthorized: false（MITM を自ら招き入れる）
req.on("error", (e) => console.error("TLS handshake/verify failed:", e.message));
req.end();
```

> **The zero-trust conclusion**: discard the premise "it's safe because it's the internal LAN," and **don't make network location the basis of trust.** If you encrypt and authenticate all service-to-service communication with mutual TLS (mTLS), etc., even if the path is seized by ARP, **the attacker gets nothing.** This is the final answer that makes ARP attacks obsolete.

---

## 5. Summary

- **The root cause of ARP spoofing is "trust without authentication."** Anyone can fake "I am that IP," and the receiving side believes unconditionally.
- **Once MITM succeeds, sniffing, tampering, and [session hijacking](/blog/tcp-session-hijacking-rst-injection-ip-spoofing-defense-guide) become possible.** The premise is "being on the same segment."
- **Detection**: monitor MAC↔IP contradictions (one MAC, multiple IPs; the gateway's MAC changing) with `arpwatch`/IDS/a pure function.
- **Defense is three layers**: ① DAI + DHCP Snooping (physically drop fake ARP) ② 802.1X (don't let unauthorized devices in) ③ **TLS/mTLS (the last line of defense that protects the contents even if the path is seized).**
- **Don't disable TLS certificate verification, and make HSTS effective.** Zero trust renders ARP attacks meaningless.

Next, we'll handle **[DNS spoofing / cache poisoning](/blog/dns-spoofing-cache-poisoning-dnssec-defense-guide)**, which hijacks name resolution itself, including defense via DNSSEC.

---

I (Hinata Tomoda) have implemented TLS/mTLS conversion of service-to-service communication, certificate operations, and zero-trust network design (private subnet separation, least privilege, encryption required) in production. "I want to raise the MITM resistance of our internal network," "I want to inventory whether plaintext communication remains," "I want to introduce mTLS" — I diagnose such "don't trust the path" designs from the attacker's perspective and implement them with the two wheels of detection and encryption. Feel free to reach out.
