Network Security and Defense Questions
Securing networks at the infrastructure layer. Covers firewalls, ACLs and rule design, network device hardening and secure configuration, intrusion detection and prevention systems, VPN and remote-access encryption, network protocols and their security properties, and packet-level traffic analysis. The hands-on network-defense layer, distinct from zero-trust architecture strategy.
Write a tcpdump/BPF filter that captures TCP packets destined to port 443 that contain a TLS "ClientHello" record (TLS record type 0x16) in the first TLS record. Provide the BPF filter expression and explain why it works (explain offsets for IP and TCP headers and the TLS record header check).
Sample Answer
Approach: match on destination port first as a cheap precondition, then reach past the fixed Ethernet/IP/TCP headers into the first byte of the TLS record layer to check its record-type value.
tcp dst port 443 and (tcp[((tcp[12:1] & 0xf0) >> 2)] = 0x16)
This compiles to valid BPF bytecode against a real TCP/IP packet, verified directly with tcpdump -d.
Explanation of the offsets
tcp dst port 443: a standard port match, and also a cheap precondition guaranteeing the packet has a full TCP header before any byte-offset math runs against it. Note what this filter does not need to do manually: because it uses thetcp[]protocol qualifier rather than rawether[]/ip[]byte offsets, BPF has already located the start of the TCP header for us, skipping past the Ethernet header and the IP header (itself variable-length if IP options are present) automatically. Every offset written below is relative to that TCP header start, not to the start of the packet.tcp[12:1]: the single byte at offset 12 into the TCP header. In the TCP header layout, the upper nibble of byte 12 is the Data Offset field, the TCP header's own length measured in 32-bit words.& 0xf0isolates that upper nibble (masking off the lower 4 bits, which belong to reserved/flag bits).>> 2then converts "number of 4-byte words, already positioned in the top nibble of the byte" into "header length in bytes" directly, since a byte's top nibble shifted right by 2 is arithmetically equivalent to the word count multiplied by 4. To see why a right-shift, which normally divides, ends up scaling by 4 here: because the Data Offset value sits in the byte's top nibble, its raw value is already the word count times 16 (occupying the high 4 bits multiplies the underlying number by 2^4 = 16). The>> 2then divides that by 4 (2^2), leaving the word count times 4; and since each 32-bit word is 4 bytes, word count times 4 is exactly the header length in bytes. The shift really is dividing, it simply starts from a value that was 16 times too large.tcp[((tcp[12:1] & 0xf0) >> 2)]therefore reads the byte located exactly at "TCP header length in bytes" past the start of the TCP header, which is the first byte of whatever follows it: here, the TLS record layer.= 0x16checks that byte equals0x16, the TLS record type value for Handshake, the record type that carries a ClientHello (and every other TLS handshake message).
Edge cases
- TCP options. The header is often longer than the minimum 20 bytes because of options like timestamps or selective acknowledgment. That's exactly why the filter computes the offset dynamically from the Data Offset field instead of hardcoding a fixed byte position; a hardcoded offset would silently miss any connection using TCP options, which is most modern traffic.
- Only matches the first record boundary. This filter checks the very first TLS record right after the TCP header, so it correctly matches a ClientHello sent as the first bytes of the first segment, but it will not match one whose relevant byte falls at a different offset because of prior segmentation. It also cannot distinguish a ClientHello from a ServerHello or any other handshake sub-type, since all handshake messages share record type
0x16; disambiguating specifically requires checking one further byte in (0x01for ClientHello), which most simple BPF filters skip because deeply nested offset math becomes awkward in classic BPF's limited instruction set. - IPv6 is a hard limitation, not just a caveat.
tcpdump's own documentation states plainly that arithmetic expressions against transport-layer headers, liketcp[n], only work against IPv4 packets and do not work against IPv6 at all. This was confirmed empirically as well: the same filter compiled and tested against a synthetic IPv6 packet matched nothing. Filtering TLS records over IPv6 requires a different approach entirely, usingip6 protochain 6to locate the TCP header past IPv6's variable-length extension-header chain, combined with manually computed byte offsets from a fixed link-layer base rather than thetcp[]shorthand used here.
Write detailed pseudocode or a Python outline (using scapy or pyshark) to reconstruct TCP sessions from a pcap, reassemble payloads per session, compute per-session entropy and average packet inter-arrival time, and output a CSV of session metadata for downstream analysis. Discuss memory, concurrency, and performance considerations for large pcaps.
Sample Answer
Approach: group packets into sessions by their unsorted (source, destination) socket-pair key so both directions of one TCP conversation land in the same group, then compute per-session payload entropy and average inter-arrival time from that group, streaming results out as CSV rows. In real use the packets come from scapy.utils.PcapReader over a capture file; the block below builds two small, fully pinned synthetic TCP sessions in memory instead of reading an external file, so it is self-contained and reproducible by anyone who copies it as-is.
import math, csv, io
from collections import defaultdict
from scapy.all import IP, TCP, Raw
# Two synthetic sessions, fully pinned (no external pcap file needed to reproduce this)
packets = []
t = 0.0
session1_payloads = [b"GET / HTTP/1.1\r\n", b"aaaaaaaaaaaaaaaa", b"HTTP/1.1 200 OK\r\n"]
for i, payload in enumerate(session1_payloads):
src, dst, sport, dport = ("10.0.0.5", "93.184.216.34", 5555, 80) if i % 2 == 0 else ("93.184.216.34", "10.0.0.5", 80, 5555)
pkt = IP(src=src, dst=dst) / TCP(sport=sport, dport=dport, seq=1000 + i) / Raw(load=payload)
pkt.time = t
packets.append(pkt)
t += 0.05
t += 1.0
session2_payloads = [bytes(range(0, 64)), bytes(range(64, 128)), bytes(range(128, 192))]
for i, payload in enumerate(session2_payloads):
src, dst, sport, dport = ("10.0.0.7", "198.51.100.9", 6666, 443) if i % 2 == 0 else ("198.51.100.9", "10.0.0.7", 443, 6666)
pkt = IP(src=src, dst=dst) / TCP(sport=sport, dport=dport, seq=2000 + i) / Raw(load=payload)
pkt.time = t
packets.append(pkt)
t += 0.2
def session_key(pkt):
ip, tcp = pkt[IP], pkt[TCP]
a, b = (ip.src, tcp.sport), (ip.dst, tcp.dport)
return tuple(sorted([a, b])) # direction-independent key
def shannon_entropy(data: bytes) -> float:
if not data:
return 0.0
freq = defaultdict(int)
for b in data:
freq[b] += 1
n = len(data)
return -sum((c / n) * math.log2(c / n) for c in freq.values())
sessions = defaultdict(list)
for pkt in packets:
if IP in pkt and TCP in pkt:
sessions[session_key(pkt)].append(pkt)
rows = []
for key, pkts in sessions.items():
pkts.sort(key=lambda p: p.time)
payload = b"".join(bytes(p[Raw].load) for p in pkts if Raw in p)
times = [float(p.time) for p in pkts]
gaps = [t2 - t1 for t1, t2 in zip(times, times[1:])]
avg_iat = sum(gaps) / len(gaps) if gaps else 0.0
rows.append({
"endpoint_a": f"{key[0][0]}:{key[0][1]}",
"endpoint_b": f"{key[1][0]}:{key[1][1]}",
"packets": len(pkts),
"payload_bytes": len(payload),
"entropy_bits_per_byte": round(shannon_entropy(payload), 3),
"avg_inter_arrival_s": round(avg_iat, 3),
})
buf = io.StringIO()
writer = csv.DictWriter(buf, fieldnames=list(rows[0].keys()))
writer.writeheader()
for r in rows:
writer.writerow(r)
print(buf.getvalue(), end="")
Running the block above (session 1 carries repetitive text-like bytes, session 2 carries the full byte range 0-191 to simulate compressed/encrypted-looking payload) prints:
endpoint_a,endpoint_b,packets,payload_bytes,entropy_bits_per_byte,avg_inter_arrival_s
10.0.0.5:5555,93.184.216.34:80,3,49,3.403,0.05
10.0.0.7:6666,198.51.100.9:443,3,192,7.585,0.2
Key points
Sorting the two endpoints into a single, direction-independent key means both the client-to-server and server-to-client packets of one TCP conversation land in the same session bucket, which is what makes a genuine "session" instead of two disconnected half-flows. The entropy calculation treats the payload as a flat byte histogram (Shannon entropy over 256 possible byte values), so a repetitive, text-like payload lands well below the 8-bit-per-byte ceiling (3.4 bits/byte above) while a payload spanning the full byte range sits close to it (7.6 bits/byte above), which is the standard, well-known way to flag likely-encrypted or compressed traffic without decrypting anything.
Complexity
Building the session index is O(N) in the number of packets, one pass, one dictionary insert per packet. Computing entropy for a session is O(B) in that session's total payload bytes (one pass to build the byte histogram, one pass over at most 256 distinct byte values to sum the entropy terms), so total entropy work across all sessions is O(total payload bytes). Overall the whole pipeline is linear in packet count plus total payload size, with no quadratic step.
Memory and concurrency considerations for large pcaps
Reading a real capture with scapy.utils.rdpcap loads the entire file into memory before processing, which does not scale to very large pcaps. For large files, iterate with scapy.utils.PcapReader in a with block instead, which streams packets one at a time from disk. Concatenating a session's full payload into one bytes object (as shown, for clarity) also risks high memory use for an unusually long-lived session; a production version would maintain a running 256-entry byte-frequency counter per session incrementally instead of storing the full payload, computing entropy from the running counts only once, at the end. For concurrency, sessions are independent of each other by construction, so sharding packets across workers by a hash of the session key (rather than by arrival order) parallelizes cleanly, as long as each worker owns the complete set of packets for any session key it's assigned.
Edge cases
A session with a single packet and no payload produces zero entropy and an undefined average inter-arrival time (handled here by defaulting to 0.0 rather than dividing by zero). Retransmitted or out-of-order packets are included in the payload concatenation in capture order after the per-packet timestamp sort, which is a simplification since it doesn't deduplicate retransmissions the way a real TCP reassembly stack would; a more rigorous version would track sequence numbers and only count each byte range once.
Explain how NAT, hairpinning (NAT loopback), and service discovery interact when traffic traverses multiple firewalls or VPCs. Walk through how you would diagnose a resulting failure (for example, a callback or health check that stops working) and propose concrete mitigations and troubleshooting steps.
Sample Answer
Network Address Translation (NAT), hairpinning (also called NAT loopback), and service discovery can interact in a way that works perfectly from outside the network but silently fails for a caller inside it, because the caller and an external client can end up taking genuinely different paths to reach what looks like the same service.
How the interaction breaks things
Hairpinning is what has to happen when a client behind the same NAT gateway as a service tries to reach that service via its public address: traffic has to leave the gateway and come back in through it, rather than staying purely internal, and not every NAT or firewall device supports this correctly. If service discovery or DNS resolves callers to the service's externally-published address regardless of where the caller sits (a very common default when there's a single public DNS name), an internal caller ends up depending on hairpin support it may not actually have.
Worked example: a health check that stops working
An internal health-check process resolves the target service's public DNS name (because that's the only name service discovery publishes) and connects to its public IP through the same firewall/NAT path an external client would use. If that gateway doesn't support hairpin NAT, the SYN either gets silently dropped or the return traffic takes an asymmetric path back through a different device that never saw the outbound leg and drops it as an invalid, untracked connection. External clients keep working fine (they were never depending on hairpinning), so the failure looks host- or path-specific and is easy to misdiagnose as an application bug rather than a network topology issue.
Diagnosing the failure
- Capture from the internal caller's own interface to see whether the SYN leaves at all, and whether any SYN-ACK returns, and if it does, whether it arrives via the interface you'd expect.
- Check exactly what address service discovery handed the caller: public or internal.
- Check whether the outbound and expected-return paths traverse the same stateful device; a stateful firewall that sees only one leg of a connection will drop the other leg as invalid, which looks identical to a routing problem from the outside.
- Confirm whether the specific NAT/firewall device in the path actually supports hairpin/loopback NAT, since support varies significantly by vendor and platform.
Mitigations
Use split-horizon DNS (or equivalent internal service discovery) so internal callers resolve to an internal address or private virtual IP entirely, bypassing the external NAT and load-balancer path rather than depending on hairpinning to work at all. Where hairpinning genuinely must be relied on, explicitly verify and enable loopback support on the specific gateway rather than assuming it. Ensure routing symmetry, the same stateful device sees both directions of a given flow, since asymmetric routing across multiple firewalls is a common root cause even when hairpinning itself is supported. Finally, test service-to-service calls from inside the network as part of normal validation, rather than only testing from outside, since that's exactly the blind spot this failure mode hides in.
Write a set of Azure Network Security Group (NSG) rules (in descriptive form) that permit outbound HTTPS only for a web application subnet while denying outbound SSH for that same subnet, and allow inbound health-check probes from a public load balancer IP range. Explain rule priority numbers and how implicit deny plays out in NSGs.
Sample Answer
Direct answer
The rule set needs three explicit rules, ordered by priority number (lower numbers are evaluated first): allow inbound health-check traffic from the load balancer, deny outbound Secure Shell (SSH), and allow outbound HTTPS, all sitting above Azure's built-in implicit deny-all rule, which silently drops anything not explicitly matched by a higher-priority allow rule.
Approach
An Azure Network Security Group (NSG) evaluates its rules in priority order, lowest number first, and stops at the first rule that matches a given packet. So the design task is really: put the specific exceptions where they need to be relative to each other and to the built-in catch-all, and make sure nothing broader accidentally matches before a more specific rule gets its turn.
| Priority | Direction | Name | Source | Destination | Port | Protocol | Access |
|---|---|---|---|---|---|---|---|
| 100 | Inbound | Allow-LB-HealthProbe | AzureLoadBalancer | VirtualNetwork | 80 | TCP | Allow |
| 200 | Outbound | Deny-SSH-Outbound | VirtualNetwork | Internet | 22 | TCP | Deny |
| 300 | Outbound | Allow-HTTPS-Outbound | VirtualNetwork | Internet | 443 | TCP | Allow |
| 65500 | Inbound / Outbound | (built-in) DenyAllInBound / DenyAllOutBound | Any | Any | Any | Any | Deny |
Equivalent Azure command-line interface (CLI) commands for the three custom rules:
# Allow inbound health-check probes from the Azure Load Balancer
az network nsg rule create \
--resource-group myRG \
--nsg-name web-subnet-nsg \
--name Allow-LB-HealthProbe \
--priority 100 \
--direction Inbound \
--access Allow \
--protocol Tcp \
--source-address-prefixes AzureLoadBalancer \
--source-port-ranges '*' \
--destination-address-prefixes VirtualNetwork \
--destination-port-ranges 80
# Deny outbound SSH from the web subnet
az network nsg rule create \
--resource-group myRG \
--nsg-name web-subnet-nsg \
--name Deny-SSH-Outbound \
--priority 200 \
--direction Outbound \
--access Deny \
--protocol Tcp \
--source-address-prefixes VirtualNetwork \
--destination-address-prefixes Internet \
--destination-port-ranges 22
# Allow outbound HTTPS from the web subnet
az network nsg rule create \
--resource-group myRG \
--nsg-name web-subnet-nsg \
--name Allow-HTTPS-Outbound \
--priority 300 \
--direction Outbound \
--access Allow \
--protocol Tcp \
--source-address-prefixes VirtualNetwork \
--destination-address-prefixes Internet \
--destination-port-ranges 443
Key points
Priority numbers. Azure NSG rules take a priority number from 100 to 4096, and lower numbers are evaluated first. Once a packet matches a rule, evaluation for that direction stops, so the first (lowest-numbered) matching rule always wins. Here, the health probe's inbound allow at 100 has to sit below any rule that might otherwise deny that traffic, and the outbound deny and allow rules are on disjoint ports (22 versus 443) so their relative order does not change the outcome in this specific case, though as a general habit it is safer to place explicit deny rules at a lower number than broader allow rules that could otherwise also match the same traffic.
Implicit deny. Every NSG ships with two built-in rules at the very bottom of its list, at priority 65500, one for each direction, that deny all inbound and all outbound traffic not matched by anything above them. These built-in rules cannot be deleted or reprioritized. That means the three custom rules only need to state what should be explicitly allowed or explicitly denied; everything else already falls through to that catch-all deny without any extra configuration.
Edge cases and things worth checking
NSGs are stateful for allowed flows: an inbound-allowed connection's return traffic is automatically permitted outbound without a separate matching rule, and the same is true in reverse, so do not add a redundant explicit rule for traffic that is already covered by an already-allowed session's return path. NSGs can also be associated at both the subnet level and the individual network interface level, and both have to permit a flow for it to actually pass, which doubles the places a future rule change needs to be checked. Finally, if the load balancer's actual health-check port differs from the example port 80 used here, the inbound allow rule's destination port has to match the real probe port exactly, or the load balancer will mark otherwise-healthy instances as unhealthy.
Trade-offs and pitfalls
A subtle mistake is placing the SSH-deny rule at a higher priority number than some broader outbound allow-all rule, if one existed elsewhere in the same NSG, since the broader rule would win first and the specific deny would never be evaluated. Priority ordering always has to be checked against every rule in the NSG, not just the two you are currently focused on.
Provide a concise nftables or iptables configuration snippet that rate-limits new HTTP connections to 200 new connections per second per source IP with a burst of 400, dropping connections that exceed this. Explain limitations of this approach under high-cardinality distributed attacks and the impact on conntrack tables.
Sample Answer
iptables -A INPUT -p tcp --dport 80 --syn -m hashlimit \
--hashlimit-name http_new --hashlimit-mode srcip \
--hashlimit-upto 200/sec --hashlimit-burst 400 \
--hashlimit-htable-expire 60000 \
-j ACCEPT
iptables -A INPUT -p tcp --dport 80 --syn -j DROP
Approach
The xt_hashlimit module gives per-key (here, per source IP) token-bucket rate limiting, unlike the plain limit module which enforces one global rate across all traffic. The first rule accepts new connections (--syn, matching only the initial SYN of each attempted connection) as long as the originating source IP stays within 200 per second with a burst allowance of 400; anything from a source IP that has exceeded that falls through to the second rule and is dropped.
Key points
--hashlimit-mode srcipis what makes the bucket per-source-IP rather than global; each distinct source IP gets its own independent 200/sec, burst-400 allowance.--hashlimit-burst 400allows short bursts above the steady 200/sec rate (up to 400 tokens banked) before dropping begins, so a legitimate client opening several connections in quick succession isn't punished for a momentary spike.--hashlimit-htable-expire 60000expires a source IP's tracking entry after 60,000 ms (60 seconds) of inactivity, bounding the memory used by the hash table of tracked sources.
Limitations under high-cardinality distributed attacks
Per-source-IP rate limiting defends against a small number of noisy sources, not a distributed attack. A botnet of 10,000 hosts each sending 50 connections per second stays well under the per-IP 200/sec threshold for every individual source, yet delivers an aggregate 500,000 connections per second, none of which this rule alone will ever drop. Distributed floods need an aggregate control (a global cap, upstream scrubbing, or an anycast/CDN layer absorbing volume before it reaches this host) layered on top of, not instead of, the per-source rule shown here.
Impact on conntrack
The --syn match is itself stateless: it is shorthand for --tcp-flags SYN,RST,ACK,FIN SYN, a pure per-packet test of the TCP flag bits that never consults conntrack (only -m state or -m conntrack matches read that table). Connection tracking is a separate kernel subsystem: the conntrack table holds state for in-flight and recently-seen connections, and once a SYN is accepted the connection-tracking subsystem creates an entry for that flow independently of how the packet was matched. Even rate-limited SYNs still create conntrack entries once accepted, so a sustained flood just under the per-IP threshold, spread across enough distinct source IPs, can still fill the conntrack table (bounded by nf_conntrack_max) before entries expire, at which point the kernel starts dropping new connections indiscriminately, including legitimate ones, regardless of what this rule intended. Tuning net.netfilter.nf_conntrack_max and TCP-specific conntrack timeouts alongside this rule is necessary, not optional, once the source count gets large.
Unlock Full Question Bank
Get access to all Network Security and Defense interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.