Lesson 10 of 10
Practice & Quiz - Penetration Testing
Test your pentesting knowledge: recon methodology, vulnerability exploitation, privilege escalation, report writing, and bug bounty with a practical automated recon exercise and 5 quiz questions.
Practical Exercise - Automated Recon & Vulnerability Discovery
#!/usr/bin/env python3
"""
Automated Pentesting Recon Framework
For authorized testing only. Always obtain written permission before testing.
"""
import asyncio, subprocess, json, socket, ssl, datetime
from pathlib import Path
import httpx, dns.resolver
TARGET = 'example.com' # ← REPLACE with authorized target
OUTPUT_DIR = Path(f'pentest_{TARGET}_{datetime.date.today()}')
OUTPUT_DIR.mkdir(exist_ok=True)
# ─── Phase 1: Passive Reconnaissance ─────────────────────────
async def passive_recon(domain: str) -> dict:
"""OSINT gathering without direct target interaction."""
results = {'domain': domain, 'subdomains': [], 'emails': [], 'dns': {}}
# DNS enumeration
record_types = ['A', 'AAAA', 'MX', 'NS', 'TXT', 'CNAME', 'SOA']
resolver = dns.resolver.Resolver()
for rtype in record_types:
try:
answers = resolver.resolve(domain, rtype)
results['dns'][rtype] = [str(r) for r in answers]
except Exception:
pass
# Certificate Transparency logs (crt.sh) - passive subdomain discovery
async with httpx.AsyncClient(timeout=10) as client:
try:
resp = await client.get(f'https://crt.sh/?q=%.{domain}&output=json')
if resp.status_code == 200:
certs = resp.json()
subdomains = set()
for cert in certs:
name = cert.get('name_value', '')
for sub in name.split('\n'):
if sub.endswith(f'.{domain}') or sub == domain:
if '*' not in sub:
subdomains.add(sub.lower())
results['subdomains'] = sorted(subdomains)
print(f'Found {len(subdomains)} subdomains via CT logs')
except Exception as e:
print(f'CT log error: {e}')
return results
# ─── Phase 2: Active Scanning ─────────────────────────────────
async def scan_web_headers(url: str) -> dict:
"""Check security headers and TLS configuration."""
findings = {'url': url, 'missing_headers': [], 'tls_issues': [], 'info_disclosure': []}
SECURITY_HEADERS = {
'strict-transport-security': 'HSTS not set - HTTPS not enforced',
'content-security-policy': 'CSP missing - XSS mitigation absent',
'x-frame-options': 'Clickjacking protection missing',
'x-content-type-options': 'MIME sniffing protection missing',
'referrer-policy': 'Referrer leakage not controlled',
'permissions-policy': 'Browser features not restricted',
}
async with httpx.AsyncClient(verify=True, timeout=10, follow_redirects=True) as client:
try:
resp = await client.get(url)
headers = {k.lower(): v for k, v in resp.headers.items()}
for header, issue in SECURITY_HEADERS.items():
if header not in headers:
findings['missing_headers'].append({'header': header, 'issue': issue})
# Information disclosure
if 'server' in headers:
findings['info_disclosure'].append(f'Server: {headers["server"]}')
if 'x-powered-by' in headers:
findings['info_disclosure'].append(f'X-Powered-By: {headers["x-powered-by"]}')
except Exception as e:
findings['error'] = str(e)
return findings
# ─── Phase 3: Vulnerability Checks ────────────────────────────
async def check_common_vulns(base_url: str) -> list[dict]:
"""Check for common misconfigurations."""
vulns = []
sensitive_paths = [
('/.env', 'Environment file exposed - may contain secrets'),
('/.git/HEAD', 'Git repository exposed - source code accessible'),
('/phpinfo.php', 'PHP info page exposed - server config disclosed'),
('/wp-admin/', 'WordPress admin panel exposed'),
('/admin', 'Admin panel accessible'),
('/api/v1/users', 'User API may be unauthenticated'),
('/swagger.json', 'API documentation exposed'),
('/actuator/health', 'Spring Boot actuator exposed'),
]
async with httpx.AsyncClient(verify=True, timeout=10, follow_redirects=False) as client:
for path, description in sensitive_paths:
try:
resp = await client.get(f'{base_url}{path}')
if resp.status_code in [200, 301, 302]:
vulns.append({
'severity': 'HIGH' if 'env' in path or 'git' in path else 'MEDIUM',
'path': path,
'description': description,
'status': resp.status_code,
})
print(f'🚨 [{resp.status_code}] {path} - {description}')
except Exception:
pass
return vulns
# ─── Generate Report ──────────────────────────────────────────
def generate_report(findings: dict, output_path: Path):
report = {
'metadata': {
'target': findings.get('target'),
'date': datetime.datetime.now().isoformat(),
'tester': 'Automated Recon Tool v1.0',
},
'findings': findings,
'risk_summary': {
'critical': 0, 'high': 0, 'medium': 0, 'low': 0, 'info': 0
}
}
(output_path / 'report.json').write_text(json.dumps(report, indent=2))
print(f'\nReport saved to {output_path / "report.json"}')
async def main():
print(f'Starting recon for: {TARGET}')
print('=' * 50)
recon = await passive_recon(TARGET)
headers = await scan_web_headers(f'https://{TARGET}')
vulns = await check_common_vulns(f'https://{TARGET}')
generate_report({'target': TARGET, 'recon': recon, 'headers': headers, 'vulns': vulns}, OUTPUT_DIR)
# asyncio.run(main()) # Uncomment to run (authorized targets only)Module Quiz
What is the difference between passive reconnaissance and active scanning in a penetration test?
Tip
Tip
Practice Practice Quiz Penetration Testing in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Penetration Testing from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Penetration Testing is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Finished this lesson?