Skip to content
Tech Interview Prep
Technical interview guide

Network Security Basics

Firewalls, VPNs, and network segmentation: the perimeter and internal controls that limit blast radius.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: NIST SP 800-41 Rev. 1, SP 800-77 Rev. 1, SP 800-207/207A, CISA ZTMM 2.0, and RFC 8446 guidance accessed 2026-08-31..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-11

What is the primary difference in deployment and traffic handling between an IDS and an IPS?

Answer

The primary difference: an IDS is a sensor that sits off the forwarding path and inspects a copy of traffic; an IPS is a forwarding element that sits in the path and decides whether each packet continues. Latency, failure behaviour, and the cost of a false positive all follow from that one placement decision. If the box cannot drop the packet before it reaches the target, it is a detector, not a preventer.

Forwarding path

IDS — out of band (sees a copy)
[Client] --> [Switch] --> [Server]
                 |
            SPAN port / TAP
                 v
             [ IDS ]  -> alerts, logs, best-effort RST

IPS — inline (no packet passes without a verdict)
[Client] --> [ IPS ] --> [Server]
             decode -> match -> permit | drop | reject

Worked trace: one-packet exploit (hypothetical timings, 1 GbE LAN)

Attacker sends a single TCP segment that triggers a buffer overflow in an exposed service.

t (ms)IDS deploymentIPS deployment
0.000packet leaves attackerpacket leaves attacker
0.180switch forwards the original to the server and mirrors a copy to the sensorpacket arrives at the IPS
0.185server receives it and executes the exploit—
0.300sensor finishes signature matchIPS finishes decode + match, verdict = drop
0.310alert written to SIEMpacket discarded, never forwarded

The IDS alert lands roughly 125 µs after the exploit already ran. The IPS pays ~120 µs on every packet on that path, including the 99.99% that are benign. That is the trade: prevention costs per-packet latency and a hard dependency on the device staying up.

Trade-offs

DimensionIDSIPS
PlacementOut-of-band (SPAN/TAP)Inline (L2 bridge, routed hop, or firewall module)
Packet actionObserve; emit alert/logForward, drop, reject, or sanitize
Latency on live flowsNoneAdded to every packet's transit time
Failure modeFails open by construction: the monitored link never depended on itFails closed (outage) unless a hardware bypass relay or software fail-open is configured
False-positive costAlert fatigue in the SIEMDropped valid business transactions
Encrypted payloadsBlind to TLS without a decrypting proxySame limit; inline decryption breaks certificate pinning and adds its own latency

Failure modes and how you detect them

  1. IPS fail-closed outage. CPU saturation or a crash stops traffic unless a bypass relay mechanically shorts RX to TX on power loss. Detect: SNMP trap on bypass state, and compare rx/tx counters on both bridge interfaces. A widening gap means drops.
  2. IPS fail-open, silently. A bypass relay stuck closed after a power event lets traffic flow uninspected. Detect by comparing the IPS's own verdict logs against NetFlow from the adjacent router; a link with zero verdicts is not being inspected.
  3. IDS blind spots from the mirror. SPAN ports drop mirrored packets when the monitored link exceeds the SPAN port's capacity, and they strip FCS errors. Detect via the switch's SPAN drop counters and by comparing sensor-observed sessions against NetFlow.
  4. Reassembly mismatch. A passive sensor's IP/TCP reassembly must match the target's stack (overlapping fragments, TTL handling) or the attacker's packet is normalized differently than the victim sees it. An inline IPS normalizes before forwarding, so both sides see the same bytes.
  5. RST injection is not prevention. An IDS can spoof a TCP RST, but it races the server's response, does nothing for UDP or single-packet exploits, and modern stacks ignore in-window RSTs with a bad sequence number (RFC 5961). Treat it as a speed bump.

When not to go inline

Don't put an IPS inline where a false positive costs more than the attack: a link with no bypass option, or a latency-critical path. Use IDS-only there and accept that you detect rather than prevent. An IDS on a link you must protect but cannot afford to drop is a monitoring choice, not a control.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-4

How do stateful and stateless firewalls differ, and how do state tables track connections?

Answer

A stateless firewall evaluates each packet in isolation against static rules (typically 5-tuple: source IP, destination IP, protocol, source port, destination port). It retains no memory of past packets. To permit bidirectional communication (for example, client to web server), two explicit rules are mandatory: outbound traffic from client to server port 80/443, and inbound traffic from server port 80/443 back to high ephemeral ports (1024-65535). This leaves high ports open to unsolicited inbound scans and spoofed packets.

A stateful firewall inspects packet context within an active session using an internal state table. Once an outbound packet matches an allowed rule, the firewall creates a state entry and automatically permits reciprocal return packets without requiring open reverse ACL rules.

State Table Tracking Mechanism

For TCP, the firewall tracks protocol flags and sequence numbers across the handshake and teardown:

  1. SYN (Client -> Server): The firewall matches the packet against policy. If allowed, it creates an entry: [SrcIP:Port, DstIP:Port, Protocol, State=SYN_SENT, InitSeq=X, Timeout]. It verifies that return packets match the reversed 4-tuple.
  2. SYN-ACK (Server -> Client): The firewall checks the table, verifies that AckNum == InitSeq + 1, records server sequence number InitSeq=Y, and transitions state to SYN_RECV.
  3. ACK (Client -> Server): Verifies AckNum == InitSeq + 1, transitions to ESTABLISHED, and extends the session idle timeout (e.g., standard default 3600s).
  4. FIN / RST (Teardown): A FIN moves the state to FIN_WAIT or CLOSE_WAIT. When both ends close, a short closing timeout (e.g., 30–120s) clears the table entry.

For connectionless protocols like UDP and ICMP, the firewall creates "pseudo-state": an outbound UDP packet establishes an entry matching the reversed IP/port tuple with an idle timeout (typically 30–60s). Return packets refresh the timer. If no traffic flows before expiry, the entry drops.

Client (192.0.2.10:49152)             Firewall State Table Entry                   Server (198.51.100.5:443)
        |                                                                                    |
        |--- SYN (Seq=100) ----------------> [Created: TCP 192.0.2.10:49152 -> 198.51.100.5:443,  |
        |                                     State: SYN_SENT, Timeout: 30s] --------------> |
        |                                                                                    |
        |<-- SYN-ACK (Seq=500, Ack=101) ---- [Matched! State: ESTABLISHED,                 |<-- |
        |                                     Timeout: 3600s] <------------------------------|

Failure Modes & Trade-offs

AttributeStateless (e.g., Router ACLs, AWS Network ACLs)Stateful (e.g., Linux conntrack, AWS Security Groups)
Memory footprintO(1) negligible; line-rate fast pathO(N) where N = concurrent connections
Asymmetric routingHandles out-of-order/split paths nativelyDrops traffic if return path bypasses the stateful instance
State exhaustionImmune to connection table floodsVulnerable to SYN floods / state exhaustion (mitigated via SYN cookies)
Port exposureRequires broad ephemeral ingress rulesMinimal; return ports dynamically allowed for active flows

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Walk me through how ARP spoofing, MAC flooding, and VLAN hopping work at Layer 2, and which switch-level controls stop each one?

Answer

Every one of these attacks abuses a Layer 2 protocol that trusts whatever it is told. ARP lets any host claim any IP. A switch's MAC learning table trusts any source MAC it sees. 802.1Q trusts the tag on the frame, and DTP trusts whoever asks to become a trunk. The controls all have the same shape: make the switch verify a claim against something it learned from a trusted source, then rate-limit the rest.

ARP spoofing

ARP has no authentication and no state. An attacker sends gratuitous ARP replies: "10.0.20.1 is at aa:bb:cc:00:11:22". To hosts and to the gateway. Both sides overwrite their ARP cache, and the attacker is now on the path: a man-in-the-middle, or simply a blackhole for the gateway. Detection is a duplicate IP/MAC warning or two MACs claiming the gateway IP.

The control is Dynamic ARP Inspection (DAI). DAI intercepts ARP on untrusted ports and validates the (IP, MAC) pair against the DHCP snooping binding table; anything that does not match is dropped. ip arp inspection validate src-mac dst-mac ip adds a check that the Ethernet source MAC equals the ARP sender MAC, which catches a host spoofing an IP it does not own while keeping its own MAC. DAI depends on DHCP snooping, so static-IP hosts need an ARP ACL or they get dropped. Untrusted ports default to a 15 pps ARP rate limit; exceeding it err-disables the port.

MAC flooding

The CAM table is finite: typically 8K–16K entries on an access switch. An attacker sends frames with thousands of random source MACs until it fills. The switch then has no entry for legitimate destinations and falls back to flooding unknown unicast out every port in the VLAN: the switch behaves like a hub, and a promiscuous NIC on the attacker's port sees other hosts' traffic.

The control is port security: maximum MACs per port, optionally sticky, with violation restrict (log and drop) or shutdown (err-disable). 802.1X is the stronger version, binding the port to an authenticated identity. Port security does not stop an attacker from spoofing the one MAC it is allowed to use.

VLAN hopping

Two distinct techniques, often conflated:

  • Switch spoofing via DTP. An access port left in dynamic auto or desirable negotiates a trunk with the attacker, who then tags frames into any VLAN. Fix: switchport mode access plus switchport nonegotiate, and prune allowed VLANs on real trunks.
  • Double tagging. The attacker sits on the native VLAN and sends a frame with two 802.1Q tags. The first switch strips the outer (native VLAN) tag and forwards it; the next switch reads the inner tag and delivers into the target VLAN. It is one-way, replies never come back, so it is used for blind injection. Fix: move the native VLAN to an unused ID, tag the native VLAN on trunks, and never place access ports on it.
AttackWhat it abusesControlThe control's own failure mode
ARP spoofingUnauthenticated ARP repliesDAI + DHCP snoopingStatic-IP hosts silently dropped without ARP ACLs
MAC floodingFinite CAM tablePort security / 802.1XSticky MACs break VM migration and NIC teaming
DTP trunkAuto trunk negotiationnonegotiate, explicit access modeMisconfigured uplink loses trunking
Double taggingNative VLAN is untaggedNative VLAN moved to unused IDNative VLAN mismatch between switches

interface GigabitEthernet1/0/10 switchport mode access switchport access vlan 20 switchport nonegotiate switchport port-security maximum 2 switchport port-security violation restrict spanning-tree bpduguard enable

ip dhcp snooping ip dhcp snooping vlan 20 ip arp inspection vlan 20 ip arp inspection validate src-mac dst-mac ip interface GigabitEthernet1/0/1 ! uplink ip dhcp snooping trust ip arp inspection trust errdisable recovery cause psecure-violation errdisable recovery interval 300

Failure modes and limits

DHCP snooping without trust on the uplink kills DHCP for the whole VLAN. DAI without ARP ACLs breaks every static-IP server. Port security without err-disable recovery leaves a port dark after a single violation. And none of it survives the Layer 3 boundary: a host with a second NIC, a wireless association, or a VPN tunnel routes around the access switch entirely. These controls harden the access edge; they complement segmentation rather than replace it. Watch show ip arp inspection statistics, port-security violation counters, err-disable syslog, and CAM table utilization to know they are working.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

How does 802.1X network access control authenticate and authorize devices onto wired and wireless networks, and how does it differ from relying on a perimeter firewall?

Answer

802.1X (IEEE 802.1X-2020) is port-based access control. Three roles: the supplicant (client), the authenticator (switch port or AP), and the authentication server (RADIUS, e.g. FreeRADIUS or Cisco ISE). The authenticator holds the port in an uncontrolled state where only EAPOL frames (EAP over LAN, EtherType 0x888E) pass. Supplicant and RADIUS server run an EAP method end-to-end; the authenticator relays EAPOL to RADIUS and opens the controlled port only on success. The client gets no IP address until then: that is the whole point, and the whole difference from a firewall.

The exchange:

  1. Link up → authenticator sends EAP-Request/Identity.
  2. Supplicant replies with an outer identity, often anonymous (anonymous@corp), so the real username is not sent in the clear.
  3. Authenticator wraps it in a RADIUS Access-Request.
  4. EAP method runs. On success, RADIUS Access-Accept carries authorization attributes: Tunnel-Type=VLAN, Tunnel-Medium-Type=IEEE-802, Tunnel-Private-Group-ID=42, Filter-Id=ACL-name, Session-Timeout, or a vendor-specific dACL.
  5. Authenticator moves the port to authorized, applies the VLAN and ACL, and the client DHCPs.
  6. A reauth timer, or a RADIUS CoA/Disconnect-Request (RFC 5176), revokes access mid-session.
EAP methodCredentialNotes
EAP-TLSClient + server certsStrongest; needs PKI on every device
PEAPv0/EAP-MSCHAPv2Server cert + passwordCommon; supplicant must validate the server cert
EAP-TTLSServer cert + inner methodFlexible inner auth

Wireless is the same infrastructure: WPA2/WPA3-Enterprise uses 802.1X for 802.11 authentication, and the MSK from EAP becomes the PMK for the 4-way handshake.

Versus a perimeter firewall. A firewall is an L3/L4 chokepoint at a trust boundary; it filters a 5-tuple from hosts that already have network reachability. 802.1X is L2 admission control: identity decides whether the device gets a port at all, and the authorization result (VLAN, ACL) shapes what it can reach. A firewall cannot stop a rogue laptop from pulling a DHCP lease on the corporate VLAN; 802.1X can. They are complementary: 802.1X is the front door, the firewall is the interior doors.

Failure modes worth naming:

  • RADIUS outage. Fail-open authorizes the port with no policy; fail-closed drops it. Per-port-profile choice: a critical VLAN for phones and OT, fail-closed for user ports.
  • MAB (MAC Authentication Bypass). MAC addresses are spoofable in one line. Use only for devices that cannot run a supplicant, and pair with profiling plus a restricted VLAN.
  • Evil twin. PEAP without server-cert validation hands a rogue AP an MSCHAPv2 challenge for offline cracking. Pin the CA and the server name.
  • Certificate expiry across thousands of supplicants causes mass lockout; monitor expiry and automate renewal.
  • CoA storms and aggressive reauth timers flap ports; rate-limit and stagger.

When not to use it: guest and BYOD networks where onboarding friction outweighs the risk. A captive portal on a separate VLAN is the right call. And 802.1X never replaces segmentation or a firewall; it is an admission gate, not a policy engine.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does a Denial of Service (DoS) attack differ from a Distributed Denial of Service (DDoS) attack, and what are standard network mitigation techniques?

Answer

A Denial of Service (DoS) attack originates from a single source host or network path, aiming to exhaust target bandwidth, connection tables, or CPU. A Distributed Denial of Service (DDoS) attack coordinates traffic from many distributed sources, typically botnets or spoofed reflectors, making source-IP blocking ineffective and saturating upstream pipes before packets reach the host.

Attacks divide into three primary layers, each requiring distinct network mitigations based on NIST SP 800-41 Rev. 1 principles:

  1. Volumetric (L3/L4 floods such as UDP, ICMP, DNS/NTP amplification): Ingress bandwidth saturates upstream of the firewall. Defense requires upstream multi-homed BGP Anycast scrubbing, Remotely Triggered Black Hole (RTBH) routing, or Cloudflare/AWS Shield edge nodes absorbing aggregate gigabits/terabits.
  2. State-exhaustion (TCP SYN floods, ACK floods): Targets connection tracking (conntrack) tables on stateful firewalls, load balancers, or operating systems. Mitigations include SYN cookies (net.ipv4.tcp_syncookies = 1), stateful inspection proxying with aggressive embryonic connection timeouts, and TCP sequence validation.
  3. Application-layer (L7 HTTP GET/POST floods, slowloris): Legitimate-looking Layer 7 payloads that exhaust web server worker threads or database pools. Mitigations include reverse-proxy rate limiting, TLS connection offload, and Web Application Firewall (WAF) challenges.
Attack CategoryNetwork LayerPrimary Exhaustion TargetCore Mitigation
Volumetric (Amplification/Flood)L3 / L4 (UDP/ICMP)Transit link bandwidth, interface line-rateBGP Anycast scrubbing, Upstream RTBH, FlowSpec filtering
State-Exhaustion (SYN flood)L4 (TCP)Stateful firewall conntrack, OS SYN backlogSYN cookies, aggressive half-open timeouts, rate limits
Application-layer (Resource drain)L7 (HTTP/DNS)Backend thread pools, memory, database IOPSReverse proxy caching, WAF challenge/token, per-client rate limits

Worked defense trace for a state-exhaustion SYN flood:

Attacker (10,000 spoofed IPs) ---> [SYN Flood: 800,000 pkts/sec] ---> Edge Firewall / Proxy
                                                                          |
[Traditional Stateful Firewall]                                           |-- Evaluates half-open queue
- Allocates conntrack table entry per SYN                                 |-- Exceeds embryonic threshold
- Exhausts memory table within seconds                                    v
- Drops legitimate incoming traffic                                [Mitigation: SYN Cookie Mode]
                                                                   - Generates cryptographic cookie in Seq#
                                                                   - Allocates ZERO state in conntrack
                                                                   - Awaits [ACK with Seq# + 1]
                                                                   - Allocates session ONLY on valid ACK

Trade-offs and failure modes:

  • Upstream Blackholing (RTBH) stops pipe saturation but completes the denial of service for all users targeting the blackholed IP.
  • Aggressive rate limiting by CIDR risks blacklisting large residential NATs or enterprise egress gateways containing legitimate users.
  • SYN cookies disable advanced TCP extensions (like large window scales) unless TCP timestamp options are leveraged.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Explain zero trust and its relationship to segmentation and application authorization.

Answer

Core answer (say this first). Zero trust is an architectural principle, not a product: no user or workload is trusted because of its network location or who owns the asset. Every request is authenticated and authorized against policy built from identity, device posture and context, and the session it produces is narrowly scoped and re-evaluated as signals change. NIST SP 800-207 (August 2020) formalizes the pattern as a policy decision point (PDP) that evaluates the request and a policy enforcement point (PEP) that creates the session. Segmentation and application authorization are two enforcement layers under that policy, not alternatives to it.

Assume a multi-tenant SaaS on Kubernetes: humans authenticate through SSO, workloads carry SPIFFE identities, and a service mesh terminates mTLS.

Why the layers are orthogonal. Segmentation decides on network tuples (namespace, IP, port) so it can bound where a compromised workload reaches but it cannot see object identity. Application authorization decides on (subject, action, resource, context), so it can stop tenant A reading tenant B's record but it cannot see topology. A pod with a valid SVID passes authorization for its own tenant and is still stopped by a default-deny NetworkPolicy from reaching the payments namespace. A user with a valid session passes segmentation inside the cluster and is still stopped by an object-level check. That is why neither substitutes for the other.

Worked trace: request → identity-aware proxy (PEP) → PDP (OPA/Rego) evaluates policy → allow with scoped token → mesh mTLS to backend → backend runs a relationship check (Zanzibar-style ReBAC) → response. If the PDP is unreachable, the PEP fails closed.

LayerSeesDecidesBlind to
SegmentationIP, port, namespaceCan this workload reach that oneObject, tenant, field
App authorizationSubject, action, resourceMay this identity do thisNetwork topology
Channel crypto (mTLS)Peer identityIs this channel authenticWhether the action is allowed

Blast radius, worked example. A flat cluster of 500 pods: one compromised pod can reach all 500. Default-deny NetworkPolicy per 20-pod namespace cuts that to 20. Per-request authorization cuts it further to only the objects that identity is entitled to. The numbers are illustrative; the ordering is the point.

Trade-offs. Zero trust is not always worth it: a single-tenant internal tool behind SSO with no lateral-movement risk, or an air-gapped lab, gets little from a PDP and pays its latency and availability coupling. The credible alternatives are the perimeter/VPN model (cheaper, trusts location), microsegmentation alone (no object-level decisions), and an identity-aware proxy alone (no workload-to-workload control). Decide on tenant count, regulated data, and lateral-movement exposure.

Failure modes. PDP outage is the classic one: fail-open silently converts zero trust into no trust. Detect with PDP error-rate and authorization deny-rate dashboards. Stale policy after offboarding: detect with access-review diffs. Over-broad service accounts: detect with authz logs showing wildcard grants. Replayed tokens: bound with short SVID TTLs and alert on anomalous source.

Decision logic. Multiple tenants or regulated data: per-request authorization is mandatory. Segmentation is the cheap first step that bounds blast radius. Zero trust is the policy layer that makes both decisions from the same identity and context.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do you govern the lifecycle of a firewall rule?

Answer

What I'd say first

Assume a mid-size estate: a few thousand rules across a central firewall pair plus cloud security groups, changes through a ticket and a pipeline, and an auditor who asks once a year. Under those assumptions, governing a rule's lifecycle means treating every rule as a record with an owner, a justification, and a death date, and building the pipeline so a rule cannot exist without all three. The rule is the easy part. Firewalls accumulate rules faster than they retire them, and every stale rule is standing permission nobody is watching.

The five stages, and what each one actually enforces

Request. The ticket carries the five-tuple, the business flow it serves, an owning team (not a person), a data classification, and an expiry. Missing expiry gets a default: 90 days for a temporary exception, 12 months for a production flow. That default is the highest-leverage control in the process, because it turns "we'll clean it up later" into a queue with dates.

Review. Automated analysis runs before a human looks at it. Three checks earn their keep:

  • Shadowing: rule 47 permits 10.20.5.0/24 → 10.30.7.0/24 tcp/443, but rule 10 already permits 10.20.0.0/16 → 10.30.0.0/16 tcp/443. Rule 47 can never match. It is dead config that still shows up in audits and still has to be tested.
  • Overlap: two rules match some of the same traffic, so the effective policy is the union and neither owner knows the other exists.
  • Broad scope: 0.0.0.0/0 on 22, or a v4 rule added while the v6 path stays open.

AlgoSec, Tufin and FireMon do this offline against a config dump; the same analysis is a few hundred lines against nftables or security-group JSON.

Deploy. Simulate, then canary. Most enterprise firewalls have a policy-simulation mode; cloud groups can be staged in a non-prod VPC first. Then verify both directions: the intended path works and the paths that were denied are still denied. A rule that opens what you wanted and also opens something else passes "does it work" and fails "what else changed".

Reconcile. Git holds intent; the device holds reality. Drift is any delta: a console rule added at 03:00 during an incident, or a deploy that half-applied. Detection is a scheduled pull of the running config, normalized and diffed against the rendered intent, alerting on any delta. Hourly if the estate changes daily; daily is usually enough.

Retire. Expiry opens a renewal ticket for the owner rather than deleting anything, unless the rule is explicitly tagged temporary. Removal needs a dependency check: read hit counters across a full business cycle (a month, so month-end batch jobs show up) then disable rather than delete, wait one more cycle, then delete.

Trade-offs

Expiry versus review is the real choice. Expiry is cheap and catches everything, but it breaks long-lived flows at inconvenient times; review is safe but decays the moment the reviewer gets busy. The workable combination is expiry with owner re-justification, plus a hard cap, say 24 months, beyond which renewal needs a design review. And tighter governance is not always worth it: in a lab VPC where the blast radius is the lab, a 90-day expiry on every rule is pure friction.

Failure modes worth naming

  • Orphaned rule: the owner's team was dissolved, the rule still permits. Detect by resolving the owner field against the directory; the cost is an audit finding that sits open until someone claims it.
  • Drift: an incident fix made in the console, never backported. Detect with the config diff. The blast radius is nasty: the next pipeline deploy reverts the fix, or the drift is the only thing keeping a flow alive and nobody knows.
  • Shadowed rule: the control you believe is protecting a segment is not. This is the one that shows up in a breach timeline.
  • Expiry without a dependency check: the month-end job fails at 02:00 on the 1st.

Artefact

stagecontrolfailure signal
requestmandatory owner + expiryticket with no expiry
reviewshadow / overlap / broad-scope analysisrule never matches a hit counter
deploysimulate + canary + deny-path testallowed path works, denied path changed
reconcilescheduled config diffdelta between Git and device
retirehit-counter check, disable-then-deleteexpiry with no renewal and no owner

Arithmetic on why this matters: 2,000 rules, 15% added a year, 5% retired, is +200 net per year. Ten years of that and the rulebase has doubled, with the shadowing rate climbing alongside it: exactly the state where nobody can answer what the firewall actually permits.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Design firewall policy for a three-tier internet application.

Answer

Assumptions first. One AWS VPC 10.0.0.0/16, three subnets (public 10.0.1.0/24 (ALB), app 10.0.2.0/24, data 10.0.3.0/24 (RDS Postgres on 5432)) TLS terminated at the ALB, no IPv6 yet, no SSH to instances. If any of those change, the rules below change.

The answer. Default-deny at three layers, then permit only named flows, and prefer stateful enforcement so return traffic is free. Security groups are stateful and attach to the workload identity; NACLs are stateless and attach to the subnet. Use SGs for the real policy and NACLs only as a coarse subnet guard, because a stateless NACL is where most outages hide.

FlowEnforced byRule
Internet → ALBSG on ALBallow TCP 443 from 0.0.0.0/0; nothing else
ALB → appSG on appallow TCP 8080 from sg-alb (SG reference, not CIDR)
app → RDSSG on RDSallow TCP 5432 from sg-app
app → internetSG egress + NATallow TCP 443 to specific endpoints, not 0.0.0.0/0
ops → appSSM Session Managerno inbound 22 at all
data subnetNACLallow TCP 5432 in from 10.0.2.0/24; allow TCP 1024-65535 out to 10.0.2.0/24

Why it behaves this way. A stateful SG creates a conntrack entry on the first SYN; the SYN-ACK and all later packets in that flow are permitted without a matching inbound rule. That is why you never write a return rule for an SG. A NACL has no conntrack, so the return packet is evaluated as a fresh flow, and Linux's default ephemeral range is 32768-60999, so a NACL that only allows 443 out silently drops the SYN-ACK.

Trace one request. Client SYN to ALB:443 → ALB SG allows, conntrack entry created → ALB opens a new connection to app:8080, app SG allows because source is sg-alb → app opens a connection to RDS:5432, RDS SG allows because source is sg-app → every return packet is auto-allowed by statefulness. The only place this breaks is the data-subnet NACL: if its outbound range is 32768-60999 but the app's kernel picked a source port below that, the SYN-ACK is dropped and the app sees a timeout, not a refusal.

Trade-offs. SG-only is simplest and survives IP churn because rules reference SG IDs; its cost is you cannot write a deny rule, so containment is purely allow-list. NACLs can deny (useful to block a known-bad CIDR fast) but are stateless and ordered, and every ephemeral-port mistake becomes an intermittent outage. The stronger alternative is identity-based policy, mTLS with SPIFFE IDs or a service mesh, which wins when pods get new IPs every deploy and you want per-call authorization, at the cost of a mesh, cert rotation, and a new failure domain. A perimeter-only allow-list is cheaper still and fine for a single monolith, but a flat network also complicates PCI DSS scoping: v4.0 Req 1.3.2 requires inbound traffic to the cardholder data environment be restricted to only what is necessary, so an unsegmented app-to-data path fails an assessment.

Failure modes and detection. (1) NACL ephemeral-port omission → intermittent timeouts on long-lived connections; detect via VPC Flow Logs showing REJECT on the return path, not the request. (2) A rule widened to 0.0.0.0/0 on 5432 → detect with a nightly diff of the SG against the Terraform state and a custom Config rule that flags any 5432 rule whose source is not sg-app. (3) Asymmetric routing through a middlebox → conntrack drops half the flow; detect by comparing SYN and SYN-ACK counts per interface. (4) Drift from a console hotfix → detect by canarying the change on one AZ and rolling back if 5xx rises.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design outbound egress controls for application and build workloads.

Answer

Assumptions. Kubernetes on AWS (EKS), workloads in private subnets, and a build system that runs untrusted PR code. On VMs or GCP the shape is identical; the product names change.

The answer. Default-deny egress, then grant through one of three doors, in order of preference:

  1. Private endpoints for first-party services (S3, ECR, STS, KMS): no internet path at all.
  2. An authenticated egress proxy with a per-identity domain allowlist for everything else.
  3. Nothing else. The sensitive tier gets no NAT route.

Identity, not IP. The proxy authenticates the workload (mTLS SPIFFE ID, or an IAM task role signing the request) and the allowlist is keyed to that identity. A build job for an untrusted PR gets a different identity with a much shorter list.

Why a proxy and not just firewall rules. A firewall matches IPs, and the IP behind registry.npmjs.org rotates and is shared with thousands of unrelated sites. The proxy resolves the name itself, pins the resolved IP for the connection, and connects to that IP: closing the DNS-rebinding window where the attacker's first answer is public and the second is 169.254.169.254.

Concrete config. Kubernetes NetworkPolicy, default deny:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-egress, namespace: app}
spec:
  podSelector: {}
  policyTypes: [Egress]
  egress:
  - to:
    - namespaceSelector: {matchLabels: {name: egress-proxy}}
    ports: [{protocol: TCP, port: 3128}]
  - to:
    - ipBlock: {cidr: 10.100.0.0/16}   # cluster service CIDR
    ports: [{protocol: TCP, port: 443}]

This only holds if the CNI enforces it: Calico, Cilium, or the AWS VPC CNI with network policy enabled. A cluster on a CNI that ignores NetworkPolicy silently allows everything. Cilium can add toFQDNs enforcement through its DNS proxy, which is a second, independent check on the same allowlist.

Block these ranges at the proxy and the firewall: 169.254.0.0/16 (IMDS at 169.254.169.254), 127.0.0.0/8, 10/8, 172.16/12, 192.168/16, ::1, fc00::/7, fe80::/10, and the cluster CIDR. Normalise the destination before matching: 2130706433, 0177.0.0.1, 0x7f.0.0.1 and ::ffff:127.0.0.1 all reach loopback. Require IMDSv2 (HttpTokens: required) so a stolen SSRF can't read credentials with a bare GET.

Limits. Per request: 5 s connect, 30 s total, 100 MB response body, 10 redirects, and re-evaluate the allowlist on every redirect hop, because a 302 to http://169.254.169.254/latest/meta-data/ is the classic bypass. Per identity: alert when a build job egresses more than 1 GB in an hour. That is the exfiltration signal, not a block.

Build workloads. Untrusted PR code runs on a separate node pool with no production secrets, no cluster credentials, and egress only to the internal artifact proxy (Artifactory or Nexus) plus the VCS. The proxy mirrors npm, PyPI, Maven and Go modules, so the build never talks to registry.npmjs.org directly. That also makes upstream outages survivable: the mirror keeps serving when the registry is down.

Failure modes and detection. SNI-based filtering is not a boundary: Encrypted Client Hello hides the SNI, so the proxy's own resolution is the control, not the SNI string. IPv6 is the usual hole: an IPv4-only allowlist plus a v6 route bypasses everything. Detect with VPC Flow Logs (rejected egress), proxy verdict logs (identity, destination, SNI, bytes, allow/deny), and a periodic diff of the allowlist against observed destinations.

What would change the decision. If the workload is a third-party agent that must reach arbitrary customer endpoints, you can't allowlist: you move to a forward proxy with DLP and per-tenant rate limits. On GCP, Cloud NAT plus Secure Web Proxy replaces the NAT-gateway-plus-Squid shape.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design segmentation to limit lateral movement after endpoint compromise.

Answer

Assume a mid-size company: 200 services, hybrid cloud (AWS EKS, on-prem VMware), identity via Okta, service mesh Istio. Endpoint compromise means a laptop or VM is taken over. Goal: prevent lateral movement.

The core design is zero-trust microsegmentation. Deny all east-west traffic by default. Allow only authenticated, authorized service-to-service communication. Network location (subnet, VLAN) grants no trust. Each workload gets a cryptographic identity (SPIFFE ID, mTLS cert). Policy is enforced at the workload or host level. Concretely: Kubernetes NetworkPolicy for L3/L4, Istio AuthorizationPolicy for L7 identity. For non-Kubernetes, host firewalls with SPIFFE. Management plane (K8s API, CI/CD, backup) sits on a separate network with a separate identity provider and MFA. Data stores only accept specific service identities on specific ports. Endpoint controls (EDR) and application authorization remain necessary; segmentation is not a substitute.

Why identity-bound rules stop pivots: an attacker on a compromised endpoint can steal credentials, but a short-lived mTLS cert bound to that workload cannot be used from another host. Network-based rules (IP/port) can be bypassed if the attacker moves to a host with broader firewall rules. Identity-based rules enforce that only service A can talk to service B, regardless of IP. Control-plane compromise is different: if the attacker gets K8s API access, they can change policies. So the control plane needs separate strong auth (hardware keys, MFA) and audit logging.

Trade-offs: identity-based segmentation adds latency. mTLS handshake adds ~1-2 ms per connection; policy evaluation adds ~0.1 ms. It requires a PKI and service mesh, which is operational overhead. When not worth it: a small static environment with fewer than 10 services and no regulatory requirement. Network segmentation with VLANs and firewalls is simpler there. Deciding criteria: number of services, rate of change, threat model (credential theft vs network scanning), compliance (PCI DSS requires segmentation).

Failure modes:

  • Policy misconfiguration: deny-all breaks legitimate traffic. Symptom: service error rate spikes, 503s. Detection: alerts on policy denies, service mesh metrics. Cost: outage until the rule is fixed.
  • Identity compromise: attacker steals a service's mTLS cert from a compromised pod. Symptom: that service makes unexpected calls. Detection: anomaly detection on the service graph, unexpected egress. Mitigation: short-lived certs (e.g., 1 hour), rotation, least privilege.
  • Control plane compromise: attacker modifies NetworkPolicy to allow all. Symptom: audit log shows a policy change from an unusual IP. Detection: audit logs, immutable infrastructure. Mitigation: separate admin plane, MFA, GitOps with review.
  • DNS/proxy bypass: attacker uses DNS tunneling to reach internal services. Symptom: unusual DNS queries to internal domains. Detection: DNS logs, proxy logs. Mitigation: restrict DNS to internal resolver, inspect proxy.
  • Policy outage: policy engine fails. If fail-open, lateral movement is possible. Detection: health checks. Design: fail-closed for high-security zones, fail-open for low. Trade-off: fail-closed causes outage.
  • Emergency access: break-glass account used. Symptom: audit log shows break-glass. Detection: alert on use. Mitigation: time-bound, monitored.

Artefacts. Table comparing approaches:

AspectNetwork-based (VLAN/Firewall)Identity-based (mTLS/SPIFFE)
Trust anchorIP subnetCryptographic identity
Pivot resistanceLow (IP spoofing, move to trusted host)High (need private key)
Operational costLowHigh (PKI, mesh)
Latency<0.1 ms1-2 ms per connection
Best forStatic, few servicesDynamic, many services

Code: Kubernetes NetworkPolicy deny-all, then allow app to DB.

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-app-to-db
spec:
  podSelector:
    matchLabels:
      app: myapp
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: db
    ports:
    - protocol: TCP
      port: 5432

For L7 identity, use Istio AuthorizationPolicy with principals.

Trace: Attacker compromises a laptop, tries SSH to DB. Network policy denies. Attacker uses a stolen service account token to call the payment service. mTLS requires a client cert; the token alone is insufficient. Attacker tries the K8s API. The API server requires MFA and is on a separate network. Trace ends.

Arithmetic: without segmentation, a compromised endpoint can reach 1000 hosts. With segmentation, it can reach 5. Blast radius reduced by 99.5%. (Hypothetical figures.)

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Detect and respond to lateral movement using network evidence.

Answer

Assume you have east-west network telemetry (Zeek, Suricata, VPC flow logs), identity logs (AD Kerberos, LDAP), and endpoint telemetry (Sysmon, EDR). The core answer: lateral movement is detected by comparing observed internal connections against a baseline of expected communication derived from asset inventory, service dependency maps, and policy. You score deviations, triage to confirm effective identity and path, and contain while preserving evidence.

Why baselining works: lateral movement violates the normal communication matrix. A workstation should not initiate SMB (445) to another workstation; only to file servers. A server should not initiate RDP (3389) to workstations. Build a graph of allowed edges from CMDB. Then alert on new edges, especially on management protocols. Example threshold: a host initiating connections to >5 new internal hosts on ports 445, 3389, 5985, 22 within 10 minutes. This is a hypothetical threshold; tune to your environment.

Trade-offs: Network-only vs identity+endpoint. Network-only is blind to encrypted SMB3 and RDP TLS, and cannot see the user. Identity-only misses host-to-host scanning. Endpoint-only misses network path. Combine. Containment vs evidence: isolating a host kills volatile memory and network connections. Deciding criteria: if host is a domain controller or has EDR live response, capture memory first. When not to use: don't rely solely on NetFlow for lateral movement; it lacks payload and user context. Don't block all east-west traffic.

Failure modes: 1) Vulnerability scanners: a scanner hits many hosts on many ports. Detection: correlate with known scanner IPs and schedules. Cost: alert fatigue. 2) Encrypted management: attacker uses WinRM over HTTPS (5986) with valid credentials. Network sees TLS to 5986. Detection: endpoint process telemetry (Sysmon Event ID 1 for process creation, 3 for network connection). 3) Credential-based lateral movement: stolen Kerberos ticket accesses file share. Network sees normal SMB. Detection: baseline user-to-host access; alert on first-seen user-host pair. 4) DNS tunneling: many TXT queries to a domain. Detection: entropy of subdomains, query volume. Example: 1000 DNS queries in 5 minutes to a single domain with high entropy subdomains.

Artefacts: Table of signals and weights.

| Signal | Example weight | Why | | New internal destination on management port (445, 3389, 5985, 22) | +5 | Lateral movement often uses these | | Destination not in baseline peers for source | +3 | Violates communication matrix | | Authentication failure | +2 | Credential guessing or spraying | | Large outbound, small inbound | +4 | Data staging/exfil | | User not in baseline users for source | +4 | Compromised account |

Code snippet (Python 3.11):

Python
def score_flow(flow, baseline_peers, baseline_users):
    score = 0
    if flow["dst_port"] in {445, 3389, 5985, 5986, 22, 135}:
        score += 5
    if flow["dst_ip"] not in baseline_peers.get(flow["src_ip"], set()):
        score += 3
    if flow["auth_result"] == "failure":
        score += 2
    if flow["bytes_out"] > 1_000_000 and flow["bytes_in"] < 10_000:
        score += 4
    if flow["user"] not in baseline_users.get(flow["src_ip"], set()):
        score += 4
    return score

flow = {
    "src_ip": "10.0.1.5",
    "dst_ip": "10.0.2.10",
    "dst_port": 445,
    "user": "alice",
    "auth_result": "success",
    "bytes_out": 5000,
    "bytes_in": 2000,
}
baseline_peers = {"10.0.1.5": {"10.0.2.20", "10.0.2.30"}}
baseline_users = {"10.0.1.5": {"bob"}}
print(score_flow(flow, baseline_peers, baseline_users))  # 12

Trace: port 445 -> +5; dst 10.0.2.10 not in {10.0.2.20, 10.0.2.30} -> +3; auth success -> 0; bytes_out 5000 not >1M -> 0; user alice not in {bob} -> +4. Total 12. If threshold is 10, alert.

Response: Triage: identify effective identity (who really is alice? Is it a service account?), credential (Kerberos ticket, NTLM hash), device (source host, MAC, EDR agent), path (which hosts were touched), resources (file shares, databases), time window. Containment: revoke Kerberos tickets (klist purge, reset krbtgt twice if golden ticket), isolate host via EDR network containment, block flows at firewall. Preserve volatile evidence: memory capture, netstat, logged-on users, before isolation if possible. Hunt for variants: check other hosts for same user, same destination, same time. Rotate exposed credentials. Restore clean systems. Reconcile data/actions. Notify by impact. Convert path into policy, detection, exercise.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Contain a compromised workload without causing a wider outage.

Answer

What I'd say first

Before touching anything: is this one workload or a fleet? What identity does it hold, and what can that identity reach? I'd assume a single Kubernetes pod with an attached cloud IAM role, running in a shared cluster and account, and that I have control-plane access plus a forensic sink. If it's a VM, the same order holds with different levers.

The answer is an order, not a checklist: freeze the identity, cut network reachability to a known-good set, preserve volatile state, then stop new scheduling from the suspect artifact. Identity first because it's the fastest reversible lever and the only one that stops damage outside the network segment: a pod that already fetched STS credentials can call cloud APIs from anywhere for the token's lifetime.

Why that order

Killing the pod first is the instinct and it's wrong twice. It destroys memory-resident evidence (injected shellcode, in-memory credentials, established C2 sockets) and it doesn't revoke the IAM role. Role sessions default to one hour (DurationSeconds=3600) and can be configured up to 12 hours, so a killed pod's credentials remain live. The mechanism you're exploiting is that containment has to sever the credential, not just the process.

Levers, with what they actually do

LeverMechanismTime to effectReversible
IAM inline deny conditioned on aws:TokenIssueTimeExisting STS sessions fail at next API callnext callyes, detach policy
NetworkPolicy default-deny egress on the workload's labelCNI drops packetsseconds, CNI-dependentyes, delete policy
Istio AuthorizationPolicy with action: DENYEnvoy rejects at the sidecaron config pushyes
kubectl cordon the nodeScheduler stops placing new podsimmediateyes, uncordon
Delete the podProcess and memory goneimmediateno

The IAM deny is the one people miss. Attaching a policy that denies * on * when aws:TokenIssueTime is older than the incident start invalidates sessions already issued, which a role-permission change alone does not.

The trade-off

Aggressive isolation breaks legitimate dependencies. A payment service that can't reach its database fails its liveness probe, the kubelet restarts it, and the replacement may land on a node where your label selector doesn't apply: re-establishing the compromise somewhere you're not watching. So scope the deny to the workload's identity (label selector or service account), and allow only the forensic collector and control paths. Aggressive deny-all is right when the workload's dependencies are unknown or the blast radius is already spreading; it's wrong when you've mapped the dependency graph and can allow-list it.

Failure modes and how you see them

  • Deny-all egress kills the liveness probe, kubelet restarts the pod, and the new pod bypasses your label. Detect: restart count climbing, new pod UID. Fix: patch the Deployment to zero replicas or add the label to the template.
  • You revoke the role but not the STS session; the attacker keeps calling APIs. Detect: CloudTrail events from that role after your revocation timestamp. Fix: the TokenIssueTime deny above.
  • You delete the node and lose the container filesystem. Detect: nothing left to image. Fix: cordon, snapshot the node disk, then drain.

Handoff

Once contained, find the callers and downstream resources from flow logs and application audit, rotate the exposed trust, rebuild from a verified source, and restore behind a canary. Remove the temporary blocks deliberately: a deny-all left in place becomes next quarter's outage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design a site-to-site IPsec VPN between two organizations.

Answer

What I'd say first (0:00–1:30)

Two organizations, two independently-administered firewalls, and the job is to move specific traffic between named subnets, not to merge the networks. My default is a route-based IKEv2 tunnel with certificate authentication, narrow traffic selectors, and two tunnels for redundancy. Before any config I'd confirm three things: the exact source/destination subnets and ports in both directions, whether the RFC 1918 ranges overlap (if they do we need policy NAT, which is not the same thing as NAT-T), and who owns each end plus the change window.

The proposal I'd bring

ParameterValueWhy
IKE versionIKEv2 (RFC 7296)IKEv1 aggressive-mode PSK is offline-crackable; IKEv2 has built-in DPD, MOBIKE, cleaner rekey
EncryptionAES-GCM-256AEAD, one pass, no separate HMAC; AES-CBC-256 + HMAC-SHA-256 only if a peer lacks GCM
PRFHMAC-SHA-256GCM already covers integrity
DH group19 (256-bit ECP), fall back to 14 (2048-bit MODP)group 2 (1024-bit MODP) is not acceptable
Peer authX.509 certs from a private CA; a ≥32-char random PSK only if certs aren't feasible
IKE SA lifetime86400 s (Cisco default) / 14400 s (strongSwan default)rekey before expiry
CHILD_SA lifetime3600 s or 28800 s
PFSDH group 19 on each CHILD_SA rekey
Anti-replayESP window, 64 packets default (RFC 4303), 1024 on Cisco
DPD10 s interval, 3 retries (Cisco default)

Why route-based

Policy-based (crypto ACL / SPD) ties the tunnel to an ACL match. You can't run OSPF or BGP over it cleanly, and an any-to-any ACL makes you a transit for the partner's traffic to third parties: that's the transitive-trust trap. Route-based (Cisco VTI, Palo Alto route-based, strongSwan with if_id) gives you a real interface, so you can run BGP for failover and write normal firewall rules on it. Use policy-based only when a peer supports nothing else.

MTU: the arithmetic

ESP overhead for AES-GCM-256 over IPv4: 20 (outer IP) + 8 (ESP header) + 8 (IV) + 2 (pad/pad-len/next-hdr) + 16 (ICV) ≈ 54 bytes. On a 1500-byte path that leaves a 1446-byte tunnel MTU. Clamp TCP MSS to 1360 on both ends and let ICMP type 3 code 4 through, or you get the classic blackhole: small pings pass, TLS handshakes hang. AES-CBC-256 + HMAC-SHA-256 is worse: about 78 bytes.

Failure modes and how I'd catch them

  • Proposal mismatch: IKE_SA never comes up, logs show NO_PROPOSAL_CHOSEN. Fix by diffing both sides' proposals, not by widening to everything.
  • Auth failure: AUTHENTICATION_FAILED. Usually cert clock skew or a PSK typo.
  • Asymmetric routing: return traffic leaves via the internet instead of the tunnel. The far-side stateful firewall sees a SYN with no matching session and drops it; you see one-way traffic and denied logs. Fix with route preference or BGP local-pref, not by disabling the firewall.
  • MTU blackhole: as above.
  • Rekey failure: tunnel drops every lifetime interval; watch for IKE_SA rekey failed. Often a peer without PFS or a mismatched lifetime.
  • DPD false positive: flapping tunnel under load; check underlay packet loss before blaming IPsec.

Lifecycle

Key compromise → revoke the cert (CRL/OCSP) and tear the SA. Partner offboarding → remove the peer config and routes, then verify nothing still matches. Emergency disable → one ACL/route kill switch both sides can hit. Rollback → keep the previous config staged.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Choose between full-tunnel and split-tunnel remote access.

Answer

Assumptions: managed laptops with EDR and full-disk encryption, a workforce that lives in Microsoft 365 plus a few SaaS apps, and roughly 40 internal services behind a single concentrator pair. Under those, default to split tunnel with a curated exclusion list, and reserve full tunnel for unmanaged/BYOD devices and the small group that touches regulated data.

The 60-second answer. Split tunnel wins because the dominant traffic is SaaS that sits closer to the user than your gateway does. A Berlin engineer on a us-east-1 concentrator has ~90 ms RTT to the gateway. Full tunnel sends their Teams media Berlin → Virginia → Frankfurt, adding roughly 180 ms round trip: past the point where calls degrade. Split tunnel keeps that on the local path and pushes only 10.0.0.0/8 plus the internal DNS suffix through the tunnel.

Why hairpinning costs what it does. The gateway is a chokepoint on the data path, not just the control path. Every packet crosses it twice (in and out), so its throughput ceiling is the sum of all user traffic, and its latency is added to every flow. A pair of 5 Gbps concentrators serving 5,000 users at 2 Mbps average is at 10 Gbps: saturated before any burst. Split tunnel removes SaaS from that sum entirely.

Why DNS and routes get ambiguous. Split tunnel means two resolvers are live at once. Without a rule, the OS asks the local resolver (192.168.1.1 at home) for git.corp.internal, gets NXDOMAIN, and the user sees a broken app rather than a broken VPN. On Windows the fix is an NRPT rule that sends only *.corp.internal to the corporate resolver; everything else stays local. Route ambiguity is the same problem one layer down: some clients install 0.0.0.0/1 and 128.0.0.0/1 instead of replacing the default route, so the tunnel wins for most destinations but the local default still exists, which is exactly how traffic leaks when a route is missing.

When to flip to full tunnel. Unmanaged or contractor devices, where you cannot trust the local network or enforce EDR; a small, sensitive resource set where the gateway cost is trivial; and jurisdictions where you must keep egress visible. If you want to avoid the routing question altogether, a ZTNA broker (Zscaler ZPA, Cloudflare Access) replaces the tunnel with per-app connections: different operational model, same decision about who reaches what.

Failure modes and how you catch them.

  • IPv6 leak. The client pushes only IPv4 routes; the endpoint still has native IPv6 and reaches dual-stacked corp services directly. Detect: on a connected client, curl -6 https://ifconfig.co should return the gateway's address, and ip -6 route should show the default via the tunnel. Fix: push ::/0 or disable IPv6 on the adapter.
  • Captive portal. Split tunnel captures DNS before the portal is passed, so the login page never loads. Detect: probe a known 204 endpoint before bringing the tunnel up; if it fails, stay down.
  • WireGuard revocation. There is no CRL or OCSP: a peer's public key stays valid until it is removed from every peer's config. Detect: reconcile the peer list against IdP leavers weekly.
  • Gateway saturation under full tunnel. Detect: p99 tunnel-establish latency and concurrent sessions against the licensed ceiling.

Exclusion list, concretely.

DestinationWhy it is excluded
Microsoft 365 endpoints, "Optimize" categoryPulled from the endpoint web service at endpoints.office.com; ranges rotate, so fetch them rather than hardcoding
Teams media, UDP 3478–3481Real-time media; hairpin adds jitter
Zoom media rangesPublished in Zoom's support docs; same reason

What would change the decision: a regulatory requirement that all egress be inspected, or a move to unmanaged devices, flips the default to full tunnel. At which point size the concentrators for peak aggregate, not average.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Govern enterprise TLS inspection safely.

Answer

What I'd say first

Assumptions I'd state up front: endpoints are managed, so I can install and remove a root CA on them; the proxy sits on the egress path for everything; and someone can name the control decryption actually buys. DLP content matching on outbound uploads, malware payload inspection inside TLS, or a written compliance mandate. If that last one is missing, my recommendation is don't inspect. That's the governing constraint: RFC 7258 (BCP 188) classifies pervasive monitoring as an attack, so interception is the exception. I'd size the bypass list before rollout, not after the first broken app.

Trust root and keys

One offline root, not one per site. Root key offline in an HSM; a 1-2 year intermediate signs the leaves; leaves under 90 days so rotation is routine. Publicly trusted TLS certs cap at 398 days under the CA/B Forum baseline, enforced by Apple and Chrome: private roots aren't bound by that, but short leaves keep the rotation runbook boring. Access to the signing key is dual-controlled and logged; if the HSM goes down you can't issue, so keep a documented break-glass.

Distribution is MDM. On iOS and macOS the pushed root payload is trusted automatically on supervised devices. Android is where the whole bypass list gets decided: since API 24, any app targeting 24+ trusts only system CAs unless its own network security config opts into <certificates src="user"/>. Third-party apps write that config themselves, so your root is invisible to them, which is why you cannot inspect most mobile apps even with perfect MDM.

Bypass classes, and how you verify each

classmechanism that forces the bypassverification
third-party mobile appsapp trust store, not OS store; pins via Android network security config or OkHttp CertificatePinnerclient sends TLS alert 48 (unknown_ca) right after the server cert
Firefox, Java workloadsown NSS store and cacerts keystoreset security.enterprise_roots.enabled; keytool-import into cacerts; test both pre-rollout
QUIC / HTTP3TLS 1.3 inside QUIC; classic proxies terminate TCP/TLSset Chrome policy QuicAllowed=false, or log the flow as uninspected
ECH (Chrome 117+)ClientHello encrypted, SNI goneunclassifiable flows: you find out when SNI-policy stops firing
mTLS, LDAPS, database TLSproxy can't present the client cert upstreampass through, or re-sign with a proxy-issued client cert

Sizing (hypothetical numbers, to show the method)

20,000 endpoints * 15 concurrent TLS flows = 300,000 live flows; at ~32 KB of flow state each that's 9.6 GB of RAM. Mean flow life 30 s gives 10,000 new handshakes/s. Take your own figure from openssl speed rsa2048 or a handshake load test: at roughly 1,500 full ECDHE handshakes/s/core you need ~7 cores for handshakes alone, before bulk crypto. So a pair of 16-core boxes at 50% headroom, and a decided answer for what traffic does when they fail.

Failure behaviour

Fail-closed on inspection turns a proxy bug into a company-wide outage; fail-open silently evaporates policy. Split it: keep category blocking on a path that doesn't decrypt (DNS filtering, endpoint agent), and let inspection fail open with an alert when inspected-session count drops more than ~20% over 5 minutes. A per-SNI spike in alert-48 means an app shipped a new pin.

When not to inspect

Don't install a root on devices you can't later remove (BYOD, personal phones). Don't inspect where no control depends on plaintext: DNS filtering plus EDR captures most malware value at a fraction of the trust cost. Don't inspect regulated or privileged endpoints where the DPIA (GDPR Art. 35) or works-council co-determination (Betriebsverfassungsgesetz 87(1)(6)) says no. And don't inspect pinned business-critical apps you don't control: the outage costs more than the visibility buys.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design secure enterprise DNS resolution and monitoring.

Answer

Assumptions I'd state first: managed endpoints on a corporate image, hybrid (AD on-prem plus cloud VPCs), one IdP, and a requirement to keep resolving when the primary resolver site is down. If any of those is false (BYOD, no IdP) the design changes, so I'd confirm before drawing anything.

Core answer. Resolution is a three-plane problem: path, trust, telemetry. Path: managed clients get resolvers via DHCP option 6 or cloud DHCP option sets, and the network drops outbound UDP/TCP 53 to anything but the approved resolver IPs. Trust: the resolver validates DNSSEC and the client authenticates to it. Telemetry: structured query logs feed detection.

Path. Run Unbound or BIND 9 as the internal recursive resolver on 10.0.0.53, with access-control refusing everything outside corporate ranges. Block direct 53 at the egress firewall and log the attempts: that log is your policy-bypass detector. DoT (RFC 7858, port 853) and DoH (RFC 8484, port 443) are allowed only to the approved resolver; unmanaged DoH endpoints are blocked by name and IP, because a browser's built-in DoH silently bypasses your split horizon.

Trust. DNSSEC validation and DoT/DoH solve different problems, and conflating them is the common mistake.

MechanismProtectsDoes not protectDeciding criterion
DNSSEC validationIntegrity and authenticity of signed RRsets, chain from the root KSKUnsigned zones, confidentiality, whether the domain is maliciousUse when you must detect forged answers; fails closed with SERVFAIL
DoT/DoH to your resolverConfidentiality and integrity of the client→resolver hopAnything past the resolver; domain reputationUse on untrusted networks, e.g. roaming laptops
RPZ (response policy zones)Blocking known-bad namesNovel domainsFast blocklist layer, never the only control

Monitoring. Ship queries via dnstap into a pipeline, not flat querylog files. Minimize: hash or truncate client IP after 24h, keep full fidelity 7 days, aggregate 12 months (PCI DSS 10.5.1 wants 12 months with 3 immediately available). Detection signals with thresholds:

  • Tunneling: Shannon entropy per label > 3.5 bits/char (random hex is 4.0, base32 5.0; api or us-east-1 sit near 2–3), label length > 20, and unique-subdomain ratio > 0.9 per client over 5 minutes. Iodine and dnscat2 both show this shape because every query carries a fresh encoded chunk and never hits cache.
  • New domains: first-seen domain resolved by more than N clients in an hour.
  • Private/metadata answers: any A record in 169.254.169.254/32 or RFC1918 returned for an external name. Rebinding or hijack.
  • NXDOMAIN ratio per client above 50% with a high query rate.

Failure modes and how you'd see them.

  • Cache poisoning: attacker wins the 16-bit transaction-ID plus source-port race. Detect via DNSSEC (SERVFAIL spike) and alerts on anomalously low TTLs. Mitigate with port randomization, 0x20 encoding, DNSSEC.
  • Stale/negative caching: a bad NXDOMAIN sticks for the SOA minimum, capped at 3600s in Unbound (cache-max-negative-ttl) and 10800s in BIND (max-ncache-ttl). Cost: a decommissioned hostname stays unresolvable up to 3 hours after you fix the zone.
  • Rebinding: attacker sets TTL 0 and flips the A record to 127.0.0.1. Alert on TTL 0 answers for external names; pin and validate Host headers.
  • Bootstrap: the resolver needs root hints or a forwarder before DNSSEC works; if the forwarder is DoT-only and the cert bundle is stale, everything SERVFAILs. Test by killing the forwarder in staging.
  • Outage: two resolver sites, clients get both, health-checked VIP. Test by draining one.

Config artefact (Unbound 1.12+):

server:
  interface: 10.0.0.53
  access-control: 10.0.0.0/8 allow
  access-control: 0.0.0.0/0 refuse
  qname-minimisation: yes
  harden-dnssec-stripped: yes
  harden-below-nxdomain: yes
  edns-buffer-size: 1232
  cache-max-negative-ttl: 3600

1232 is the DNS flag day 2020 recommendation to avoid IP fragmentation; Unbound defaults to it since 1.12.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design privacy-conscious network telemetry and flow logging.

Answer

Clarify, then answer. I'd ask what the driver is (incident response, compliance, or capacity) and assume all three, with one hard constraint: no raw payload and no full URLs in the default pipeline. That gives the shape of the design. Log flow metadata at the enforcement point, add host-level flow events where the network can't see (encrypted east-west traffic), normalize everything into one schema with a shared flow ID, and treat payload capture as a separate exception path with its own approval and its own retention clock.

What I log, and why.

FieldWhy it's therePrivacy handling
5-tuple: src/dst IP, ports, protocolthe join key for everything elsekeep; IPs are treated as personal data under GDPR, so retention-bounded
start/end timestampsordering, duration, session reconstructionabsolute UTC from a synced clock
bytes, packetscapacity planning, exfil volumekeep
action (allow/deny) + rule ID + policy versionthe decision evidencekeep, and never sample it away
enforcement point IDwhich device made the callkeep
workload identity (namespace/service, or user)attributionkeep where trustworthy; don't infer it
trace/request IDcorrelate with app logskeep when the app propagates it
DNS name, SNI, full URLattribution, exfil detectionoff by default, opt-in per namespace
payloadcontentnever in the default pipeline

Why sampling must not touch denies. Sampling happens at the exporter, before the flow record exists. A 1-in-1000 sample of a 200-packet scan burst yields an expected 0.2 records, so the probability of seeing nothing is e^-0.2 ≈ 82%. You lose exactly the event you most need. So sample the high-volume allow traffic, and either disable sampling on deny rules or re-sample at the collector, where you can keep every deny plus the high-risk set: new destinations, unusual ports, first-seen pairs.

Why clock skew breaks the whole thing. NetFlow v5 timestamps are relative to device uptime: absolute time is unix_secs − (sysUpTime − First)/1000. A reboot mid-export-interval wraps sysUpTime and the computed time is garbage. Even with NTP, a host 30 s off makes a deny at the load balancer look like it happened after the pod's connection, so your causal chain runs backwards. Detect it by comparing exporter clock to collector clock on every export and alerting past roughly 1 s of skew; never sort a merged timeline on a single device's clock.

Trade-offs worth naming. DNS names are the most useful and least durable field: CDN and cloud load-balancer addresses change constantly, so a name resolved today may not describe that address tomorrow. Capture the name at flow time if you need it; don't rely on reverse lookup later. Pseudonymizing IPs with HMAC-SHA256 keeps records joinable within a key epoch but breaks the join across rotation, so rotate on a schedule you can explain to an investigator. Retention pulls two ways: hot 7–30 days searchable, warm 90 days, cold 12 months. PCI DSS wants 12 months with the most recent 3 immediately available; GDPR wants deletion once the purpose ends. Decide per data class, not globally.

Failure modes and how they show up. Log injection: a DNS name or user-agent containing newlines can forge records. Strip control characters before writing. Cardinality blowup: full URLs as metric labels will wreck a Prometheus or Loki index, so keep them in the log store, not the metric. Silent gaps: exporters drop records under load and emit nothing, so monitor per-exporter record rate and alert on a flat line, not just on error counters. NAT ambiguity: log both pre- and post-NAT addresses or you cannot attribute a session to a workload. Finally, run a drill: pick a known incident, replay the query, and confirm you can answer who talked to whom and whether it was allowed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design DDoS resilience for network security enforcement points.

Answer

Assumptions I'd state first: the enforcement points are inline (perimeter firewall, TLS-inspection proxy, VPN concentrator, WAF) plus a control plane that pushes policy and authenticates admins. Public DNS and HTTP can sit behind anycast; VPN and east-west inspection cannot. Budget is real, so "scale out" has a ceiling.

Core answer: absorb what you can upstream, keep per-packet state off the box for as long as possible, and make the state that remains cheap to exhaust and cheap to recover. Concretely: anycast or a scrubbing contract in front of DNS and public HTTP; stateless ACLs and SYN-cookie handling before conntrack; per-source and global rate limits on the expensive paths (TLS handshake, auth, policy lookup); control plane on its own interface and VRF; and a degraded mode that fails closed on identity while shedding non-essential inspection.

Why stateless must precede stateful. The conntrack table is a fixed-size hash sized from RAM at boot. An established TCP entry lives for nf_conntrack_tcp_timeout_established, default 432000 s: five days. So 200k hosts each holding five idle connections pins a million entries, the table fills, and from then on every new flow is dropped while existing ones keep working. That reads as a partial outage, not an attack. Detection is nf_conntrack_count against nf_conntrack_max, plus the kernel line nf_conntrack: table full, dropping packet. A stateless rule that drops obviously-spoofed sources before they reach conntrack costs nothing and never fills.

Trade-off: upstream vs on-box.

LayerStopsCostLatency added
Anycast (DNS, HTTP)volumetric L3/L4bundled with CDN~0 in-region
Scrubbing contractvolumetric beyond uplinkShield Advanced $3,000/mo, 1-yr commitsingle-digit ms in-region, tens if hairpinned
On-box stateless ACLspoofed / known-bad sourcesCPU onlynone
On-box conntrack + rate limitstate exhaustiontable entriesnone

Decision rule: if the attack exceeds your uplink, only upstream absorption works. On-box filtering just drops packets you already paid to receive. Anycast anything that tolerates it; scrubbing contract for the rest; on-box filtering only for what's left after both.

Amplification is the cheap attack. Memcached stats reflection hit 1.35 Tbps at GitHub in 2018, roughly 51,000x. NTP monlist is ~556x, SSDP ~30x. So: no UDP service reachable from the internet except DNS, and DNS with RFC 8482 minimal ANY plus response-rate limiting.

Failure modes and how I'd catch them:

  • SYN backlog overflow: clients time out, the server logs nothing. Signal: netstat -s | grep -i "SYNs to LISTEN" climbing.
  • TLS handshake CPU saturation: a TCP-connect health check still passes, so the load balancer keeps sending. Signal: handshake p99 and ssl_handshake error rate; fix by making the health check do a real handshake.
  • Control plane starved by the data plane: you can't push the mitigation rule. Signal: policy-push latency. Keep it on a separate NIC and VRF.
  • Autoscale cost blowout: a budget alarm, not a dashboard.

Degraded mode. Shed non-essential inspection (stop deep content inspection, keep L3/L4 policy), never silently fail open on identity. If the auth service is down, VPN fails closed and you say so.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Define safe network-policy behavior during identity or policy-service outage.

Answer

Assumptions and core answer

I'll assume a PDP/PEP split: a remote decision service (OPA, an Envoy ext_authz service, or the IdP itself) and enforcement points at the edge and in sidecars. The question is what the PEP does when the PDP is unreachable.

Default: fail closed for anything that mints new authority; fail open only for a pre-approved, time-bounded set of flows served from a local decision cache. Client-supplied identity or role claims are never a substitute for a PDP decision.

Envoy already encodes the safe default. The HTTP ext_authz filter has failure_mode_allow: false, and on error returns status_on_error, 403 by default. An unreachable PDP therefore denies new sessions with no extra work. The design effort goes into the exception path and into bounding how long a stale allow can live.

What the exception path looks like

YAML
http_filters:
- name: envoy.filters.http.ext_authz
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
    failure_mode_allow: false
    status_on_error: { code: 403 }
    http_service:
      server_uri:
        uri: http://pdp.internal:9191
        cluster: pdp
        timeout: 250ms

A cached allow is only usable if it carries: verified principal (SPIFFE ID or subject), resource + action, the policy bundle version it was decided under, an expiry, and the revocation epoch. Cache TTL is the blast radius of a revocation that lands during the outage. 60s is a defensible starting point for user data-plane reads; admin writes get no cache at all.

Flow classes

FlowOn PDP outageBound
New session, admin/control-plane writeDenynone
New session, data-plane read already granted to this principalAllow from cache60s TTL
Established mTLS session, already authorizedContinueuntil SVID expiry
Break-glass operator actionAllow, two-person approval15 min, auto-revoke, audited

The third row is the one people forget: an already-authenticated mTLS session keeps working because the certificate is still valid. SPIRE's default X.509 SVID TTL is 1h, so an identity-service outage longer than that stops new workloads from getting identity at all. That TTL, not the policy cache, is often the real outage budget.

Trace: PDP down, one request

  1. Client presents mTLS cert, SPIFFE ID spiffe://corp/ns/payments/sa/api, valid for 42 more minutes.
  2. PEP calls pdp.internal:9191, 250ms timeout.
  3. Connection refused in 3ms → ext_authz returns 403 → request denied.
  4. A second request for the same (principal, method, path) hits the local cache, decision age 12s < 60s TTL → allowed.
  5. PDP recovers; cache entries drain within 60s. OPA bundle polling defaults to min_delay_seconds: 60, max_delay_seconds: 120, so PEPs don't all refetch in the same instant.

Failure modes and detection

  • Stale allow after revocation. Bounded by cache TTL. Detect by alerting when decision_age_p99 exceeds the TTL, or when a revocation event timestamp is older than the oldest live cache entry.
  • SVID expiry mid-outage. New pods can't authenticate. Alert on SVID time-to-expiry below 15 min across the fleet.
  • Clock skew. JWT exp/nbf checks fail if skew exceeds tolerance. Track NTP offset per node; alert above 30s.
  • Recovery stampede. Jittered bundle polling (above) plus a rate limit on PDP reconnects.
  • Cache poisoning. Cache key is the verified principal only, never a header the client can set.

Alternatives

L3/L4 policy compiled locally, Kubernetes NetworkPolicy enforced by Cilium's eBPF datapath, keeps working through a control-plane outage because there is no per-request PDP call. Use it as the floor, and put identity-aware policy on top.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Troubleshoot a legitimate request blocked after a network-policy change.

Answer

Assume a Kubernetes cluster where NetworkPolicy is enforced by Cilium or Calico, and the request worked before the last policy apply. Treat the policy change as the cause until you prove otherwise. In the first two minutes, say this: find the exact drop point, compare the effective policy to the intended selectors and ports, then restore with a scoped exception or rollback. Do not start with a broad allow-all.

A concrete example. Namespace shop has checkout-7d9c at 10.244.3.17 calling payments.shop.svc.cluster.local:8443. The new policy is:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: payments-ingress
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: payments
  policyTypes: ["Ingress"]
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: checkout
    ports:
    - protocol: TCP
      port: 8443

This allows only pods labeled app=checkout in the same namespace. If the checkout pod is labeled app=checkout-api, the request is blocked. Trace it the way the packet moves:

  1. checkout-7d9c resolves payments.shop.svc.cluster.local to ClusterIP 10.96.12.34.
  2. kube-proxy or the eBPF dataplane DNATs that to payments-5f6b at 10.244.5.22:8443.
  3. At the destination, the policy engine evaluates ingress. The source identity is app=checkout-api; the policy requires app=checkout. No allow rule matches, so the verdict is DROP.
  4. With Cilium, hubble observe --namespace shop --to-pod payments-5f6b --verdict DROPPED shows Policy denied and ingress with no matching rule. cilium monitor --type policy-verdict shows policy-verdict: ... ingress ... verdict DROP.

Without Hubble, kubectl exec checkout-7d9c -- nc -vz -w 2 payments.shop.svc.cluster.local 8443 times out, and kubectl get networkpolicy -n shop -o yaml shows the selector mismatch.

Now the failure modes that actually bite, with detection and cost:

FailureDetectionOperational cost
Label or identity mismatchkubectl get pod -n shop --show-labels; compare to the policy podSelector5 minutes; fix the label or the policy selector
DNS egress blockedkubectl exec checkout-7d9c -- nslookup payments.shop.svc.cluster.local; check egress to kube-system/kube-dns on UDP/TCP 53Fails fast; add a scoped egress rule to kube-dns
Rule order or shadowingCalico: calicoctl get globalnetworkpolicy -o yaml; check order and tier. Kubernetes NetworkPolicy is additive, so order does not exist there.10 minutes; reorder or merge policies
Conntrack or NAT state`conntrack -Lgrep 10.244.5.22; ss -tnp` on the client
Health check blockedkubectl get endpoints payments; kubectl describe pod payments-5f6bCascading; allow the kubelet or probe source

If the label is wrong, fix the label or the policy selector. If you need immediate restore, add a scoped ingress rule from app=checkout-api to app=payments on TCP 8443, with an owner and an expiry annotation. Do not add 0.0.0.0/0 or namespaceSelector: {}. Roll back the policy if the change was not reviewed. Verify with a positive test from checkout and a negative test from a pod that should not reach payments. Then remove the exception and re-run the canary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Operate network policy as code safely.

Answer

Assume a Kubernetes cluster whose CNI actually enforces NetworkPolicy (Calico, Cilium or Antrea) with policies in git and applied by a controller. If the CNI doesn't enforce, nothing below matters, so that's the first thing I verify. Given that, "safely" means the change is previewed against real traffic before it can drop a packet, and the live state is reconciled back to git.

The pipeline is author, validate, preview, canary, enforce, reconcile. The part people skip is preview, and it's the part that catches what CI cannot. CI reasons about policy text; it has no idea which flows exist. Staged policies (Calico's StagedGlobalNetworkPolicy, Cilium's policy audit mode) push the new rules into the dataplane, evaluate them against live traffic, and log what would be denied without dropping anything. That is how you find the flow you forgot to model: a node health check, DNS to kube-dns, a metrics scrape from a namespace you don't own.

YAML
apiVersion: projectcalico.org/v3
kind: StagedGlobalNetworkPolicy
metadata:
  name: allow-payments-to-ledger
spec:
  order: 100
  selector: app == 'ledger'
  ingress:
    - action: Allow
      source:
        selector: app == 'payments'
      destination:
        ports: [5432]

Run it in staged mode for a full traffic cycle, then read the would-be denials:

flowoldnewaction
payments → ledger:5432allowallownone
node healthcheck → ledger:5432allowdenymodel it or widen the rule before enforcing
ledger → kube-dns:53allowallownone

(Figures above are a labelled example, not a measurement.)

Trade-offs. Generate rules when you have many namespaces and a real source of truth, a service graph or ownership metadata, because hand-maintaining hundreds of selectors drifts. Hand-write when the policy is small and stable, or when the generator's abstraction leaks: L7 rules, host firewall, node-level policy. Shadow mode is not free: you run two policy versions and must retain flow logs long enough to cover weekly and monthly jobs, so skip it for a change that only tightens an already-denied path, or in a dev cluster. Canary is worth it when the change widens access; skip it when you're purely narrowing a namespace with no production traffic.

Failure modes and how you see them. A shadowed rule, a broad allow earlier in the chain means a later specific rule never matches, shows up in cilium policy trace or Calico's policy coverage, which names the rule that actually decided. A missing default-deny means a namespace with no policy allows everything; assert every namespace has a default-deny selector. Drift, someone editing live objects, shows as an OutOfSync in Argo CD or a diff between kubectl get netpol -A -o yaml and the rendered manifest. Address-family parity breaks in dual-stack clusters when an IPv4 rule has no IPv6 twin; render both families and diff them.

Rollback has to restore the whole dependency set, not one rule, because policies are additive and removing one can re-open a path another was closing. Emergency changes stay narrow, carry an expiry, and get back-ported to git the same day.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Build an end-to-end test strategy for network security controls.

Answer

The 90-second answer. I'd start by inventorying the enforcement points that actually sit on the path, because the test strategy is only as good as that inventory. On a typical AWS-plus-Kubernetes stack that's security groups (stateful, allow-only rules, default deny inbound and default allow all outbound), NACLs (stateless, lowest rule number wins, implicit deny at the end), the Kubernetes NetworkPolicy layer (a pod with no selecting policy is allow-all; the moment one policy selects it, that direction becomes default-deny), and whatever fronts it: an ALB, a NAT gateway, AWS Network Firewall. Then I derive cases from the flow matrix: identity, source zone, destination, direction, protocol, state, address family, environment. For each cell I assert the allow and the deny, and I assert which enforcement point produced the verdict, not just that the connection failed.

Enforcement pointStatefulDefaultHow I observe it
Security groupyesdeny in, allow all outVPC Flow Logs action=REJECT
NACLnoimplicit deny after last ruleFlow Logs, rule-number order
K8s NetworkPolicydepends on CNIallow-all until a policy selects the podcilium monitor --type drop
Host iptables/nftablesyes, via conntrackvaries by distroiptables -L -v -n counters

Making it concrete. Every test names a tool and an observable. Reachability: nc -vz -w2 host port or curl -sS --max-time 3. DNS: dig +tcp @resolver name to force TCP 53 and catch truncation bugs. State: conntrack -L | grep dport=443, ss -tan state time-wait. Policy: kubectl get networkpolicy -A -o yaml, calicoctl get globalnetworkpolicy -o yaml. Cloud: VPC Flow Logs give action=ACCEPT|REJECT per 5-tuple, the cheapest way to prove a deny happened at the SG or NACL rather than in the app.

A worked trace. Client in zone A (10.0.1.0/24) to a service in zone B (10.0.2.0/24) on TCP 443. The SG on B allows 443 from A's SG ID. Because NACLs are stateless, B's subnet NACL needs inbound 443 from 10.0.1.0/24 and outbound 1024-65535 back to 10.0.1.0/24; A's subnet NACL needs the mirror image. Miss the ephemeral half and the SYN arrives, the SYN-ACK is dropped, and the client just times out: the classic asymmetric-NACL bug. Now the negative: same flow from 10.0.3.0/24, which no rule covers. Expect a silent drop, no RST, because security groups drop rather than reject. If you see a RST or an ICMP port-unreachable, the packet got past the SG and something downstream rejected it: that tells you where to look next.

Failure modes and detection. Conntrack exhaustion: watch nf_conntrack_count against nf_conntrack_max; new connections fail while established ones keep working. Rule-order shadowing: a broad allow above a specific deny. Diff iptables-save or nft list ruleset against the intended policy, and let a property test prove every deny cell still denies. Identity staleness: replay a token one second past exp, or a cert signed by the previous CA, and confirm rejection. Drift: a non-empty terraform plan, or a nightly job reconciling live SG rules against the repo. Control-plane outage: the safe behavior is deny, or an explicitly bounded, risk-approved fallback. Never "permit all internal until policy services recover."

Trade-offs. Controlled tests (a lab or ephemeral VPC, tcpreplay of captured traffic) are cheap, repeatable, and safe in CI. Production synthetic probes catch drift and real-path problems a lab can't, but they cost money, generate real traffic, and can trip DDoS protections. I'd run controlled tests on every policy change and synthetic probes on a schedule, and reserve active scanning for a window with written authorization; running nmap against your own prod without that is how you end up in an incident review.

Property test. For every declared flow, assert reachability; for every zone pair not in the matrix, assert unreachability. In hypothesis or a table-driven pytest, that's a few hundred cases, and it catches the "someone added a 0.0.0.0/0 rule" regression a hand-written list misses.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Plan IPv6 adoption without creating an unmonitored bypass path.

Answer

Assumptions I'd state up front: we're dual-stack during a transition window, not IPv6-only; IPv4 stays until the last segment moves; and success means parity of inventory, identity, policy, DNS and telemetry across families, not "IPv6 is enabled."

The core answer. The bypass isn't IPv6; it's that your control plane is IPv4-shaped. Three gaps open the moment you publish a AAAA record. First, NAT disappears: hosts get global addresses from 2000::/3, so inbound reachability changes without anyone editing a firewall. Second, the rule engines are separate: iptables and ip6tables are distinct chains, and AWS security groups carry IpRanges and Ipv6Ranges as separate lists. Adding a rule to one does nothing for the other. Third, transition tunnels (6to4 (2002::/16, IP protocol 41), Teredo (2001::/32, UDP 3544), ISATAP) encapsulate IPv6 inside IPv4 and walk past v4-only inspection.

Mechanism. Two things decide which path a connection actually takes. RFC 6724's default address-selection table prefers a global IPv6 address when one exists, and Happy Eyeballs (RFC 8305) races both families with a 250 ms head start for IPv6. So a service that "works" over IPv4 silently flips to IPv6 the day AAAA lands: that is the moment the bypass opens, not the day you enable the stack. Second, RFC 8981 temporary addresses rotate the interface identifier, so any rule keyed to a /128 host address expires within hours. Key policy to the /64 or to device identity, and normalize logs on a stable identifier rather than the address.

Trade-offs. Dual-stack costs two rule sets and two telemetry paths but adds no translation state. IPv6-only plus NAT64/DNS64 (well-known prefix 64:ff9b::/96) is one stack to operate, but DNS64 breaks DNSSEC validation for synthesized answers and hardcoded IPv4 literals fail; NAT64 adds a stateful failure domain. 464XLAT keeps legacy clients working at the cost of another translation layer. For a one-week scope, dual-stack with parity checks is the defensible default.

mechanismencapsulationcontrol
6to42002::/16 in IP proto 41block proto 41 egress, alert on hits
Teredo2001::/32 in UDP 3544block UDP 3544 egress, alert on hits
ISATAPIPv6 in IPv4 proto 41block proto 41 egress
NAT64/DNS6464:ff9b::/96permit only at the designated translator

Failure modes and how to detect them.

  • Rogue RA: a host takes a prefix from an unauthorized router and egresses a path you don't monitor. Detect with RA Guard on access ports (RFC 6105) and alert on any RA arriving on a non-router port; watch for a second default router appearing.
  • Unconfigured ip6tables: run ip6tables -S | head -1. If it prints -P INPUT ACCEPT while the v4 chain prints DROP, you have the gap. Diff both chains in config management and alert on drift.
  • Tunnel egress: a hit on the proto 41 or UDP 3544 block is either a misconfigured host or an actual bypass attempt. Both need a ticket.
  • Cloud SG gap: compare each security group's IpRanges and Ipv6Ranges; an empty Ipv6Ranges on a public-facing group is the finding.

Worked trace. A client resolves api.internal. Before AAAA: A → 10.0.4.7, and the v4 firewall logs the flow. After AAAA: getaddrinfo returns both; RFC 6724 prefers 2001:db8:1::7; Happy Eyeballs opens v6 first and v4 at +250 ms; the v6 SYN reaches the host because ip6tables was never configured, and nothing logs it. The v4 path still looks healthy, so dashboards stay green while traffic has moved.

Rollout. Segment by segment, canary one /64, watch for unexpected IPv6 flows, and roll back by withdrawing the AAAA record: that lever is faster than any firewall change.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Secure connectivity during a merger or hybrid-cloud integration.

Answer

Assume the ask is: two organizations are merging, or one is integrating a hybrid cloud, and you must connect specific services without merging routing domains, directories, or trust. The duration is 6–18 months, both sides use RFC 1918 space, and the acquired side may already be compromised. My first answer: treat the other network as an external security domain. Connect only named service pairs through an identity-aware proxy or a routed VPN with default-deny policy. Never redistribute routes between the two routing domains, and never federate their identity provider into your admin plane.

Why transitive access is the failure mode. If you redistribute routes, a single peering becomes any-to-any. A BGP leak from the acquired AS can advertise 10.0.0.0/8 into your VPC. Because RFC 1918 is not unique, your 10.1.0.0/16 and their 10.1.0.0/16 collide. A route to 10.1.5.0/24 from their side can blackhole or hijack your internal service. Fix: re-IP, NAT, or use a proxy that addresses services by DNS name. If you must route, filter with BGP no-export communities and explicit prefix lists.

Asymmetric routing breaks stateful firewalls. Trace: client 10.1.5.10 sends SYN to 10.2.5.20. Forward path goes VPN-A, return path goes VPN-B. Firewall-A sees SYN, creates state. SYN-ACK arrives on VPN-B, firewall-B has no state, drops. Client retries, same result. tcpdump on both firewalls shows SYN out A, SYN-ACK in B. Fix: policy-based routing to force both directions through the same firewall, or terminate at a proxy. Also clamp TCP MSS to 1360 on both tunnel endpoints; a 1500-byte packet over IPsec with ESP overhead fragments or blackholes if ICMP frag-needed is blocked, and the TLS ClientHello hangs.

Inherited compromise looks like EDR telemetry from the acquired side showing unusual outbound to C2, impossible travel, or a service account authenticating from a new ASN. Do not trust their IdP assertions for your admin plane. Use separate OIDC app registrations, require MFA and device compliance, and scope workload identity to specific service accounts, SPIFFE IDs or cloud IAM roles with trust policies, not a shared VPN PSK.

DNS overlap is the quiet one. Both sides use corp.example.com. Their resolver forwards corp.example.com to your DNS; a query for payroll.corp.example.com from their compromised host resolves to your internal 10.1.5.20. Fix: give them acquired.example.com, use conditional forwarders only for specific zones, and never accept their DNS as authoritative for your zone.

OptionReachabilityAuthCost/latencyWhen wrong
Identity-aware proxy (Envoy with mTLS)L7 onlyper-request mTLS + OIDCadds 5–15 ms p99 per hopnon-HTTP protocols like SMB or database replication
IPsec VPN with narrow selectorsL3/L4PSK or cert, then firewall1500 MTU, clamp MSS 1360; asymmetric routing breaks stateful firewallmany services, overlapping CIDR, no re-IP budget
Private link (AWS PrivateLink, Azure Private Link)one-way serviceprovider IAMper-endpoint-hour + per-GBbidirectional or client-initiated connections

Stage canaries: test asymmetric routing, DNS, MTU, IPv6, failover, and policy outage. Pull the central firewall policy and confirm fail-closed. Set a calendar expiry on every firewall rule and VPN tunnel; automate teardown. What would change my answer: if only one service is needed and both sides support private link, skip the VPN. If regulatory data residency forbids cross-border, keep separate and filter at the API gateway.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design network security for a multi-tenant cloud platform.

Answer

Assumptions. Multi-tenant SaaS on Kubernetes on one cloud, external customers with a contractual isolation requirement, you control the CNI and can run a mesh, and policy ships through GitOps.

The 90-second answer. Pick the tenant isolation boundary before anything else, because it sets the blast radius you are defending. For external customers with a compliance obligation that boundary is a cloud account per tenant, with a VPC per account and PrivateLink for anything shared. For internal tenants, a namespace per tenant on a shared cluster is enough. Everything below assumes the shared-cluster case, which is the harder one.

Then default-deny at every layer, allow only named flows, and put identity in the packet instead of the IP: NetworkPolicy default-deny per namespace, mTLS with SPIFFE identities in STRICT mode, egress through a gateway with FQDN allowlists, IMDSv2 with a hop limit of 1, per-tenant KMS keys. Object authorization stays in the domain service: the network only decides reachability.

Why default-deny actually stops cross-tenant traffic.

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny, namespace: tenant-a}
spec:
  podSelector: {}          # every pod in tenant-a
  policyTypes: [Ingress, Egress]   # no rules => all denied
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: api-to-db, namespace: tenant-a}
spec:
  podSelector: {matchLabels: {app: db}}
  policyTypes: [Ingress]
  ingress:
  - from: [{podSelector: {matchLabels: {app: api}}}]
    ports: [{protocol: TCP, port: 5432}]

NetworkPolicy rules are additive and have no deny form, so the empty-rule policy is what creates default-deny. The mechanism that stops cross-tenant traffic is that from.podSelector is namespace-scoped: tenant-a's rule can only ever select pods in tenant-a. A pod in tenant-b matches no rule in tenant-a's namespace, and tenant-b has its own default-deny, so the CNI drops the packet. Two caveats: NetworkPolicy does not apply to hostNetwork: true pods and does not restrict traffic to the node IP or kubelet, and it is L3/L4 only. Forbid hostNetwork with a Kyverno or OPA admission policy and keep node-level firewall rules as a second layer.

Identity. SPIRE issues X.509-SVIDs with a default TTL of 1 hour. Istio PeerAuthentication STRICT rejects plaintext; PERMISSIVE accepts it, so a pod that skips its sidecar still talks: never leave PERMISSIVE on in production. The TTL is the trade-off: at 1 hour, a SPIRE outage gives you at most 1 hour of new handshakes before hard failure, but revocation propagates within the hour. A 24-hour TTL buys a day of outage tolerance and costs a day of revocation lag.

Egress and metadata. Default-deny egress, allow DNS to CoreDNS and named FQDNs via Cilium toFQDNs. FQDN policy is DNS-based, so a domain with a 60-second TTL can be re-pointed at an internal address between policy evaluation and connection: pin critical egress to static IPs or a TLS-terminating egress proxy. Block 169.254.169.254 from pods: require IMDSv2 (HttpTokens: required) and set HttpPutResponseHopLimit to 1, which stops container traffic reaching IMDS because the extra veth hop exceeds the limit.

Failure modes and how you see them.

  • Cross-tenant reachability: a prober pod in every tenant namespace attempts every other tenant's services every 60s; any success pages. Hubble or VPC Flow Logs flag any flow whose source and destination tenant labels differ.
  • Policy drift: Argo CD diff plus Kyverno admission that rejects direct kubectl edits, reconciled hourly.
  • CA outage: alert on SPIRE server health and SVID issuance latency; bounded by the SVID TTL above.
  • DDoS: Shield Advanced ($3,000/month) plus a WAF rate-based rule; CloudFront absorbs volumetric floods.
  • KMS regional outage: envelope encryption with cached DEKs keeps reads alive until the cache TTL expires.

When this is wrong. If tenants are regulated to the point of needing separate failure domains, namespace isolation is the wrong answer no matter how good the policy is: one CNI CVE or kubelet escape crosses every namespace. Move to cluster- or account-per-tenant and pay the cost.

Curated: · Written: · Reviewed:

Difficulty: Hard