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
| Domain | Focus | Key Technologies |
|---|---|---|
| Perimeter Security | Controlling network boundaries | Firewalls, IDS/IPS, VPNs |
| Endpoint Security | Protecting individual devices | EDR, AV, host firewalls |
| Application Security | Securing software and web apps | WAF, SAST/DAST, code review |
| Data Security | Protecting data at rest and in transit | Encryption, DLP, tokenization |
| Identity & Access | Controlling who can access what | IAM, SSO, MFA, RBAC |
| Cloud Security | Securing cloud infrastructure | CSPM, CASB, CNAPP |
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.
| Layer | Name | Function | Protocols/Devices | Security Relevance |
|---|---|---|---|---|
| 7 | Application | User-facing network services | HTTP, FTP, DNS, SMTP | Input validation, authentication, WAF |
| 6 | Presentation | Data translation, encryption | SSL/TLS, JPEG, ASCII | Encryption at the session layer |
| 5 | Session | Session management | NetBIOS, RPC | Session hijacking prevention |
| 4 | Transport | End-to-end delivery | TCP, UDP | Port scanning, SYN floods |
| 3 | Network | Logical addressing, routing | IP, ICMP, OSPF, BGP | IP spoofing, routing attacks |
| 2 | Data Link | Physical addressing, framing | Ethernet, ARP, MAC | ARP poisoning, MAC flooding |
| 1 | Physical | Raw bit transmission | Cables, hubs, radio | Physical 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.
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 Layer | OSI Equivalent | Key Protocols |
|---|---|---|
| Application | Layers 5-7 | HTTP, HTTPS, DNS, SSH, FTP, SMTP |
| Transport | Layer 4 | TCP, UDP |
| Internet | Layer 3 | IP, ICMP, ARP, IGMP |
| Network Access | Layers 1-2 | Ethernet, Wi-Fi, PPP |
TCP vs UDP
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (3-way handshake) | Connectionless |
| Reliability | Guaranteed delivery, retransmission | Best-effort, no guarantee |
| Ordering | In-order delivery | No ordering |
| Speed | Slower (overhead) | Faster (minimal overhead) |
| Use Cases | HTTP, SSH, FTP, email | DNS, VoIP, streaming, gaming |
| Security Risk | SYN floods, session hijacking | Amplification 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).
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.
ARP poisoning with arpspoof (Ettercap suite)
Redirect traffic between victim and gateway through attacker.
Enable IP forwarding to act as a man-in-the-middle.
Defense: Static ARP entries.
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.
DNS enumeration with dnsenum.
DNS spoofing with dnsspoof.
Defense: DNSSEC (DNS Security Extensions)
Adds cryptographic signatures to DNS records.
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.
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.
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
| Type | Layer | How It Works | Pros & Cons |
|---|---|---|---|
| Packet Filter | Layer 3/4 | Inspects IP/TCP/UDP headers | Fast, simple; no payload inspection |
| Stateful Inspection | Layer 3/4 | Tracks connection state | More secure; moderate performance |
| Application (Proxy) | Layer 7 | Intercepts and inspects app traffic | Deep inspection; slower |
| NGFW/UTM | Layer 3-7 | Deep packet inspection + IPS + AV | Comprehensive; expensive |
| Cloud/Virtual | All layers | Software-defined, scalable | Flexible; 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
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
| Table | Purpose | Chains |
|---|---|---|
filter | Packet filtering (default) | INPUT, FORWARD, OUTPUT |
nat | Network Address Translation | PREROUTING, POSTROUTING, OUTPUT |
mangle | Packet modification | All chains |
raw | Connection tracking exemption | PREROUTING, OUTPUT |
Common iptables Commands
List all rules with line numbers and verbose output.
Default policy: DROP everything.
Allow established connections.
Allow loopback.
Allow SSH (rate limited to prevent brute force)
Allow HTTP and HTTPS.
Block a specific IP.
Log and drop suspicious traffic.
Save rules (Debian/Ubuntu)
Restore.
-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.
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.
Persist the ruleset to disk and enable it at boot.
Saves the running ruleset so it can be reloaded later.
Loads the saved ruleset automatically on every boot.
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.
List active zones and their settings.
List available services.
Add a service permanently.
Add a custom port.
Rich rules (more granular control)
Block an IP.
Rate limiting (similar to fail2ban)
IP masquerading (NAT)
firewalld Zones
| Zone | Trust Level | Use Case |
|---|---|---|
drop | Untrusted | Drop all incoming, no reply |
block | Untrusted | Reject all with ICMP error |
public | Untrusted | Public Wi-Fi, untrusted networks |
external | Untrusted | External network with masquerading |
dmz | Partially trusted | Publicly accessible servers |
work | Partially trusted | Work environment |
home | Trusted | Home network |
internal | Trusted | Internal corporate network |
trusted | Fully trusted | Accept 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.
Default policies.
Allow SSH (critical — do this first to avoid lockout!)
Allow specific services.
Allow from specific IP.
Deny specific IP.
Limit connection rate (brute force protection)
Delete a rule.
Or by number:
View status.
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
| Type | Knowledge Level | Use Case |
|---|---|---|
| Black Box | No prior knowledge | Simulates external attacker |
| Gray Box | Limited knowledge (user creds) | Simulates insider threat |
| White Box | Full knowledge (source code, architecture) | Comprehensive audit |
| Red Team | Adversarial simulation | Tests detection and response |
| Purple Team | Collaborative attack/defense | Improves both sides |
Penetration Testing Methodology
- Planning & Scoping: Define objectives, scope, rules of engagement, and legal authorization
- Reconnaissance: Gather information about the target (passive and active)
- Scanning & Enumeration: Identify live hosts, open ports, services, and vulnerabilities
- Vulnerability Analysis: Assess findings and identify exploitable weaknesses
- Exploitation: Attempt to gain unauthorized access using identified vulnerabilities
- Post-Exploitation: Determine value of compromised asset, maintain access, pivot
- Reporting: Document findings with evidence, risk ratings, and remediation steps
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.
DNS enumeration.
Zone transfer attempt.
Subdomain enumeration.
OSINT with theHarvester.
Shodan search (requires API key)
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.
ARP scan (local network only)
Traceroute.
Continuous traceroute.
Banner grabbing.
SSL/TLS certificate inspection.
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.
Scan all ports.
Service version detection.
OS detection.
Aggressive scan (OS + version + scripts + traceroute)
Stealth SYN scan (doesn't complete TCP handshake)
UDP scan.
Scan with NSE scripts.
Output formats.
Normal, XML, and grepable.
Scan a network range.
Timing templates (T0 = paranoid, T5 = insane)
Enumeration Techniques
SMB enumeration.
SNMP enumeration.
DNS enumeration.
Web enumeration.
LDAP enumeration.
SMTP enumeration.
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.
Search for exploits.
Use an exploit.
Meterpreter commands (post-exploitation)
Background session and pivot.
Generate payloads.
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:
Linux Privilege Escalation Awesome Script.
Linux enumeration script.
Manual checks:
List sudo privileges.
SUID binaries.
SGID binaries.
Cron jobs.
Users with shells.
Kernel version (exploits?)
Running processes.
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)
SSH key pivoting.
Then scan internal network from pivot.
Proxychains for routing through compromised host.
In /etc/proxychains.conf:
Socks5 127.0.0.1 1080.
SSH dynamic port forwarding.
BloodHound (Active Directory attack paths)
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.
| Standard | Frequency | Max Speed | Notes |
|---|---|---|---|
| 802.11b | 2.4 GHz | 11 Mbps | Legacy, widely supported |
| 802.11a | 5 GHz | 54 Mbps | Less interference |
| 802.11g | 2.4 GHz | 54 Mbps | Backward compatible with b |
| 802.11n | 2.4/5 GHz | 600 Mbps | MIMO support |
| 802.11ac | 5 GHz | 3.5 Gbps | Wave 1 & 2 |
| 802.11ax (Wi-Fi 6) | 2.4/5 GHz | 9.6 Gbps | OFDMA, better efficiency |
| 802.11be (Wi-Fi 7) | 2.4/5/6 GHz | 46 Gbps | 320 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.
Enable monitor mode (requires compatible adapter)
Kill interfering processes.
Creates wlan0mon interface.
Scan for wireless networks.
Detailed scan on specific channel.
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.
| Protocol | Encryption | Authentication | Security Status |
|---|---|---|---|
| WEP | RC4 (40/104-bit) | Shared key | Broken — crackable in minutes |
| WPA | TKIP/RC4 | PSK or 802.1X | Deprecated — vulnerable |
| WPA2-Personal | AES-CCMP | PSK (4-way handshake) | Vulnerable to KRACK, but generally secure |
| WPA2-Enterprise | AES-CCMP | 802.1X/RADIUS | Secure when properly configured |
| WPA3-Personal | AES-CCMP/GCMP | SAE (Simultaneous Authentication of Equals) | Current standard — most secure |
| WPA3-Enterprise | AES-CCMP/GCMP | 802.1X + 192-bit mode | Highest 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.
Deauthenticate a client to force reconnection (capture handshake)
Crack with aircrack-ng (dictionary attack)
Crack with hashcat (GPU-accelerated)
WPA3 downgrade attack (Dragonblood)
Forces WPA3 to downgrade to WPA2, then perform standard attack.
Requires specific tools and vulnerable implementations.
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.
PMKID attack (no client needed!)
Evil Twin with Wifiphisher.
Create rogue AP with 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.
Check for unauthorized clients on your network.
Verify no WPS is enabled.
Lists WPS-enabled networks.
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
| Type | How It Works | Pros | Cons |
|---|---|---|---|
| Signature-Based | Matches traffic against known attack patterns | Low false positives, fast | Can't detect zero-days |
| Anomaly-Based | Learns normal behavior, flags deviations | Detects unknown attacks | Higher false positives |
| Heuristic | Uses algorithms to identify suspicious behavior | Adapts to new threats | Complex tuning required |
| Behavioral | Tracks entity behavior over time | Detects slow attacks | Requires 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
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.
Check Snort version and build info.
Test configuration.
Run Snort in IDS mode.
Run Snort in packet logger mode.
Run Snort in IPS mode (inline)
Update rules with PulledPork.
View alerts.
Writing Snort Rules
Snort rule syntax:
Action protocol src_ip src_port -> dst_ip dst_port (msg:"..."; content:"..."; sid:...; rev:...;)
Detect SQL injection attempt.
Detect port scan (SYN flood)
Detect SSH brute force.
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.
Update rules with Suricata-Update.
Test configuration.
Run Suricata in IDS mode.
Run Suricata in IPS mode (inline with NFQUEUE)
Process a PCAP file.
View alerts.
Generate stats.
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.
TLS fingerprinting rule.
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.
Runs Zeek live on interface eth0.
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.
Lists every log file Zeek generated for the session.
Source, destination, and service for every connection.
Requested host, URI, and response code for HTTP traffic.
Every DNS query and the answers it received.
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.
Zeek Log Files
| Log File | Contents |
|---|---|
conn.log | All TCP/UDP/ICMP connections |
http.log | HTTP requests and responses |
dns.log | DNS queries and responses |
ssl.log | SSL/TLS handshake details |
ssh.log | SSH connection metadata |
files.log | File transfers over any protocol |
notice.log | Alerts generated by Zeek scripts |
weird.log | Protocol 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
| Solution | Type | Best For |
|---|---|---|
| Splunk | Commercial | Enterprise, powerful search |
| Elastic Security (ELK) | Open Source / Commercial | Flexibility, cost-effective |
| QRadar | Commercial | IBM ecosystem, AI |
| Sentinel | Commercial (Cloud) | Microsoft/Azure environments |
| Wazuh | Open Source | Endpoint detection, compliance |
| Graylog | Open Source | Log management, fast search |
Wazuh — Open Source SIEM/XDR
Install Wazuh server (using the quickstart script)
Install Wazuh agent on a Linux endpoint.
Configure agent.
View Wazuh logs.
Custom rules in /var/ossec/etc/rules/local_rules.xml.
Example: Detect failed sudo attempts.
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
| Type | Description | Protocols | Use Case |
|---|---|---|---|
| Remote Access VPN | Individual users connect to corporate network | OpenVPN, WireGuard, IPsec/IKEv2 | Work from home, mobile workers |
| Site-to-Site VPN | Connects entire networks together | IPsec, MPLS, WireGuard | Branch offices, data centers |
| SSL/TLS VPN | Browser-based or client-based over HTTPS | OpenVPN, AnyConnect | Easy deployment, web apps |
| Layer 2 VPN | Extends Layer 2 across networks | L2TP, PPTP, OpenVPN TAP | Legacy applications |
| Mesh VPN | Decentralized peer-to-peer connections | WireGuard, Tailscale, Nebula | Cloud-native, distributed teams |
VPN Protocol Comparison
| Protocol | Encryption | Speed | Security | Ease of Setup |
|---|---|---|---|---|
| PPTP | MPPE | Fast | Broken — do not use | Very easy |
| L2TP/IPsec | AES | Moderate | Good | Moderate |
| OpenVPN | AES-256-GCM | Good | Excellent | Moderate |
| WireGuard | ChaCha20 | Very fast | Excellent | Very easy |
| IPsec/IKEv2 | AES-GCM | Fast | Excellent | Complex |
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.
Set up PKI with Easy-RSA.
Generate server certificate.
Generate Diffie-Hellman parameters.
Generate client certificate.
Generate TLS auth key.
Server configuration (/etc/openvpn/server.conf)
Start OpenVPN server.
Generate client config (.ovpn file)
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.
Generate server keys.
Server configuration (/etc/wireguard/wg0.conf)
Client 1.
Client 2.
Enable IP forwarding.
Start WireGuard.
Client configuration.
View active WireGuard connections.
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
| Mode | Description | Use Case |
|---|---|---|
| Transport Mode | Encrypts only the payload, original IP header intact | Host-to-host communication |
| Tunnel Mode | Encrypts entire packet, adds new IP header | Site-to-site VPNs, remote access |
StrongSwan (Linux IPsec implementation)
Server configuration (/etc/ipsec.conf)
Start 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
| Version | Status | Notes |
|---|---|---|
| SSL 2.0 | Deprecated — insecure | Vulnerable to multiple attacks |
| SSL 3.0 | Deprecated — insecure | POODLE attack |
| TLS 1.0 | Deprecated | Vulnerable to BEAST, downgrade attacks |
| TLS 1.1 | Deprecated | Weak ciphers |
| TLS 1.2 | Supported | Widely deployed, secure when configured |
| TLS 1.3 | Recommended | Faster handshake, improved security |
Certificate Management
Generate a private key and CSR.
Generate a self-signed certificate.
Let's Encrypt with certbot.
Check certificate details.
Check TLS configuration of a server.
Check certificate expiration.
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)
Null, FIN, and Xmas scans (bypass simple firewalls)
Null scan (no flags)
FIN scan.
Xmas scan (FIN, PSH, URG)
Fragment packets (evade simple IDS)
Double fragment.
Decoy scan (hide your IP among fake ones)
10 random decoys + your IP.
Idle scan (zombie host — completely anonymous)
OS detection and service version.
NSE scripts for vulnerability scanning.
Scan IPv6.
Output to all formats.
Top ports scan with service detection.
Nmap NSE Scripts
List all NSE scripts.
HTTP enumeration.
SMB enumeration and vulnerability scanning.
EternalBlue.
SSH brute force (with caution!)
DNS enumeration.
SSL/TLS analysis.
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
| Component | Description |
|---|---|
| Exploits | Code that takes advantage of a vulnerability |
| Payloads | Code that runs after successful exploitation |
| Auxiliary | Scanners, fuzzers, and other non-exploit tools |
| Encoders | Obfuscate payloads to evade detection |
| Nops | No-operation sleds for buffer overflow exploits |
| Post | Post-exploitation modules for privilege escalation, etc. |
| Evasion | Modules to evade antivirus and IDS |
Start Metasploit.
Search for modules.
Use an exploit module.
Meterpreter commands.
Mimikatz integration.
Generate payloads with msfvenom.
Encode payload to evade AV.
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
| Tool | Function | Edition |
|---|---|---|
| Proxy | Intercept and modify HTTP/HTTPS traffic | All |
| Repeater | Manually modify and resend requests | All |
| Intruder | Automated attacks (fuzzing, brute force) | Pro |
| Scanner | Automated vulnerability scanning | Pro |
| Sequencer | Analyze session token randomness | All |
| Decoder | Encode/decode data (Base64, URL, hex, etc.) | All |
| Comparer | Compare two pieces of data | All |
| Extender | Add plugins (BApps) | All |
Common Burp Suite Workflows
- Configure the browser proxy. Point the browser at
127.0.0.1:8080and install Burp's CA certificate (fromhttp://burpsuite/cert) so it can intercept HTTPS too. - 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.
- Spider/crawl the application. Right-click the target and choose Scan → Crawl, or explore it manually via Target → Site Map.
- 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. - Test for SQL injection in Repeater by trying inputs like these:
Should return the normal page if the field is injectable.
Should return a different result than 1=1 if the field is injectable.
Test for XSS with payloads such as:
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.
Capture traffic to/from a specific host.
Capture traffic on a specific network.
Capture ICMP traffic only.
Capture SSH traffic excluding one host.
Capture DNS queries.
Capture ARP traffic.
Capture TLS/SSL handshakes.
Display Filters
Filter by IP address.
Filter by protocol.
Filter by port.
Filter HTTP requests.
Filter DNS queries.
Filter by TCP flags.
SYN scan.
RST packets.
Filter SSL/TLS.
Client Hello.
Server Hello.
Filter suspicious traffic.
Tshark (Command-Line Wireshark)
Capture and display packets.
Capture to file.
Read from file with filter.
Extract HTTP URIs.
Extract DNS queries.
Top talkers.
Protocol hierarchy.
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.
List supported hash types.
Crack MD5 hash with wordlist.
Crack NTLM hash.
Crack WPA/WPA2 handshake.
Crack with rules (mutate wordlist)
Brute force (mask attack)
8 lowercase letters.
1 upper, 4 lower, 3 digits.
Mask characters:
?l = lowercase, ?u = uppercase, ?d = digit.
?s = special, ?a = all, ?h = hex lowercase.
Use GPU acceleration.
Optimized kernels.
Use specific GPU device.
Show cracked passwords.
John the Ripper
Crack Linux password hashes (/etc/shadow)
Crack with wordlist.
Crack with rules.
Show cracked passwords.
Crack ZIP file.
Crack PDF.
Crack SSH key.
Incremental (brute force) mode.
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.
| Rank | Risk | Description | Common Impact |
|---|---|---|---|
| A01 | Broken Access Control | Restrictions on authenticated users are not properly enforced | Unauthorized data access, privilege escalation |
| A02 | Cryptographic Failures | Failure to properly protect data in transit or at rest | Data theft, compliance violations |
| A03 | Injection | Untrusted data sent to interpreters (SQL, OS, LDAP) | Data loss, RCE, authentication bypass |
| A04 | Insecure Design | Fundamental design flaws in application architecture | Multiple attack vectors |
| A05 | Security Misconfiguration | Improperly configured permissions, features, or defaults | Unauthorized access, data exposure |
| A06 | Vulnerable Components | Using outdated or vulnerable libraries/frameworks | RCE, data breach |
| A07 | Auth Failures | Weak authentication mechanisms or session management | Account takeover, identity theft |
| A08 | Integrity Failures | Software and data integrity failures (CI/CD, deserialization) | Supply chain attacks, RCE |
| A09 | Logging Failures | Insufficient logging and monitoring | Delayed detection, no forensic data |
| A10 | SSRF | Server-Side Request Forgery | Internal 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
| Type | Description | Persistence |
|---|---|---|
| Stored XSS | Malicious script stored on the server (database, comment, profile) | Persistent |
| Reflected XSS | Malicious script in URL parameters, reflected in response | Non-persistent |
| DOM-based XSS | Client-side JavaScript modifies DOM unsafely | Non-persistent |
| Blind XSS | Payload executes in admin panel or backend system | Delayed |
XSS Payloads
A few basic proof-of-concept payloads to confirm a field is vulnerable:
A real attack payload exfiltrates data instead of just popping an alert — here, the victim's cookie:
Or a keylogger that streams every keystroke to the attacker:
Naive filters that just strip or block the literal <script> tag can often be bypassed:
A filter that removes "<script>" once leaves a working tag behind.
A polyglot payload is written to execute in several different injection contexts at once (HTML attribute, JS string, URL, etc.):
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
| Type | Description |
|---|---|
| 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-based | Database error messages reveal information |
| Union-based | UNION operator used to extract data from other tables |
| Stacked Queries | Multiple queries executed in one statement |
SQL Injection Payloads
Authentication bypass.
Union-based data extraction.
Time-based blind SQLi (MySQL)
Error-based (MySQL)
Database fingerprinting.
MySQL.
PostgreSQL.
MSSQL.
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:
A parameterized query fixes it by letting the database driver handle escaping:
An ORM like SQLAlchemy achieves the same safety without writing raw SQL at all:
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
- User logs into bank.com and receives a session cookie
- User visits malicious.com in another tab
- malicious.com contains a form or image that submits to bank.com/transfer
- The browser automatically includes the bank.com cookie with the request
- The bank processes the transfer as if the user initiated it
CSRF attack payload (malicious website)
CSRF via image tag (GET request)
CSRF Prevention
- CSRF Tokens: Include unpredictable tokens in every state-changing request
- SameSite Cookies: Set
SameSite=StrictorSameSite=Laxon 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:
Include the token as a hidden field in every form that changes state:
Pair it with SameSite cookies as a second layer of defense:
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.
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:
/etc/nginx/modsec/main.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
| Strategy | Method | Best For |
|---|---|---|
| VLANs | Logical separation at Layer 2 | Cost-effective, flexible |
| Physical Separation | Separate hardware and cabling | Maximum security (air-gapped) |
| Micro-segmentation | Policy-based per-workload | Cloud, data centers |
| SDN Segmentation | Software-defined policies | Dynamic environments |
Common Network Zones
VLAN Configuration (Cisco IOS)
! Create VLANs.
! Configure trunk port.
! Configure access port.
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)
Configure Google Authenticator for MFA.
Add to /etc/pam.d/sshd:
Auth required pam_google_authenticator.so.
Session recording with script.
Add to /etc/profile or /etc/bash.bashrc:
Auto-logout idle sessions.
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
| Pillar | Description | Technologies |
|---|---|---|
| Identity | User and service identity verification | IAM, MFA, PIM, RBAC |
| Devices | Device health and compliance | MDM, EDR, device certificates |
| Applications | Application-level access controls | OAuth, API gateways, CASB |
| Data | Data classification and protection | DLP, encryption, rights management |
| Infrastructure | Secure configuration and monitoring | CSPM, IaC scanning, micro-segmentation |
| Network | Micro-segmentation and encryption | SDN, VPN, TLS everywhere |
Implementing Zero Trust
- Define the Protect Surface: Identify critical data, assets, applications, and services (DAAS)
- Map Transaction Flows: Understand how traffic moves across your network
- Build a Zero Trust Architecture: Design controls around the protect surface
- Create Zero Trust Policy: Define who, what, when, where, why, and how for every access
- Monitor and Maintain: Continuously inspect and log all traffic
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.
2. Configure firewall (default deny)
3. Secure SSH.
4. Install and configure fail2ban.
5. Disable unnecessary services.
6. Audit listening ports.
7. File integrity monitoring (AIDE)
Run checks periodically.
8. Kernel hardening (sysctl)
IP Spoofing protection.
Ignore ICMP redirects.
Ignore source routed packets.
Log martian packets.
Disable IPv6 if not needed.
9. Remove unnecessary packages.
10. Set up log monitoring.
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)