Skip to content

Network Security

A firewall is a network security device or software that monitors and filters incoming and outgoing Network traffic based on an organization’s security policies.

TypeOSI LayerInspection DepthExample
Packet filteringL3 (Network)Source/destination IP, port, protocoliptables, nftables, PF
Stateful inspectionL3-L4Connection state trackingiptables with conntrack, PF
Application-layerL7Application protocol contentModSecurity, AWS WAF
Next-generation (NGFW)L3-L7All of the above + IPS, TLS inspectionPalo Alto, Fortinet, pfSense
Web Application (WAF)L7HTTP/HTTPS request/responseCloudflare WAF, AWS WAF, ModSecurity

Stateful firewalls maintain a connection table that tracks the state of each connection. They Understand the difference between a new connection, an established connection, and a related Connection.

Terminal window
# nftables example: stateful firewall rules
nft add table inet filter
nft 'add chain inet filter input { type filter hook input priority 0; policy drop; }'
nft 'add chain inet filter output { type filter hook output priority 0; policy accept; }'
nft 'add chain inet filter forward { type filter hook forward priority 0; policy drop; }'
# Allow established/related connections
nft add rule inet filter input ct state established,related accept
# Allow loopback
nft add rule inet filter input iif lo accept
# Allow SSH (rate limited)
nft add rule inet filter input tcp dport 22 ct state new limit rate 10/minute accept
# Allow HTTPS
nft add rule inet filter input tcp dport 443 ct state new accept
# Log and drop everything else
nft add rule inet filter input log prefix "nft-drop: " drop

A WAF operates at layer 7 and inspects HTTP/HTTPS traffic for malicious payloads. It is the last Line of defense against web application attacks (after secure coding practices and input Validation).

WAF rules target specific attack patterns:

Attack TypeWAF Detection Pattern
SQL injection' OR``UNION SELECT``--``; DROP
XSS<script``onerror=``javascript:
Path traversal../``%2e%2e%2f``..%2f
Remote code execeval(``exec(``system(``cmd=
SSRF169.254.169.254``metadata.google.internal

WAF limitations:

  • WAFs are signature-based and cannot detect novel attacks
  • False positives can block legitimate traffic
  • WAFs do not fix underlying vulnerabilities — they mask them
  • Encrypted traffic (HTTPS) requires TLS termination before WAF inspection
  • Attackers can encode payloads to bypass pattern matching

The most important firewall principle: default deny. All traffic is denied unless explicitly Allowed. The alternative (default allow) requires you to enumerate every possible attack, which is Impossible.

Terminal window
# Default deny (correct)
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT # Typically allow outbound
# Then add specific allow rules
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Network segmentation divides a network into smaller zones with different security policies. Each Zone represents a trust boundary.

VLANs (Virtual Local Area Networks) operate at layer 2 and segment a physical network into logical Broadcast domains. Traffic between VLANs must pass through a router or layer 3 switch, where Firewall rules can be applied.

VLAN 10: Management (switches, hypervisors, IPMI)
VLAN 20: Production (application servers)
VLAN 30: Database (database servers, no internet access)
VLAN 40: Development (dev/test environments)
VLAN 50: Guest/IoT (isolated, internet-only)
Terminal window
# Linux bridge VLAN configuration
ip link add name br0 type bridge
ip link set dev br0 up
ip link set dev eth0 master br0
bridge vlan add dev eth0 vid 10
bridge vlan add dev br0 vid 10 pvid untagged

A DMZ (Demilitarized Zone) is a network segment that sits between the internal network and the Internet, hosting publicly accessible services.

graph LR
    Internet --> FW1[External Firewall]
    FW1 --> DMZ[DMZ Zone]
    FW1 --> FW2[Internal Firewall]
    FW2 --> Internal[Internal Network]

    DMZ --> WebServer[Web Server]
    DMZ --> MailServer[Mail Server]
    Internal --> AppServer[App Server]
    Internal --> Database[(Database)]

DMZ firewall rules:

DirectionRule
Internet to DMZAllow specific ports (80, 443)
DMZ to InternetAllow established connections
DMZ to InternalAllow specific ports to app tier
Internal to DMZAllow established connections
Internal to InternetAllow outbound (proxy/NAT)
Internet to InternalDeny all

Microsegmentation applies security policies at the workload level (container, VM, process) rather Than the network level. It is the network-level implementation of zero trust.

TechnologyEnvironmentMechanism
Kubernetes NetworkPolicyKubernetesPod-to-pod rules
Istio/EnvoyService meshmTLS + authorization policies
CalicoKuberneteseBPF-based network policy
VMware NSXVirtualizationVM-level microsegmentation
AWS Security GroupsCloudENI-level rules
# Kubernetes NetworkPolicy: deny all ingress to database, allow only from app pod
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: database-policy
namespace: production
spec:
podSelector:
matchLabels:
app: database
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: api-server
ports:
- port: 5432
protocol: TCP

A VPN creates an encrypted tunnel over a public network, allowing secure communication between Remote hosts and a private network.

ProtocolEncryptionSpeedAudit StatusKey Feature
WireGuardChaCha20-Poly1305Very fastSmall, audited codebaseModern, minimal, kernel-integrated
IPsecAES-GCM, IKEv2FastMature, complexSuite of protocols, OS-native
OpenVPNAES-256-GCMModerateMature, auditedFlexible, TLS-based
SSTPTLS 1.2+ModerateMicrosoftWindows-native, traverses firewalls

WireGuard is the recommended VPN protocol for new deployments. It is simple (4,000 lines of kernel Code vs OpenVPN’s 100,000+), fast (in-kernel, modern crypto), and secure (formally verified subset, Small attack surface).

# /etc/wireguard/wg0.conf (server)
[Interface]
PrivateKey = <server-private-key>
Address = 10.0.0.1/24
ListenPort = 51820
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
[Peer]
PublicKey = <client-public-key>
AllowedIPs = 10.0.0.2/32
# /etc/wireguard/wg0.conf (client)
[Interface]
PrivateKey = <client-private-key>
Address = 10.0.0.2/24
DNS = 1.1.1.1, 1.0.0.1
[Peer]
PublicKey = <server-public-key>
Endpoint = vpn.example.com:51820
AllowedIPs = 10.0.0.0/24, 192.168.1.0/24
PersistentKeepalive = 25

IPsec operates at the network layer (L3) and provides site-to-site and remote access VPN. It Consists of two protocols:

  • IKE (Internet Key Exchange): Manages key negotiation (IKEv2 is current)
  • ESP (Encapsulating Security Payload): Provides encryption and authentication
/etc/ipsec.conf
# StrongSwan IPsec configuration (site-to-site)
config setup
charondebug="ike 2, knl 2, cfg 2"
conn site-to-site
left=10.1.0.1
leftsubnet=10.1.0.0/24
leftid=@site-a.example.com
leftcert=site-a.pem
right=203.0.113.1
rightsubnet=10.2.0.0/24
rightid=@site-b.example.com
rightcert=site-b.pem
ike=aes256gcm16-sha384-ecp384!
esp=aes256gcm16-ecp384!
keyexchange=ikev2
auto=start

Intrusion Detection and Prevention (IDS/IPS)

Section titled “Intrusion Detection and Prevention (IDS/IPS)”
AspectIDS (Detection)IPS (Prevention)
ActionAlerts on suspicious activityActively blocks suspicious traffic
DeploymentSpan port, tap (passive)Inline (active)
RiskLow (no traffic impact)Higher (false positives block traffic)
VisibilityFull traffic visibilityMay miss encrypted traffic
MethodHow It WorksStrengthsWeaknesses
Signature-basedMatches known attack patternsLow false positive rateCannot detect novel attacks
Anomaly-basedEstablishes baseline, flags deviationsDetects unknown attacksHigh false positive rate
Heuristic-basedAnalyzes protocol behavior and traffic patternsGood at protocol attacksRequires tuning
Behavior-basedMonitors system/process behaviorDetects lateral movementComplex to configure

Snort and Suricata are open-source IDS/IPS engines that use rule-based detection.

Terminal window
# Suricata rule examples
# Detect SQL injection attempt
alert http $EXTERNAL_NET any -> $HOME_NET 80 (msg:"ET WEB SQL Injection"; flow:established,to_server; content:"UNION"; nocase; http_uri; content:"SELECT"; nocase; http_uri; distance:0; reference:url,owasp.org/www-community/attacks/SQL_Injection; classtype:web-application-attack; sid:1000001; rev:1;)
# Detect port scan
alert tcp $EXTERNAL_NET any -> $HOME_NET any (msg:"PORTSCAN Detected"; flags:S; threshold:type both, track by_src, count 30, seconds 60; classtype:attempted-recon; sid:1000002; rev:1;)
# Detect known malicious IP
drop ip [192.0.2.1, 198.51.100.0/24] any -> $HOME_NET any (msg:"Known Malicious IP"; sid:1000003; rev:1;)

Zeek is a network analysis framework that provides protocol-level analysis rather than signature Matching. It logs all network activity and generates detailed connection, DNS, HTTP, SSL, and file Transfer logs.

# Zeek script to detect SSH brute force
@load base/protocols/ssh
@load base/frameworks/notice
event ssh_auth_failed(c: connection, auth: bool, msg: string) {
if ( !auth ) {
NOTICE([$note=SSH::Brute_Force_Attacker,
$msg=fmt("SSH brute force from %s", c$id$orig_h),
$conn=c,
$identifier=c$id$orig_h]);
}
}

Zero trust networking eliminates implicit trust based on network location. Every request must be Authenticated, authorized, and encrypted regardless of where it originates.

Google’s BeyondCorp (published in 2014) is the foundational model for zero trust networking. Its Principles:

  1. Authenticate, not authorize: Every device and user must authenticate before accessing any resource
  2. Access based on device and user state: Not just credentials, but device posture, location, and behavior
  3. No special network access: VPNs are replaced by per-application access
  4. Dynamic access control: Policies are evaluated per-request, not per-connection
graph TD
    User[User + Device] --> IdP[Identity Provider]
    IdP --> PE[Policy Engine]
    PE --> PEP[Policy Enforcement Point]
    PEP --> App[Application]

    User -->|Device Trust| PE
    User -->|User Identity| IdP
    PE -->|Allow/Deny| PEP

Components:

ComponentPurposeImplementation
Identity ProviderCentralized authentication + device trustOkta, Azure AD, Keycloak
Policy EngineEvaluate access requests against policiesOPA, Cedar, custom
Policy Enforcement PointEnforce decisions at the resourceEnvoy, service mesh, API gateway
Access ProxyPer-application secure accessBeyondCorp Enterprise, Tailscale
Device TrustEvaluate device health and complianceMDM, certificates, posture

Tailscale is a WireGuard-based mesh VPN that implements zero trust principles:

  • Identity-based: Access is based on identity (SSO), not IP addresses
  • No open ports: Services are not exposed to the internet; access requires authentication
  • ACL-based: Fine-grained access control per resource
  • Key management: WireGuard keys are distributed via a control plane, not manually
// tailscale ACL (tailnet policy file)
{
"acls": [
// Allow all users to access their own devices
{ "action": "accept", "src": ["autogroup:member"], "dst": ["autogroup:self:*"] },
// Allow dev team to access staging servers on port 443
{ "action": "accept", "src": ["group:dev"], "dst": ["tag:staging:443"] },
// Allow on-call engineers to access production database
{ "action": "accept", "src": ["group:oncall"], "dst": ["tag:prod-db:5432"] },
// Deny everything else
{ "action": "deny", "src": ["*"], "dst": ["*:*"] },
],
"tags": ["tag:staging", "tag:prod-db"],
}

DNSSEC (Domain Name System Security Extensions) adds cryptographic signatures to DNS records, Enabling DNS response authentication. It prevents DNS cache poisoning and spoofing.

Record TypePurpose
DNSKEYPublic key for the zone
RRSIGSignature over a record set (RRset)
DSDelegation signer — links child zone to parent
NSEC/NSEC3Proves non-existence of a record (authenticated denial)

Chain of trust:

Root Zone (trust anchor)
└── .com zone (signed by root)
└── example.com zone (signed by .com)
└── www.example.com A record (signed by example.com)

DNS over HTTPS (DoH) and DNS over TLS (DoT)

Section titled “DNS over HTTPS (DoH) and DNS over TLS (DoT)”
ProtocolPortEncryptionStandard
DoH443HTTPSRFC 8484
DoT853TLSRFC 7858

Both encrypt DNS queries between the client and the resolver, preventing eavesdropping and Manipulation of DNS responses in transit. They do not encrypt queries between the resolver and the Authoritative name server.

Reference Standards: NIST SP 800-41 (Firewall Guidelines), NIST SP 800-207 (Zero Trust Architecture), RFC 6014 (DNSSEC Operational Practices), RFC 7208 (SPF), RFC 6376 (DKIM), RFC 7489 (DMARC), RFC 8446 (TLS 1.3), RFC 8484 (DNS over HTTPS), IEEE 802.1X (Port-Based Network Access Control), MITRE ATT&CK (Tactic: Lateral Movement).

This topic covers the essential concepts and techniques related to network security, including key principles and practical applications.

Key concepts include:

  • core concepts and definitions
  • key principles and frameworks
  • practical applications
  • common techniques and methods
  • evaluation and critical analysis

A thorough understanding of these concepts, combined with regular practice and review, is essential for mastery of this topic.

Worked examples demonstrating the application of key concepts are covered in the detailed sub-pages linked above.