Skip to content
Published on

Wireshark & Network Security Complete Guide: From Packet Sniffing to Intrusion Detection — Security for Developers

Authors

1. Why Network Security Matters for Developers

Security Is Not Optional — It Is Essential

According to IBM's 2025 Cost of a Data Breach Report, the average cost of a data breach has reached $4.88 million — a 10% increase year-over-year and an all-time high. Even more alarming, over 60% of security incidents originate at the application layer.

The OWASP Top 10 for 2025 shows that most vulnerabilities require direct developer involvement:

RankVulnerabilityDeveloper Relevance
1Broken Access ControlVery High
2Cryptographic FailuresHigh
3Injection (SQL, XSS, LDAP)Very High
4Insecure DesignVery High
5Security MisconfigurationHigh
6Vulnerable ComponentsHigh
7Authentication FailuresVery High
8Data Integrity FailuresHigh
9Logging/Monitoring FailuresMedium
10SSRF (Server-Side Request Forgery)Very High

The 2026 Cyber Threat Landscape

2026 is being recorded as the most dangerous year in cybersecurity history. With the escalation of the U.S.-Iran conflict, state-sponsored hacking group activities have surged by over 700%. Key trends include:

  • APT Group Activity Surge: State-sponsored groups targeting financial, energy, and healthcare infrastructure
  • Supply Chain Attack Expansion: Malicious code distribution through npm, PyPI repositories tripled
  • AI-Powered Attacks: LLM-generated phishing emails and automated vulnerability scanning became routine
  • Ransomware Evolution: Double extortion strategies (data exfiltration + encryption) became standard

DevSecOps and Shift-Left Security

Traditional security was performed during the testing phase after development was complete. The Shift-Left approach integrates security from the earliest stages of development.

Traditional Approach:
  DesignDevelopTest[Security Test]Deploy
Cost increases exponentially when issues found late →

Shift-Left:
  [Security Design][Secure Coding][Security Testing][Security Monitoring]
Early detection reduces cost →

When developers can read network packets, they can:

  • Directly verify whether sensitive data is transmitted in plaintext during API calls
  • Discover TLS configuration errors before deployment
  • Detect suspicious network activity from third-party libraries
  • Diagnose performance bottlenecks and security vulnerabilities simultaneously

2. Mastering Wireshark

2-1. Installation and Setup

macOS:

brew install --cask wireshark

Ubuntu/Debian:

sudo apt update
sudo apt install wireshark
sudo usermod -aG wireshark $USER
# Log out and log back in

Windows:

Download the installer from the official site (wireshark.org). Make sure to install Npcap alongside it.

2-2. Interface Layout

Wireshark's main window consists of 3 panels:

  1. Packet List Panel (top): Summary of all captured packets
  2. Packet Detail Panel (middle): Protocol layer details of the selected packet
  3. Packet Bytes Panel (bottom): Raw binary data (Hex + ASCII)

2-3. Capture Filters vs Display Filters

These two filters are essential for effective Wireshark usage. The most important difference is when they are applied.

AspectCapture FilterDisplay Filter
AppliedBefore capture startsAfter capture (real-time changes)
SyntaxBPF (Berkeley Packet Filter)Wireshark native syntax
PerformanceHigh (kernel-level filtering)Lower (filters after capturing all)
FlexibilityLimitedVery flexible
Examplehost 192.168.1.1ip.addr == 192.168.1.1
Exampleport 80tcp.port == 80
Exampletcp and port 443tcp.port == 443

Capture Filter examples:

host 10.0.0.1
port 443
net 192.168.0.0/24
tcp and port 80
not arp

Display Filter examples:

ip.addr == 10.0.0.1
tcp.port == 443
http.request.method == "GET"
dns.qry.name contains "google"

2-4. Top 30 Essential Display Filters

No.FilterPurpose
1ip.addr == 10.0.0.1Filter specific IP
2tcp.port == 443HTTPS traffic
3tcp.port == 80HTTP traffic
4http.request.method == "POST"POST requests only
5http.request.method == "GET"GET requests only
6dns.qry.name contains "example"DNS queries for specific domain
7tcp.flags.syn == 1 and tcp.flags.ack == 0SYN scan detection
8tcp.analysis.retransmissionTCP retransmission detection
9tcp.analysis.duplicate-ackDuplicate ACK detection
10tcp.analysis.zero-windowZero Window detection
11http.response.code == 500Server error responses
12http.response.code >= 400All error responses
13tls.handshake.type == 1TLS Client Hello
14tls.handshake.type == 2TLS Server Hello
15arpARP packets only
16icmpICMP (ping) packets only
17dnsDNS packets only
18tcp.analysis.flagsTCP problematic packets
19http.cookie contains "session"Requests with session cookies
20frame.time_delta > 1Packets delayed by 1+ seconds
21tcp.len > 0TCP packets with data
22ip.src == 10.0.0.0/8Internal network source
23not arp and not dnsExclude ARP and DNS
24http.host contains "api"API call filtering
25tcp.stream eq 5Specific TCP stream
26frame.len > 1500Packets exceeding MTU
27http.content_type contains "json"JSON responses
28tcp.analysis.lost_segmentLost segments
29ip.ttl < 10Low TTL (routing issues)
30tls.handshake.extensions_server_nameSNI-based filtering

2-5. Follow Stream Feature

TCP Stream following is one of Wireshark's most powerful capabilities:

  1. Right-click on a packet
  2. Select Follow > TCP Stream
  3. View the complete data flow for that connection
# TCP Stream example (HTTP request/response)
GET /api/users HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json
Set-Cookie: session=abc123; HttpOnly; Secure

[Response Body]

HTTP Stream is useful for tracking individual HTTP transactions in HTTP/2 multiplexing environments.

2-6. Using the Statistics Menu

Conversations: Identify which IP pairs exchange the most traffic

Source          Destination     Packets   Bytes
10.0.0.5        52.85.132.99    1,234     890KB
10.0.0.5        142.250.80.46   567       234KB
10.0.0.5        104.18.32.68    345       156KB

Protocol Hierarchy: View traffic ratios by protocol

Ethernet (100%)
  ├── IPv4 (98.5%)
  │   ├── TCP (85.2%)
  │   │   ├── TLS (62.1%)
  │   │   ├── HTTP (15.3%)
  │   │   └── Other (7.8%)
  │   ├── UDP (12.8%)
  │   │   ├── DNS (8.2%)
  │   │   └── QUIC (4.6%)
  │   └── ICMP (0.5%)
  └── ARP (1.5%)

I/O Graphs: Visualize traffic patterns over time. Essential for detecting DDoS attacks or traffic spikes.

2-7. Profile Setup and Column Customization

Profiles allow you to switch between purpose-optimized environments:

Profile examples:
  - Default: General analysis
  - Security: Security analysis (color rules, security columns)
  - Performance: Performance analysis (latency, retransmission columns)
  - DNS: DNS analysis dedicated

Useful custom columns:

  • Delta Time: Time difference from previous packet
  • TCP Stream Index: Stream number
  • HTTP Host: Host header from HTTP requests
  • TLS SNI: TLS Server Name Indication

3. tcpdump in Practice (Server Environments)

3-1. Basic Syntax and BPF Filters

tcpdump is a tool for capturing packets on servers without a GUI. It uses the same BPF (Berkeley Packet Filter) syntax as Wireshark.

Basic structure:

tcpdump [options] [BPF filter expression]

Key options:

-i eth0        # Specify interface
-w output.pcap # Save to file
-r input.pcap  # Read from file
-c 100         # Capture only 100 packets
-n             # Disable DNS reverse lookup (faster)
-nn            # Also don't convert port numbers
-v / -vv / -vvv  # Increase verbosity
-X             # Hex + ASCII output
-A             # ASCII only output
-s 0           # Capture full packets (default: 262144 bytes)
-tttt          # Human-readable timestamp format

3-2. 20 Practical Commands

No.CommandPurpose
1sudo tcpdump -i eth0Basic capture
2sudo tcpdump -i eth0 -w capture.pcapSave to file
3sudo tcpdump -i eth0 host 10.0.0.1Specific host
4sudo tcpdump -i eth0 port 443Specific port
5sudo tcpdump -i eth0 src 10.0.0.1Source IP filter
6sudo tcpdump -i eth0 dst port 80Destination port filter
7sudo tcpdump -i eth0 net 192.168.0.0/24Subnet filter
8sudo tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0'SYN packets only
9sudo tcpdump -i eth0 -c 1000 -w sample.pcapCapture 1000 only
10sudo tcpdump -i eth0 -nn port 53DNS traffic
11sudo tcpdump -i eth0 icmpICMP (ping) only
12sudo tcpdump -i eth0 'port 80 and host 10.0.0.1'Compound filter
13sudo tcpdump -i eth0 -A port 80View HTTP content
14sudo tcpdump -i eth0 'tcp[32:4] = 0x47455420'GET requests only
15sudo tcpdump -i eth0 greater 1000Over 1000 bytes
16sudo tcpdump -i eth0 arpARP packets only
17sudo tcpdump -i eth0 -tttt -c 50 port 443With timestamps
18sudo tcpdump -i any port 8080All interfaces
19sudo tcpdump -i eth0 not port 22Exclude SSH
20sudo tcpdump -i eth0 -G 3600 -w 'capture_%Y%m%d_%H.pcap'Hourly rotation

3-3. Remote Server Capture to Wireshark Analysis

Workflow for capturing pcap files on a server and analyzing locally with Wireshark:

# 1. Capture on the server
ssh user@server 'sudo tcpdump -i eth0 -c 5000 -w /tmp/capture.pcap port 443'

# 2. Copy to local machine
scp user@server:/tmp/capture.pcap ./analysis/

# 3. Open with Wireshark
wireshark ./analysis/capture.pcap

3-4. tcpdump + SSH Pipeline (Real-time)

Analyze remote server packets in real-time with local Wireshark:

# Method 1: SSH pipe
ssh user@server 'sudo tcpdump -i eth0 -w - port 443' | wireshark -k -i -

# Method 2: Using named pipe
mkfifo /tmp/remote_capture
wireshark -k -i /tmp/remote_capture &
ssh user@server 'sudo tcpdump -i eth0 -w - port 443' > /tmp/remote_capture

# Method 3: Time-limited capture
ssh user@server 'sudo timeout 60 tcpdump -i eth0 -w - port 80' | wireshark -k -i -

This technique is extremely useful for real-time analysis of network issues on production servers.


4. Protocol Analysis Through Packets

4-1. TCP 3-Way Handshake Packet Analysis

Let's analyze the TCP connection establishment 3-Way Handshake at the packet level:

Step 1: SYN (ClientServer)
  Source: 10.0.0.5:54321
  Dest:   93.184.216.34:443
  Flags:  [SYN]
  Seq:    0 (ISN: Initial Sequence Number)
  Win:    65535
  Options: MSS=1460, SACK Permitted, Window Scale=6

Step 2: SYN-ACK (ServerClient)
  Source: 93.184.216.34:443
  Dest:   10.0.0.5:54321
  Flags:  [SYN, ACK]
  Seq:    0 (Server's ISN)
  Ack:    1 (Client ISN + 1)
  Win:    65535
  Options: MSS=1400, SACK Permitted, Window Scale=7

Step 3: ACK (ClientServer)
  Source: 10.0.0.5:54321
  Dest:   93.184.216.34:443
  Flags:  [ACK]
  Seq:    1
  Ack:    1
  Win:    65535

Wireshark filter: Use tcp.flags.syn == 1 to find SYN packets, then Follow TCP Stream to view the complete handshake.

Diagnostic Points:

  • SYN only without SYN-ACK: Server not responding (possibly blocked by firewall)
  • SYN-ACK received but no final ACK: Client-side issue
  • Immediate RST packet: Port is closed or firewall is rejecting connections

4-2. HTTP Request/Response Analysis

# HTTP Request Packet Detail
Frame 45: 342 bytes on wire
  Ethernet II: Src=aa:bb:cc:dd:ee:ff, Dst=11:22:33:44:55:66
  Internet Protocol Version 4: Src=10.0.0.5, Dst=93.184.216.34
  Transmission Control Protocol: Src Port=54321, Dst Port=80
  Hypertext Transfer Protocol:
    GET /api/v1/users?page=1 HTTP/1.1
    Host: api.example.com
    User-Agent: Mozilla/5.0 ...
    Accept: application/json
    Authorization: Bearer eyJhbGci...
    Cookie: session_id=abc123
    Connection: keep-alive

# HTTP Response Packet Detail
Frame 47: 1280 bytes on wire
  Hypertext Transfer Protocol:
    HTTP/1.1 200 OK
    Content-Type: application/json; charset=utf-8
    Content-Length: 956
    Set-Cookie: session_id=xyz789; HttpOnly; Secure; SameSite=Strict
    X-Request-Id: req_abc123
    Strict-Transport-Security: max-age=31536000
    X-Content-Type-Options: nosniff

Security checkpoints:

  • Verify Authorization headers are not transmitted over plaintext HTTP
  • Check Set-Cookie includes HttpOnly and Secure flags
  • Confirm security headers (HSTS, X-Content-Type-Options, etc.) are set
  • Ensure responses don't contain sensitive information

4-3. DNS Query/Response Packet Structure

# DNS Query
Domain Name System (query)
  Transaction ID: 0x1a2b
  Flags: 0x0100 Standard query
  Questions: 1
  Queries:
    api.example.com: type A, class IN

# DNS Response
Domain Name System (response)
  Transaction ID: 0x1a2b
  Flags: 0x8180 Standard query response, No error
  Questions: 1
  Answer RRs: 2
  Answers:
    api.example.com: type A, class IN, addr 93.184.216.34
      TTL: 300 (5 minutes)
    api.example.com: type A, class IN, addr 93.184.216.35
      TTL: 300 (5 minutes)

DNS security checks:

  • Are DNS queries being transmitted unencrypted (DoH/DoT usage)
  • Abnormally long domain names (DNS tunneling suspicion)
  • Queries to unknown DNS servers (possible DNS hijacking)

4-4. TLS Handshake Packet Analysis

TLS 1.3 handshake uses 1-RTT (Round Trip Time), faster than previous versions:

Step 1: Client Hello
  TLS Record Layer:
    Content Type: Handshake (22)
    Version: TLS 1.0 (compatibility)
  Handshake Protocol: Client Hello
    Version: TLS 1.2 (for compatibility)
    Random: [32 bytes]
    Session ID: [32 bytes]
    Cipher Suites (17 suites):
      TLS_AES_256_GCM_SHA384
      TLS_AES_128_GCM_SHA256
      TLS_CHACHA20_POLY1305_SHA256
    Extensions:
      server_name: api.example.com  (SNI)
      supported_versions: TLS 1.3
      key_share: x25519 [public key]
      signature_algorithms: ecdsa_secp256r1_sha256, rsa_pss_rsae_sha256

Step 2: Server Hello + Certificate + Finished
  Handshake Protocol: Server Hello
    Cipher Suite: TLS_AES_256_GCM_SHA384
    Key Share: x25519 [server public key]
  [Encrypted Extensions]
  [Certificate]
  [Certificate Verify]
  [Finished]

Step 3: Client Finished (Encrypted)
  [Change Cipher Spec]
  [Finished]

4-5. TLS Decryption: SSLKEYLOGFILE Environment Variable

You can decrypt TLS traffic in development/debugging environments:

# 1. Set environment variable (bash)
export SSLKEYLOGFILE="$HOME/.ssl-keys.log"

# 2. Launch Chrome or Firefox (they automatically recognize this variable)
# The browser writes TLS session keys to the file

# 3. Also works with curl
SSLKEYLOGFILE=$HOME/.ssl-keys.log curl https://api.example.com/health

Wireshark configuration:

  1. Edit > Preferences > Protocols > TLS
  2. Enter the key file path in (Pre)-Master-Secret log filename
  3. Subsequently captured TLS traffic will be displayed decrypted

Warning: Never use this in production environments. Use only in development/staging environments.


5. Attack Detection in Practice

5-1. ARP Spoofing Detection

ARP Spoofing is an attack that forges MAC addresses on local networks to intercept traffic.

Normal ARP Operation:

Who has 10.0.0.1? Tell 10.0.0.5
10.0.0.1 is at aa:bb:cc:dd:ee:ff

ARP Spoofing Detection Scenario:

# Attacker impersonating the gateway (10.0.0.1)
10.0.0.1 is at [Attacker MAC: 11:22:33:44:55:66]Abnormal!
10.0.0.1 is at [Real MAC: aa:bb:cc:dd:ee:ff]Normal

# Two different MAC addresses for the same IPARP Spoofing!

Wireshark Filters:

arp.duplicate-address-detected
arp.duplicate-address-frame

Detection Script:

#!/bin/bash
# ARP table monitoring
while true; do
    arp -a | sort > /tmp/arp_current.txt
    if [ -f /tmp/arp_previous.txt ]; then
        diff /tmp/arp_previous.txt /tmp/arp_current.txt
        if [ $? -ne 0 ]; then
            echo "[ALERT] ARP table changed at $(date)"
            diff /tmp/arp_previous.txt /tmp/arp_current.txt
        fi
    fi
    cp /tmp/arp_current.txt /tmp/arp_previous.txt
    sleep 10
done

5-2. Port Scanning Detection

SYN Scan (Half-Open Scan) Pattern:

This is Nmap's default scan method. It sends SYN packets without completing the connection.

AttackerTarget:22  [SYN]
Target:22Attacker  [SYN,ACK]Port open
AttackerTarget:22  [RST]Connection not completed

AttackerTarget:23  [SYN]
Target:23Attacker  [RST,ACK]Port closed

Wireshark Filters:

# SYN scan detection (SYN without ACK)
tcp.flags.syn == 1 and tcp.flags.ack == 0

# Multiple SYN to various ports in short time
tcp.flags.syn == 1 and tcp.flags.ack == 0 and ip.src == 10.0.0.100

Nmap Scan Types and Packet Characteristics:

Scan TypeCommandTCP FlagsCharacteristics
SYN Scannmap -sSSYNMost common, Half-open
Connect Scannmap -sTFull handshakeComplete TCP connection
FIN Scannmap -sFFINStealth scan
XMAS Scannmap -sXFIN,PSH,URGChristmas Tree
NULL Scannmap -sN(none)No flags set
ACK Scannmap -sAACKFirewall rule detection
UDP Scannmap -sUUDPDetermined by ICMP response

5-3. DDoS Pattern Analysis

SYN Flood:

# Massive SYN packets from various source IPs simultaneously
# Wireshark filter
tcp.flags.syn == 1 and tcp.flags.ack == 0

# Count SYN packets with tcpdump
sudo tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0' -c 10000 2>&1 | tail -1
# Result: "10000 packets captured" in seconds indicates SYN Flood

HTTP Flood:

# Mass requests to the same URL
# Wireshark filter
http.request.uri == "/api/login"

# Check requests per second
# Statistics > I/O Graph with http.request as Y-axis

DNS Amplification:

# DNS responses much larger than queries (amplification ratio)
# Small query (approx 60 bytes)Large response (approx 3000+ bytes)

# Wireshark filter
dns.response and frame.len > 1000

# Amplification ratio = Response size / Request size
# ANY query amplification ratio: approx 28x ~ 54x

DDoS Detection Checklist:

  1. Check for traffic spikes in I/O Graph
  2. Identify top source IPs in Conversations
  3. Check for sudden protocol ratio changes in Protocol Hierarchy
  4. Look for repetitive identical request patterns
  5. Identify abnormal source IP ranges (using GeoIP)

5-4. SQL Injection Detection

Search for SQL keywords in HTTP POST bodies:

# Wireshark Display Filter
http.request.method == "POST" and (
  http contains "UNION" or
  http contains "SELECT" or
  http contains "DROP" or
  http contains "DELETE" or
  http contains "1=1" or
  http contains "OR 1" or
  http contains "--" or
  http contains "/*"
)

Actual SQL Injection Packet Example:

POST /api/login HTTP/1.1
Host: vulnerable-app.com
Content-Type: application/x-www-form-urlencoded

username=admin' OR '1'='1&password=anything

Abnormal Response Size Patterns:

  • Normal login failure response: approx 200 bytes
  • Successful SQL Injection: thousands of bytes (data exfiltration)
# Abnormal response size detection
http.response and http.content_length > 10000

5-5. Data Exfiltration Detection

DNS Tunneling Detection:

DNS Tunneling encodes data within DNS queries to bypass firewalls.

# Normal DNS query
api.example.com (15 characters)

# DNS Tunneling query (abnormally long domain)
dGhpcyBpcyBhIHNlY3JldCBtZXNzYWdl.tunnel.evil.com (48 characters)

Wireshark Filters:

# Abnormal length DNS query detection
dns.qry.name.len > 50

# TXT record queries (frequently used for tunneling)
dns.qry.type == 16

# Abnormally frequent queries to specific domain
dns.qry.name contains "tunnel.evil.com"

Abnormal Outbound Traffic Detection:

# Monitor large outbound traffic with tcpdump
sudo tcpdump -i eth0 'src net 10.0.0.0/8 and dst net not 10.0.0.0/8 and greater 10000' -c 100

# Outbound to abnormal ports
sudo tcpdump -i eth0 'src net 10.0.0.0/8 and not (dst port 80 or dst port 443 or dst port 53 or dst port 22)'

6. Security Tool Ecosystem

6-1. Nmap: Network Scanner

Nmap is an open-source tool for network exploration and security auditing.

# Basic port scan
nmap 192.168.1.1

# Service version detection
nmap -sV 192.168.1.1

# OS detection
nmap -O 192.168.1.1

# Aggressive scan (services, OS, scripts, traceroute)
nmap -A 192.168.1.1

# Full port scan
nmap -p- 192.168.1.1

# NSE script usage
nmap --script vuln 192.168.1.1
nmap --script ssl-heartbleed 192.168.1.1
nmap --script http-sql-injection 192.168.1.1

6-2. Burp Suite: Web App Security Testing

Burp Suite is the standard tool for web application security testing.

Key features:

  • Proxy: Intercept and modify requests/responses between browser and server
  • Scanner: Automated vulnerability scanning (SQL Injection, XSS, CSRF, etc.)
  • Intruder: Automated attacks (Brute Force, Fuzzing)
  • Repeater: Modify and resend individual requests
  • Decoder: Encoding/decoding utilities

6-3. OWASP ZAP: Free Web Security Scanner

# Quick scan with Docker
docker run -t zaproxy/zap-stable zap-baseline.py -t https://target.com

# API scan
docker run -t zaproxy/zap-stable zap-api-scan.py -t https://target.com/openapi.json -f openapi

# Full scan
docker run -t zaproxy/zap-stable zap-full-scan.py -t https://target.com

6-4. Snort / Suricata: IDS/IPS

# Install Suricata (Ubuntu)
sudo apt install suricata

# Update rules
sudo suricata-update

# Run in IDS mode
sudo suricata -c /etc/suricata/suricata.yaml -i eth0

# Custom rule examples
# /etc/suricata/rules/local.rules
# alert http any any -> any any (msg:"SQL Injection Attempt"; content:"UNION SELECT"; nocase; sid:1000001; rev:1;)
# alert dns any any -> any any (msg:"DNS Tunneling Suspected"; dns.query; content:".tunnel."; nocase; sid:1000002; rev:1;)

6-5. Metasploit: Penetration Testing Framework

# Start Metasploit
msfconsole

# Search for vulnerabilities
# msf6> search type:exploit platform:linux apache

# Module usage example
# msf6> use exploit/multi/http/apache_log4j
# msf6> set RHOSTS target.com
# msf6> set RPORT 8080
# msf6> run

6-6. Tool Comparison Table

ToolPurposeLicenseDifficultyPrimary Users
WiresharkPacket analysisFree/OSSIntermediateNetwork engineers, developers
tcpdumpCLI packet captureFree/OSSIntermediateSystem administrators
NmapPort scanningFree/OSSBeginnerSecurity engineers
Burp SuiteWeb security testingPaid/Free ed.AdvancedPentesters
OWASP ZAPWeb security scanningFree/OSSIntermediateDevelopers, QA
SnortIDS/IPSFree/OSSAdvancedSecurity operations
SuricataIDS/IPSFree/OSSAdvancedSecurity operations
MetasploitPenetration testingPaid/Free ed.AdvancedPentesters

7. Zero Trust Architecture

7-1. Core Principle: Never Trust, Always Verify

The traditional security model was the "Castle and Moat" approach: trust the internal network and block only external traffic. However, this model is powerless against insider threats or VPN compromises.

Zero Trust is fundamentally different:

Traditional Model:
  [Internet] --Firewall-- [Internal Network: Trust Everything]
Free lateral movement after internal breach

Zero Trust:
  [Every Request] --Authentication/Authorization-- [Resource]
Verify every access (regardless of location)

Core principles:

  1. Verify Explicitly: Authenticate, authorize, and encrypt every request
  2. Least Privilege: Grant only minimum necessary permissions (Just-In-Time, Just-Enough-Access)
  3. Assume Breach: Design assuming you are already compromised

7-2. Micro-segmentation

Divide the network into small zones to prevent lateral movement:

Traditional Network:
  [Web Server] <-> [App Server] <-> [DB Server]
  All on same VLAN, free communication

Micro-segmentation:
  [Web Server] --Policy--> [App Server] --Policy--> [DB Server]
  Separate security policies for each communication
  - Web -> App: Allow port 8080 only
  - App -> DB: Allow port 5432 only
  - Web -> DB: Block

7-3. mTLS (Mutual Authentication) Implementation

Regular TLS authenticates only the server, while mTLS also authenticates the client:

Regular TLS:
  Client -> Server: "Prove you are the real server with a certificate"
  Server -> Client: [Server certificate]
  -> Client is not verified

mTLS:
  Client -> Server: "Prove you are the real server"
  Server -> Client: [Server certificate] + "You prove yourself too"
  Client -> Server: [Client certificate]
  -> Bidirectional authentication complete

Node.js mTLS Server Example:

const https = require('https')
const fs = require('fs')

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
  ca: fs.readFileSync('ca-cert.pem'), // CA certificate
  requestCert: true, // Request client certificate
  rejectUnauthorized: true, // Reject invalid certificates
}

const server = https.createServer(options, (req, res) => {
  const clientCert = req.socket.getPeerCertificate()
  console.log('Client CN:', clientCert.subject.CN)
  res.writeHead(200)
  res.end('Mutual TLS authenticated!\n')
})

server.listen(443)

7-4. Security in Service Mesh (Istio)

Istio automatically applies mTLS to inter-microservice communication:

# Istio PeerAuthentication - Enforce mTLS
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT # mTLS required

---
# Istio AuthorizationPolicy - Fine-grained access control
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: api-access
  namespace: production
spec:
  selector:
    matchLabels:
      app: api-server
  rules:
    - from:
        - source:
            principals: ['cluster.local/ns/production/sa/frontend']
      to:
        - operation:
            methods: ['GET', 'POST']
            paths: ['/api/v1/*']

7-5. Zero Trust and Kubernetes

# Kubernetes NetworkPolicy - Pod-to-Pod communication control
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-network-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api-server
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: database
      ports:
        - protocol: TCP
          port: 5432
    - to: # Allow DNS
        - namespaceSelector: {}
      ports:
        - protocol: UDP
          port: 53

---
# Pod Security Standards
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    fsGroup: 2000
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: app
      image: myapp:latest
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop:
            - ALL
      resources:
        limits:
          memory: '256Mi'
          cpu: '500m'

8. Security Checklist for Developers

8-1. Enforcing HTTPS and HSTS

# Nginx configuration
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # HSTS header (2 years, include subdomains, preload)
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    # TLS configuration
    ssl_protocols TLSv1.3 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
}

8-2. CORS Configuration

// Express.js - Secure CORS configuration
const cors = require('cors')

const corsOptions = {
  origin: ['https://app.example.com', 'https://admin.example.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 86400, // Preflight cache 24 hours
}

app.use(cors(corsOptions))

// Never do this:
// app.use(cors());  // Allows all origins = security vulnerability

8-3. Rate Limiting

// Express.js - Rate Limiting
const rateLimit = require('express-rate-limit')

// General API
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Max 100 requests
  message: 'Too many requests, please try again later.',
  standardHeaders: true,
  legacyHeaders: false,
})

// Login endpoint (stricter)
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5,
  message: 'Too many login attempts, please try again after 15 minutes.',
})

app.use('/api/', apiLimiter)
app.use('/api/login', loginLimiter)

8-4. Input Validation

// Input validation with Joi
const Joi = require('joi')

const userSchema = Joi.object({
  username: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().email().required(),
  password: Joi.string()
    .min(12)
    .pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/)
    .required(),
  age: Joi.number().integer().min(13).max(120),
})

app.post('/api/register', (req, res) => {
  const result = userSchema.validate(req.body)
  if (result.error) {
    return res.status(400).json({
      error: result.error.details[0].message,
    })
  }
  // Process after validation passes
})

8-5. SQL Parameterized Queries

// Node.js + PostgreSQL - Safe queries
const { Pool } = require('pg')
const pool = new Pool()

// Never do this (SQL Injection vulnerable):
// const query = `SELECT * FROM users WHERE id = ${userId}`;

// Correct way: Parameterized Query
async function getUser(userId) {
  const result = await pool.query('SELECT id, username, email FROM users WHERE id = $1', [userId])
  return result.rows[0]
}

// Using ORM (Prisma)
async function getUserPrisma(userId) {
  return await prisma.user.findUnique({
    where: { id: userId },
    select: { id: true, username: true, email: true },
  })
}

8-6. JWT/OAuth2 Security

// JWT security best practices
const jwt = require('jsonwebtoken')

// Access Token: Short expiry
const accessToken = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, {
  expiresIn: '15m', // 15 minutes
  algorithm: 'RS256', // RSA asymmetric key
  issuer: 'api.example.com',
  audience: 'app.example.com',
})

// Refresh Token: Stored in DB, rotation applied
const refreshToken = jwt.sign(
  { userId: user.id, tokenVersion: user.tokenVersion },
  process.env.REFRESH_SECRET,
  { expiresIn: '7d' }
)

// Verification middleware
function verifyToken(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1]
  if (!token) return res.status(401).json({ error: 'No token' })

  try {
    const decoded = jwt.verify(token, process.env.JWT_PUBLIC_KEY, {
      algorithms: ['RS256'],
      issuer: 'api.example.com',
      audience: 'app.example.com',
    })
    req.user = decoded
    next()
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' })
  }
}

8-7. Secrets Management

# HashiCorp Vault usage example
vault kv put secret/myapp/db \
  username="dbuser" \
  password="supersecret" \
  host="db.internal.example.com"

# Read from application
vault kv get -field=password secret/myapp/db
// AWS Secrets Manager
const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager')

async function getSecret(secretName) {
  const client = new SecretsManagerClient({ region: 'us-east-1' })
  const response = await client.send(new GetSecretValueCommand({ SecretId: secretName }))
  return JSON.parse(response.SecretString)
}

// Usage
const dbCreds = await getSecret('production/database')

8-8. Security Headers

// Security headers with Helmet.js
const helmet = require('helmet')

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        imgSrc: ["'self'", 'data:', 'https:'],
        connectSrc: ["'self'", 'https://api.example.com'],
        fontSrc: ["'self'", 'https://fonts.gstatic.com'],
        objectSrc: ["'none'"],
        mediaSrc: ["'none'"],
        frameSrc: ["'none'"],
      },
    },
    crossOriginEmbedderPolicy: true,
    crossOriginOpenerPolicy: true,
    crossOriginResourcePolicy: { policy: 'same-site' },
    hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },
    noSniff: true, // X-Content-Type-Options: nosniff
    referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
    xssFilter: true, // X-XSS-Protection
  })
)

8-9. Dependency Vulnerability Scanning

# npm audit
npm audit
npm audit fix

# Snyk
npx snyk test
npx snyk monitor

# GitHub Dependabot (auto PR creation)
# .github/dependabot.yml
# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: 'npm'
    directory: '/'
    schedule:
      interval: 'weekly'
    open-pull-requests-limit: 10
    reviewers:
      - 'security-team'
    labels:
      - 'dependencies'
      - 'security'

Comprehensive Security Checklist:

ItemPriorityCheck
HTTPS enforcement + HSTSRequired-
TLS 1.2+ onlyRequired-
CORS whitelistRequired-
Rate LimitingRequired-
Input ValidationRequired-
Parameterized QueriesRequired-
JWT RS256 + short expiryHigh-
Refresh Token RotationHigh-
Secrets Manager usageRequired-
CSP headerHigh-
X-Content-Type-OptionsHigh-
Referrer-PolicyMedium-
Dependency vulnerability scanningRequired-
Dependabot enabledHigh-
Security logging/monitoringRequired-

9. Security Certification Roadmap

Entry → Intermediate → Advanced Path

Entry Level (0-1 years):
  CompTIA Security+
  ├── Difficulty: 2/5
  ├── Cost: ~$404 (exam fee)
  ├── Prep Time: 2-3 months
  ├── Content: Security fundamentals, threats, cryptography, network security
  └── Career Impact: IT security entry, required for government/military roles

Intermediate (1-3 years):
  CEH (Certified Ethical Hacker)
  ├── Difficulty: 3/5
  ├── Cost: ~$1,199 (exam fee)
  ├── Prep Time: 3-4 months
  ├── Content: Hacking techniques, vulnerability analysis, penetration testing
  └── Career Impact: Security analyst, pentester

  CISSP (Security Management Path)
  ├── Difficulty: 4/5
  ├── Cost: ~$749 (exam fee)
  ├── Prep Time: 4-6 months (requires 5 years experience)
  ├── Content: Security management, governance, risk management
  └── Career Impact: CISO, security architect

Advanced (3+ years):
  OSCP (Offensive Security Certified Professional)
  ├── Difficulty: 5/5
  ├── Cost: ~$1,649 (training + exam)
  ├── Prep Time: 6-12 months
  ├── Content: 24-hour hands-on penetration testing exam
  └── Career Impact: Senior pentester, red team

Detailed Certification Comparison

CertificationTargetPractical %RenewalAvg Salary Increase
CompTIA Security+Beginners20%3 years+15%
CEHIntermediate40%3 years+20%
CISSPManagers0% (theory)3 years+25%
OSCPExperts100% (hands-on)None+35%
GPENPentesters60%4 years+25%
CISMManagers0% (theory)3 years+20%
Web Developers:
  Security+CEHOSCPBug Bounty

Cloud Developers:
  Security+AWS Security SpecialtyCCSP

DevOps Engineers:
  Security+CKS (Kubernetes Security)OSCP

10. Quiz

Test your knowledge of what you have learned.

Q1. What is the main difference between Capture Filters and Display Filters in Wireshark?

Answer: They differ in when they are applied.

  • Capture Filter: Set before capture starts, uses BPF syntax. Filters at the kernel level for better performance but cannot be changed during capture.
  • Display Filter: Applied after capture, uses Wireshark native syntax. Filters already captured data, can be changed in real-time.

In high-traffic environments, the best practice is to use Capture Filters to capture only needed traffic, then use Display Filters for detailed analysis.

Q2. What environment variable must be set to decrypt TLS traffic in Wireshark?

Answer: SSLKEYLOGFILE

Setting the SSLKEYLOGFILE environment variable causes browsers like Chrome and Firefox to write TLS session keys to the specified file. When you specify this file in Wireshark (Edit - Preferences - Protocols - TLS), TLS-encrypted traffic content becomes visible.

Warning: This feature should only be used in development/debugging environments, never in production.

Q3. What Wireshark filter would you use to detect a SYN Flood DDoS attack?

Answer: tcp.flags.syn == 1 and tcp.flags.ack == 0

This filter displays packets with only the SYN flag set, without the ACK flag. A SYN Flood attack sends massive SYN packets to fill up the server's TCP connection table.

Additionally, applying this filter in Statistics - I/O Graphs lets you visually identify SYN packet surge patterns over time.

Q4. What are the 3 core principles of the Zero Trust security model?

Answer:

  1. Verify Explicitly: Always authenticate and authorize every request. Verify all access regardless of location or network.
  2. Least Privilege: Grant only minimum necessary permissions using Just-In-Time, Just-Enough-Access principles.
  3. Assume Breach: Design assuming you are already compromised, minimize lateral movement, and apply end-to-end encryption.

Unlike the traditional "castle and moat" model, the key is that even the internal network is not trusted.

Q5. What key indicators should you check to detect DNS Tunneling?

Answer:

  1. Abnormally long domain names: Normal DNS queries are typically 20-30 characters, while DNS Tunneling includes 50+ characters of encoded data.
  2. Spike in TXT record queries: DNS Tunneling frequently uses TXT records to transmit more data.
  3. Abnormal query frequency for specific domains: Dozens to hundreds of queries per second for the same domain.

Wireshark filters: dns.qry.name.len > 50 or dns.qry.type == 16 (TXT records) can detect these patterns.


11. References

  1. Wireshark Official Documentation - wireshark.org/docs
  2. tcpdump Manual - tcpdump.org/manpages
  3. OWASP Top 10 (2025) - owasp.org/Top10
  4. NIST Zero Trust Architecture (SP 800-207) - csrc.nist.gov
  5. IBM Cost of a Data Breach Report 2025 - ibm.com/security
  6. Nmap Reference Guide - nmap.org/book/man.html
  7. Metasploit Unleashed - offensive-security.com/metasploit-unleashed
  8. SANS Network Forensics - sans.org/cyber-security-courses/network-forensics
  9. Practical Packet Analysis, 3rd Edition - Chris Sanders (No Starch Press)
  10. The Web Application Hacker's Handbook - Dafydd Stuttard, Marcus Pinto
  11. CompTIA Security+ Study Guide - comptia.org/certifications/security
  12. OSCP Certification Guide - offensive-security.com/pwk-oscp
  13. Suricata IDS Documentation - suricata.readthedocs.io
  14. Istio Security Documentation - istio.io/latest/docs/concepts/security
  15. Kubernetes Network Policies - kubernetes.io/docs/concepts/services-networking/network-policies
  16. OWASP ZAP Documentation - zaproxy.org/docs
  17. Burp Suite Documentation - portswigger.net/burp/documentation