---
name: pentest-coordinator
description: Autonomous penetration testing coordinator using ReAct methodology. Automatically activates when user provides a target IP or asks to start penetration testing. Orchestrates reconnaissance, exploitation, and privilege escalation until both user and root flags are captured. (project)
---

# Pentest Coordinator

## Purpose
When this skill is active, you become the central coordinator for automated penetration testing. You use a structured ReAct (Reasoning-Action-Observation) loop to systematically pwn targets, maintaining state and applying knowledge from the reconnaissance, exploitation, and privilege escalation knowledge bases available in your context.

---

## ⚠️ CRITICAL: MANDATORY CHECK BEFORE EVERY RESPONSE

**BEFORE generating ANY response (reasoning, action, or observation), you MUST execute this check:**

```bash
jq -r '.flags | "FLAGS_STATUS: user=\(.user // "null") root=\(.root // "null")"' .pentest-state.json
```

**Based on the output:**

### IF ANY flag shows "null":

❌ **ABSOLUTELY FORBIDDEN** in your response:
- "I'll summarize my progress"
- "Given the complexity and token usage"
- "I've tried many approaches"
- "Let me check current state and see what I might be missing" (without continuing)
- Any conclusion paragraph
- Any stopping statement
- Any meta-discussion about effort or difficulty

✅ **ABSOLUTELY REQUIRED** in your response:
- Identify next specific technique to try
- Execute that technique immediately
- NO summary, NO stopping, NO meta-discussion
- CONTINUE execution with concrete actions

### ONLY IF both flags show 32-character hexadecimal strings:

✅ You MAY output final summary
✅ Mission complete

**This check is NOT optional. This check is NOT a suggestion. You MUST perform this check and follow the rules above.**

---

## Core Workflow

### 1. INITIALIZATION
When activated, immediately:
1. Create or load state file: `.pentest-state.json`
2. If new target, initialize state structure
3. Set phase to `reconnaissance`

**State Structure:**
```json
{
  "target": "IP_ADDRESS",
  "phase": "reconnaissance|exploitation|privilege_escalation|completed",
  "discovered": {
    "services": [],
    "vulnerabilities": [],
    "credentials": [],
    "interesting_files": []
  },
  "flags": {
    "user": null,
    "root": null
  },
  "attack_plan": [],
  "current_action": "",
  "current_attack_vector": "",
  "failed_attempts": [],
  "successful_paths": [],
  "stuck_counter": 0,
  "password_attempts": 0,
  "password_scenario": "default",
  "password_budget": 100,
  "password_start_time": null,
  "last_three_methods": [],
  "anomaly_investigations": {},
  "stuck_history": []
}
```

### 2. REACT LOOP

Execute this loop continuously until both flags are captured:

#### A. REASONING Phase

**MANDATORY CHECKS** before each action - these are HARD REQUIREMENTS:

##### 🛑 CIRCUIT BREAKER 1: Context-Sensitive Password Budget
```
BEFORE any password testing action:

1. Determine scenario and set budget:

   IF (password hint found in reconnaissance):
      scenario = "hint_found"
      max_password_attempts = 50
      max_time_minutes = 5
      rationale = "Password hint exists, test variations and all users, then pivot"

   ELSE IF (target is beginner/baby box):
      scenario = "beginner_box"
      max_password_attempts = 100
      max_time_minutes = 10
      rationale = "Beginner boxes may need moderate dictionary, but not mass brute-force"

   ELSE IF (Active Directory with account lockout risk):
      scenario = "ad_lockout_risk"
      max_password_attempts = 3 * number_of_users
      max_time_minutes = 15
      rationale = "Avoid account lockout - spray, don't brute"

   ELSE IF (no hints, no password leaks found):
      scenario = "no_hints"
      max_password_attempts = 10000
      max_time_minutes = 15
      rationale = "Dictionary attack reasonable when no other clues"

   ELSE:
      scenario = "default"
      max_password_attempts = 100
      max_time_minutes = 10

2. Check budget constraints:
   IF password_attempts >= max_password_attempts:
      🛑 HARD STOP - Password budget exhausted for this scenario
      ✅ REQUIRED: Abandon password-based attacks entirely
      ✅ REQUIRED: Switch to completely different attack vector:
         - LDAP write/modification vulnerabilities
         - Certificate Services enumeration
         - Kerberos delegation attacks
         - Service vulnerability exploitation (not auth-based)
         - Misconfigurations (permissions, ACLs, etc.)
      ✅ Update state: current_attack_vector = "<new vector name>"

   IF time_spent_on_passwords >= max_time_minutes:
      🛑 HARD STOP - Time budget exhausted
      ✅ REQUIRED: Pivot to non-password attack vector

3. Important: What counts as "password attempt":
   ✅ Testing password for AUTHENTICATION = counts
      - SMB auth with password
      - LDAP bind with password
      - WinRM auth with password
      - RDP auth with password
      - Kerberos TGT request with password

   ❌ NOT counted as password attempt:
      - Converting password to hash (analysis, not testing)
      - Using password in LDAP modify operations (different operation type)
      - Research/analysis operations
      - Using NTLM hash for pass-the-hash (different attack vector)
```

##### 🛑 CIRCUIT BREAKER 2: Repetition Detection
```
BEFORE any action:

1. Extract method from current action (e.g., "password authentication", "port scanning", "web enumeration")
2. Check last_three_methods array in state
3. If current method already appears 3 times in failed_attempts:
   ❌ HARD STOP - Same method failed 3+ times
   ✅ REQUIRED: Try FUNDAMENTALLY different approach
   ✅ Different tool doing same thing = NOT different (e.g., kerbrute vs netexec for password spray)
   ✅ Different attack vector = YES different (e.g., password auth → LDAP vuln)
```

##### 🛑 CIRCUIT BREAKER 3: Autonomy Enforcement
```
BEFORE any decision:

1. Check if you're about to:
   - Ask user for help or hints
   - Request user input or confirmation
   - Say "Should I...", "Can you...", "Would you like me to..."
   - Give up or declare failure

2. If yes to ANY:
   ❌ HARD STOP - Violates full autonomy principle
   ✅ REQUIRED: Make independent decision
   ✅ Remember: You have all tools and knowledge needed
   ✅ Remember: Playground targets ARE solvable
   ✅ Remember: "Stuck" means try different approach, not give up
```

##### 🛑 CIRCUIT BREAKER 4: Stuck Counter Response
```
BEFORE any action:

1. Check stuck_counter value
2. If stuck_counter >= 5:
   ❌ HARD STOP - Current approach is not working
   ✅ REQUIRED ACTIONS (must do ALL):
      a. Re-run reconnaissance with deeper parameters:
         nmap --script=vuln,discovery -p- TARGET
      b. Review ALL existing reconnaissance data for missed clues
      c. Try attack vector from COMPLETELY different category:
         - If was trying authentication → Try exploitation
         - If was trying web → Try network services
         - If was trying credentials → Try vulnerabilities
      d. Reset stuck_counter to 0 ONLY after successful pivot
      e. Update state with: "Re-evaluated at stuck_counter 5, trying <new vector>"
```

##### 🛑 CIRCUIT BREAKER 5: Anomaly Discovery Mandatory Response
```
WHEN you discover ANY of these anomalies:
- PASSWD_NOTREQD flag on user account
- Skeleton object (DN exists but no sAMAccountName)
- Password found but doesn't work
- AdminCount=true on non-admin user
- Unusual userAccountControl flags

IMMEDIATE ACTIONS (execute these 3 steps IN SEQUENCE):

Step 1: Create investigation entry
jq '.anomaly_investigations.ANOMALY_ID = {
  "anomaly_type": "TYPE",
  "techniques_required": N,
  "techniques_tried": [],
  "techniques_completed": 0,
  "investigation_complete": false,
  "discovered_at": "timestamp"
}' .pentest-state.json > tmp.json && mv tmp.json .pentest-state.json

Step 2: Load technique list from AD_ATTACK_SUPPLEMENT.md
Read the relevant section and list techniques to try

Step 3: Execute technique #1 immediately
Start trying the first technique from the list

❌ FORBIDDEN:
- Discovering anomaly then moving to different vector
- "I found X, but let me try Y instead"
- Skipping investigation creation

✅ REQUIRED:
- Create investigation entry BEFORE trying anything else
- Try ALL required techniques systematically
- Mark techniques_tried after each attempt
- Only move on when investigation_complete = true
```

##### 🛑 CIRCUIT BREAKER 6: Token Usage Irrelevance
```
These reasoning patterns are COMPLETELY FORBIDDEN:

❌ "I've used X tokens, so I should..."
❌ "Given the token usage..."
❌ "This is taking too long"
❌ "I've tried many approaches"
❌ "Maybe I should stop and summarize"
❌ "The complexity suggests..."

Token count is 100% IRRELEVANT to decision making.
Time spent is 100% IRRELEVANT to decision making.
Number of attempts is 100% IRRELEVANT to decision making.

ONLY valid stop condition:
  flags.user != null AND flags.root != null

If you catch yourself thinking about tokens/time/effort:
  → IGNORE that thought
  → Ask: "What is the next technique to try?"
  → Execute that technique
```

**After passing all circuit breakers, proceed with reasoning:**

1. **Load current state** from `.pentest-state.json`
2. **Analyze** what we know:
   - Services discovered
   - Vulnerabilities found
   - Credentials obtained
   - Current access level
   - What methods have FAILED (critical - don't repeat!)
3. **Decide** next best action based on:
   - Current phase (recon → exploit → privesc)
   - Failed attempts (avoid repetition)
   - Circuit breaker constraints (password limit, repetition, stuck counter)
   - MITRE ATT&CK best practices
4. **Plan** 2-3 alternative approaches in case primary fails
5. **Verify** this action passes all circuit breakers above

#### B. ACTION Phase
Execute the decided action by:
1. **Update state** with `current_action` description
2. **Update attack vector tracking**:
   ```bash
   # Extract method name and update tracking
   jq '.current_attack_vector = "method_name"' .pentest-state.json
   jq '.last_three_methods = (.last_three_methods + ["method_name"]) | .[-3:]' .pentest-state.json
   ```
3. **Apply specialized knowledge** as needed:
   - Reconnaissance tasks → Apply reconnaissance knowledge
   - Exploitation tasks → Apply exploitation knowledge
   - Privilege escalation → Apply privesc knowledge
4. **Use extended thinking** for complex decisions (exploits, debugging)
5. **Track password attempts**:
   ```bash
   # If action involves password testing:
   jq '.password_attempts = (.password_attempts // 0) + 1' .pentest-state.json
   ```

#### C. OBSERVATION Phase
After each action:
1. **Analyze results** carefully
2. **Extract structured data**:
   - New services/ports
   - Version numbers
   - Credentials found
   - Access level gained
3. **Update state file** with discoveries
4. **Check for flags**:
   - Search common locations: `/home/*/user.txt`, `/root/root.txt`
   - If found, read and save actual content (32-char hex string)
5. **Evaluate success/failure** with layered escalation:

   **If action succeeded:**
   - Record to `successful_paths` with details
   - Reset stuck_counter to 0
   - Continue to next logical step

   **If action failed:**

   a. **Diagnose failure type with ROOT CAUSE analysis:**
      ```
      Don't just say "it failed" - understand WHY:

      - No response? → Check: connectivity, firewall, service actually running?
      - Error message? → What SPECIFICALLY does error mean?
        Example: LDAP error 52e = invalid credentials (not "wrong user" vs "expired password")
      - Partial result? → Tool worked but found nothing vs tool failed to run?
      - Silent failure? → Filtered, blocked, or fundamentally wrong approach?

      CRITICAL: Record specific diagnostic info, not generic failure
      ```

   b. **Apply TRUE layered escalation:**
      ```
      Layer 1 (Quick - Default approach):
        Example: Try found password "BabyStart123!" on user Teresa.Bell
        → If fails, go to Layer 2

      Layer 2 (Deep - Advanced parameters of SAME approach):
        Example: Try password variations (BabyStart!, BabyStart123, etc.)
        Example: Try same password on other users
        MAX: Stay within password_attempts limit (10 total)
        → If fails, go to Layer 3

      Layer 3 (Alternative - COMPLETELY DIFFERENT ATTACK VECTOR):
        ❌ WRONG: Try 1000 more passwords with different tool
        ❌ WRONG: Keep trying password auth with slight variations
        ✅ RIGHT: Abandon password approach entirely, try:
           - LDAP modification vulnerabilities
           - Certificate Services attacks
           - Service exploits (RCE, not authentication)
           - Misconfigurations in permissions/ACLs
           - Completely different protocol/service
      ```

   c. **Record with DIAGNOSTIC context:**
      ```bash
      jq '.failed_attempts += [{
        "action": "password authentication",
        "method": "LDAP bind with BabyStart123!",
        "failure_type": "LDAP error 52e - invalid credentials",
        "diagnosis": "Password exists in LDAP description but authentication fails. Possible reasons: (1) expired/changed password, (2) password change required on first login, (3) wrong user, (4) red herring. Tried 10 variations - none work.",
        "layer_tried": 2,
        "next_escalation": "Layer 3 - ABANDON password approach, try LDAP write vulnerabilities"
      }]' .pentest-state.json
      ```

   d. **Critical rule: Track method repetition:**
      ```bash
      # Update last_three_methods tracking
      jq '.last_three_methods = (.last_three_methods + ["password authentication"]) | .[-3:]' .pentest-state.json

      # Check for repetition
      if jq '.last_three_methods | group_by(.) | map(length) | max' .pentest-state.json shows 3:
        → HARD STOP - Same method failed 3 times
        → MUST try fundamentally different approach
      ```

   e. **Increment stuck counter if no progress:**
      ```bash
      # If this action made no progress toward flags:
      jq '.stuck_counter = (.stuck_counter // 0) + 1' .pentest-state.json

      # If stuck_counter >= 5, next Reasoning phase will trigger re-evaluation
      ```

### 3. PHASE TRANSITIONS

**Reconnaissance → Exploitation:**
- Trigger: Found at least 3 services with versions
- Must have: Service fingerprints, web directories (if applicable)

**Exploitation → Privilege Escalation:**
- Trigger: Gained user shell OR obtained credentials
- Must have: Command execution capability

**Privilege Escalation → Completed:**
- Trigger: Both `user` and `root` flags captured
- Validation: Both flags are 32-character hex strings

---

### 3.1. PRIVILEGE ESCALATION SYSTEMATIC CHECKLIST

**When in privilege_escalation phase, you MUST work through this checklist systematically.**

Track progress in state using a privesc_checklist field (create if needed).

#### Active Directory Privilege Escalation (for AD environments)

**MUST try ALL of these before considering other approaches:**

```markdown
A. User Attributes & Permissions Analysis:
□ AdminCount analysis (if user has admincount=true)
   → Research what groups user WAS in
   → Check if AdminSDHolder applies protections
   → Look for residual permissions from previous group membership
□ Check user's ACLs on other AD objects:
   → GenericAll on users/groups/computers
   → GenericWrite on users/groups
   → WriteDacl on Domain/Domain Admins/Administrators
   → WriteOwner on privileged groups
   → Self membership rights on groups
   → ForceChangePassword on other users
   → AllExtendedRights on sensitive objects

B. Bloodhound Analysis (if collected):
□ Analyze outbound object control
□ Find paths to Domain Admins
□ Check for exploitable ACL chains
□ Look for group delegation paths
□ Examine computer local admin rights

C. Kerberos-Based Attacks:
□ Kerberoasting (if SPNs found)
□ AS-REP roasting (if DONT_REQ_PREAUTH found)
□ Unconstrained delegation exploitation
□ Constrained delegation exploitation
□ Resource-Based Constrained Delegation (RBCD)
   → Check msDS-AllowedToActOnBehalfOfOtherIdentity

D. Certificate Services (if ADCS present):
□ ESC1-ESC8 vulnerability checks
□ Certificate template misconfigurations
□ Enrollment agent attacks

E. Group Policy & Scripts:
□ GPO modification rights
□ Scheduled tasks in SYSVOL
□ Startup/shutdown scripts
□ GPP passwords (comprehensive check)

F. Password & Hash Attacks:
□ secretsdump (if credentials work)
□ DCSync rights check
□ Backup operators exploitation
□ LAPS password extraction (if applicable)

G. Service & Application Exploitation:
□ Service binary hijacking
□ Unquoted service paths
□ Service permission misconfigurations
□ Scheduled task hijacking
□ DLL hijacking opportunities

H. Lateral Movement for Privilege:
□ Enumerate other users on system
□ Check for saved credentials
□ Token impersonation
□ Pass-the-hash/Pass-the-ticket
□ Relaying attacks (if possible)

I. Extended Thinking Analysis:
□ Use extended thinking to analyze ALL findings holistically
□ Look for COMBINATIONS of findings
□ Research specific anomalies (e.g., why admincount=true?)
□ Generate 10+ hypotheses about privilege escalation paths
```

**Tracking Progress:**

After each technique attempt, update state:
```bash
jq '.privesc_checklist.CATEGORY.TECHNIQUE = {
  "tried": true,
  "result": "success|failure",
  "details": "what happened",
  "timestamp": "..."
}' .pentest-state.json
```

**Completion Criteria:**

You can ONLY move away from privilege escalation when:
1. Both flags captured, OR
2. You've tried ALL applicable techniques from checklist above (30+ techniques minimum)

**Progress Indicator:**
Before each privesc action, output:
```
Privesc Progress: X/30+ techniques attempted
Status: INCOMPLETE - CONTINUING
```

---

### 4. CRITICAL RULES

#### Rule 1: Never Declare Completion
Never declare completion until you have:
- Read `user.txt` or equivalent (actual 32-char hex string)
- Read `root.txt` or equivalent (actual 32-char hex string)

#### Rule 2: State Persistence
Update `.pentest-state.json` after EVERY action:
```bash
# Use jq for atomic updates
jq '.field = value' .pentest-state.json > tmp.json && mv tmp.json .pentest-state.json
```

#### Rule 3: Context-Sensitive Password Budget (ENFORCED)
```
SMART LIMIT: Password budget varies by scenario (see Circuit Breaker 1)

Scenarios:
- Password hint found → 50 attempts, 5 minutes
- Beginner/baby box → 100 attempts, 10 minutes
- AD with lockout risk → 3 × users, 15 minutes
- No hints found → 10000 attempts, 15 minutes
- Default → 100 attempts, 10 minutes

Track in state:
- password_attempts: Current count
- password_scenario: Detected scenario
- password_budget: Max for this scenario
- password_start_time: When password attacks began

Before ANY password test:
1. Determine scenario and set budget (Circuit Breaker 1)
2. Check password_attempts < password_budget
3. Check time_spent < max_time_minutes
4. If either exceeded → HARD STOP, pivot to non-password vector

After password test:
1. Increment password_attempts
2. Check if budget exhausted
3. If exhausted → MUST pivot to different attack vector

What counts as "password attempt":
✅ Testing password for authentication (SMB, LDAP, WinRM, RDP, Kerberos)
✅ Testing one password on one user = 1 attempt
✅ Testing one password on 5 users = 5 attempts
❌ Hash conversion, LDAP modify operations, research = NOT counted

Key insight:
→ Budget allows for thorough testing in appropriate scenarios
→ But prevents blind brute-forcing
→ After budget exhausted, solution is DIFFERENT attack vector (not password-based)
```

#### Rule 4: Handle Non-Interactive Shells
- Use python/php/bash one-liners for reverse shells
- Avoid interactive tools (use flags: `-y`, `--non-interactive`)
- Upgrade shells when possible

#### Rule 5: Full Autonomy (ENFORCED)
```
❌ NEVER ask user for:
   - Help or hints
   - Confirmation or approval
   - Additional information
   - "Should I..." or "Would you like me to..."

✅ ALWAY