# Post-Compromise Scope Assessment Methodology

## Standards Reference
NIST SP 800-61r3, PTES (Post-Exploitation), SANS FOR508/FOR572,
MITRE ATT&CK (T1078, T1539, T1528), FIRST CSIRT, OWASP WSTG

## Assessment Phases

### Phase 1 — Log Intake & Classification
Infostealer log parsing, data type identification.
Classification by source: browser credentials, cookies, autofill, crypto wallets, system tokens.
Batch correlation: link multiple credential sets to same victim or organization.

### Phase 2 — Credential Scope Assessment
Credential validation through graduated levels (L1-L4).
Service categorization: banking, crypto, email, social, corporate, infrastructure.
Priority scoring by exposure impact and organizational criticality.

### Phase 3 — Post-Compromise Scope Analysis
Determine full extent of compromise: what data was accessible, what persistence
mechanisms may exist, what lateral movement paths are available.
Required for accurate disclosure and remediation guidance.

### Phase 4 — Digital Asset & Data Exposure Impact
Cryptocurrency wallet exposure assessment.
Banking and payment credential scope.
Email cascade risk (password reset chains).
Sensitive data sampling for severity classification.

### Phase 5 — Remediation Priority Matrix & Disclosure
Account-by-account remediation priority.
Forced rotation execution plan.
Responsible disclosure notifications to affected organizations.
Monitoring recommendations for re-compromise detection.

---

## Credential Validation Levels (per IRB Section 4)

All validation documented in findings with: timestamp, endpoint, request, result.

### L1 — Identity Verification
**Purpose:** Confirm credential is active, identify owner.
**Authorization:** Auto-approved.

| Credential Type | Command | Expected Output |
|----------------|---------|-----------------|
| GitHub PAT/OAuth | `curl -sH "Authorization: token $TOK" https://api.github.com/user` | username, id, email, scopes |
| AWS keys | `aws sts get-caller-identity` | Account, ARN, UserId |
| IMAP/SMTP | `openssl s_client` + AUTH LOGIN | OK / authentication failed |
| SSH keys | `ssh -T -i key user@host` | auth success/fail (no shell) |
| API tokens | `GET /whoami` or `GET /me` | identity, permissions |
| Crypto wallets | Public explorer: address balance | balance, last tx |

### L2 — Scope Enumeration
**Purpose:** Determine what credential can access — required for disclosure severity.
**Authorization:** Auto-approved.

| Credential Type | Operations | Reveals |
|----------------|-----------|---------|
| GitHub | `GET /user/repos`, `GET /orgs`, `GET /user/keys` | Repo list (public+private), org membership, deploy keys |
| AWS | `s3 ls`, `iam list-roles`, `ec2 describe-instances` | Accessible buckets, IAM roles, infrastructure |
| IMAP | `LIST "" *` (mailbox enumeration) | Mailbox names, folder count |
| SSH | `ls -la`, `cat /etc/hostname`, `whoami`, `id` | Filesystem access, host identity, user context |
| API tokens | Permission/scope endpoint | Access level, rate limits |

### L3 — Write Verification
**Purpose:** Verify write/modify capability for critical severity scoring.
**Authorization:** Operator confirmation required before each operation.

| Credential Type | Operation | Cleanup | Severity if succeeds |
|----------------|-----------|---------|---------------------|
| GitHub | `POST /user/repos` (create private test repo) | Delete repo immediately | CRITICAL — write access to org |
| AWS | `s3 cp test.txt s3://bucket/scope-test/` | Delete object immediately | CRITICAL — data write access |
| SSH | `touch /tmp/.scope-test-$$` | `rm` immediately | HIGH — filesystem write |
| API | `POST` to test endpoint | Delete/revert | Depends on resource type |

### L4 — Privilege Assessment
**Purpose:** Determine admin/elevated access — maximum severity classification.
**Authorization:** Operator confirmation required.

| Credential Type | Operation | Reveals |
|----------------|-----------|---------|
| GitHub | `GET /orgs/{org}/members`, `GET /orgs/{org}/teams`, admin API | Org admin status, member list, team structure |
| AWS | `iam get-account-summary`, `iam list-attached-user-policies`, `organizations list-accounts` | Account-level admin, policy attachments, org scope |
| SSH | `sudo -l`, `cat /etc/sudoers`, `ls /root` | Privilege escalation paths |
| API | Admin endpoints, user management | System-level access |

---

## Post-Compromise Analysis (per PTES Post-Exploitation / SANS FOR508)

### Data Sampling (Phase 4)
**Purpose:** Verify what data credential exposes — determines disclosure severity (PII, financial, medical, etc.)
**Authorization:** Sampling auto-approved (small LIMITs, catalog/reference tables, COUNTs). Bulk extraction requires operator confirmation and an approved pipeline (see below).

| Credential Type | Operation | Limit | Purpose |
|----------------|-----------|-------|---------|
| GitHub (private repos) | `git clone` (shallow, depth=1) + first 20 lines of README/config | Single repo, minimal | Classify: source code, secrets, customer data |
| AWS S3 | `s3 cp` first object header (1KB) | Single object | Classify: PII, financial, backups, logs |
| IMAP | `FETCH 1 BODY[HEADER]` (envelope only) | First message header | Classify: personal, corporate, financial |
| SSH filesystem | `head -5` of accessible files in /home, /var | Read-only, 5 lines | Classify: application data, configs, secrets |
| Database access (sampling) | `SELECT * FROM information_schema.tables LIMIT 10`, `COUNT(*)`, `SELECT ... LIMIT 10-50` on reference/catalog tables | Schema + small samples | Classify: table names, row counts, reference data reveal data categories |
| Database access (bulk extraction) | `mysqldump` / `SELECT INTO OUTFILE` / full-table `SELECT *` on transactional/PII tables | No inherent limit | Full dataset for forensic/transaction-level analysis (fraud tracing, settlement verification, population-level disclosure) — **operator "go" + pipeline required** |

#### Phase 4 — Bulk Extraction (graduated, not prohibited)
Bulk extraction is a valid Phase 4 operation for disclosure-grade evidence and transaction-level forensic analysis. It is gated — not banned — because it materially raises disclosure scope, exfil volume, and recipient-notice obligations. The gate is procedural, not a blanket prohibition.

**Pre-conditions (all required before any bulk extraction):**
1. **Operator "go"** for the specific target + table set (same gate as L3 write).
2. **Scoped table list** — enumerate which tables/columns are in scope and why. No unscoped `SELECT *` across the whole DB.
3. **Pipeline defined** — transport (kubectl cp / kubectl logs / sidecar volume / direct egress), staging path, storage location, retention, destruction schedule. Pipeline must keep evidence in the IRB-isolated lab (no distribution).
4. **Disclosure impact note** — bulk extract changes the regulatory notification (BI/OJK/Kominfo/etc. move from "credential exposure" to "bulk PII/financial data exfiltrated"). Note this in the finding before extracting.
5. **OPSEC plan** — exfil timing, noise profile (a 25GB mysqldump through a pod logs differently than a 50-row SELECT), cleanup of pod + configmap + staging files.
6. **Evidence trail** — as with all Phase 4: `evidence/<name>.py` (script), `evidence/<name>-raw.json` (raw output or exfil manifest), `evidence/<name>.log` (audit trail). Manifest must record row counts, checksums, and storage path of the extracted dump.

**Sampling (default) vs. Bulk (gated) — decision rule:**
- Default to sampling. Sufficient for: severity classification, bank/partner ecosystem mapping, credential exposure documentation, regulatory notification triage.
- Escalate to bulk only when: (a) transaction-level forensic is required (e.g. tracing a specific settlement redirect or disbursement fraud pattern across N invoices), (b) disclosure recipient demands population-level evidence, or (c) schema-only sampling left a material gap that blocks disclosure.
- When in doubt: sample first, document the gap, request bulk for the specific residual gap. Do not bulk-extract "just in case."

### Lateral Movement Path Mapping (Phase 3)
**Purpose:** Map connected systems for remediation scope — what else is reachable from this credential.
**Authorization:** Auto-approved (enumeration only, no access attempt).

| Source | Technique | Reveals |
|--------|-----------|---------|
| GitHub repos | Scan for secrets in committed files (`.env`, configs, CI/CD) | Additional credentials, API keys, DB connection strings |
| AWS IAM | `iam list-access-keys`, cross-account roles | Other AWS accounts, shared infrastructure |
| SSH | `~/.ssh/known_hosts`, `~/.ssh/config`, `authorized_keys` | Connected hosts, trust relationships |
| Browser cookies | Domain analysis, cross-domain session tokens | SSO scope, linked applications |
| KeePass/Vault | Entry enumeration, URL fields | Full credential inventory per victim |

### Persistence Check (Phase 3)
**Purpose:** Determine if attacker established persistence before credential rotation would help.
**Authorization:** Operator confirmation for active checks.

| Check | Command | Indicates |
|-------|---------|-----------|
| GitHub deploy keys | `GET /repos/{repo}/keys` | Persistent repo access beyond PAT |
| GitHub webhooks | `GET /repos/{repo}/hooks` | Exfiltration channel |
| AWS IAM users | `iam list-users`, `iam list-access-keys --user` | Additional access keys created |
| SSH authorized_keys | `cat ~/.ssh/authorized_keys` | Backdoor SSH keys added |
| Cron/systemd | `crontab -l`, `systemctl list-units` | Scheduled persistence |
| Git config | `.git/config` hooks, post-receive | Repository-level persistence |

### Exfiltration Assessment (Phase 4)
**Purpose:** Determine what was already exfiltrated — remediation differs if data is already out.
**Authorization:** Auto-approved (log analysis only, no active probing).

| Source | Method | Reveals |
|--------|--------|---------|
| GitHub audit log | `GET /orgs/{org}/audit-log` (if admin) | Clone events, download events, API access |
| AWS CloudTrail | `lookup-events --lookup-attributes` | S3 GetObject, data access patterns |
| SSH auth.log | `grep sshd /var/log/auth.log` | Login history, source IPs, session duration |
| IMAP server logs | Server-side (if accessible) | Email read/forward events |

---

## Fresh Breach Intake — Log Cloud Pipeline

### Sources

Telegram log cloud каналы публикуют свежие инфостилер-логи ежедневно. Два типа:
- **ULP-дампы** (url:login:pass) — агрегированные списки из тысяч жертв (каналы типа @cloudxlog)
- **Полные архивы** (per-victim directories) — один архив = один заражённый хост, содержит все credentials, cookies, autofill, browser history, system info (каналы типа .boxed.pw / Daisy Cloud)

### Pipeline

```
1. Download     → boxed_pw_pipeline.py / tg_cloud_monitor.py
2. Extract      → unrar с паролем из .pass: поля
3. Parse        → aggregate_breach.py (All Passwords.txt → TSV)
4. Corp search  → grep по корпоративным таргетам
5. Victim pivot → ключевая методика (см. ниже)
```

### Victim Pivot Technique

Прямые credentials из log clouds к корпоративным целям в большинстве случаев **уже rotated** (401) или **недоступны** (timeout/DNS fail). Но инфостилер-дамп одной жертвы содержит ВСЕ её credentials — не только те, что уже expired.

**Методика:**
1. Найти credential к корпоративной цели (GitLab, Jenkins, VPN, admin panel)
2. Идентифицировать **жертву** — по email, username, или имени директории дампа
3. Извлечь **все остальные credentials** той же жертвы из полного архива
4. Среди них искать: SSH-ключи, VPN-конфиги, другие admin-панели, API-токены — которые НЕ были ротированы
5. Использовать найденное как альтернативный entry point в ту же организацию

### Практическое применение

Скрипт: `scripts/corp_search.py` (127 паттернов, 17 категорий).

**Поиск выполняется в 3 слоя:**

#### Слой 1 — Поиск по URL/домену (corp_search.py)

Прямой поиск корпоративных URL в credentials. Даёт: аккаунты игроков, клиентов, соискателей — low value, но подтверждает присутствие организации в утечках.

```bash
python3 scripts/corp_search.py                    # все паттерны
python3 scripts/corp_search.py -c infra_code      # только self-hosted GitLab/Gitea
python3 scripts/corp_search.py -p "mycompany.com" # ad-hoc поиск
```

#### Слой 2 — Поиск по email-доменам сотрудников

**Ключевое отличие от Слоя 1.** Инфостилер крадёт ВСЕ credentials жертвы. Если сотрудник компании залогинен где угодно (Netflix, Discord, Gmail) с корпоративным email — он попадает в дамп вместе со всеми корп. credentials.

Поиск по `@company.com` в email-поле выявляет **сотрудников** (не клиентов), чьи credentials могут включать VPN, Jenkins, GitLab, ADFS SSO, AWS Console — всё что было сохранено в браузере.

```bash
grep -hiE '@company\.com' findings/telegram_logs/cloudxlog/*_t7*.txt
```

**Пример (реализован):** CreditGlory/CreditSage — по Слою 1 найден только Grafana login (expired). По Слою 2 (@creditglory.com) найдены credentials к `/admins/sign_in` — **admin panel** с другим паролем, который не был rotated.

#### Слой 3 — Victim pivot (полный дамп)

После нахождения email сотрудника → поиск его полного дампа в per-victim архивах → извлечение ВСЕХ credentials.

```bash
# Найти дамп сотрудника в архивах
grep -rl 'employee@company.com' findings/telegram_logs/boxed_pw/extracted/

# Извлечь все credentials
cat "findings/telegram_logs/boxed_pw/extracted/SOURCE/VICTIM_DIR/All Passwords.txt"
```

#### Слой 2b — Поиск по портам

Инфостилер сохраняет URL как есть, включая нестандартные порты. Порт — сильный маркер self-hosted сервиса:

| Порт | Сервис | RCE? |
|:----:|--------|:----:|
| :9000/:9443 | Portainer | Да — docker exec |
| :8888 | Jupyter Notebook | Да — прямой code exec |
| :1880 | Node-RED | Да — function node |
| :5678 | n8n | Да — code node |
| :8080 | Jenkins/Guacamole | Да — Groovy console / RDP |
| :10000 | Webmin | Да — root shell |
| :8006 | Proxmox | Да — VM console |
| :3000 | Grafana/Gitea/n8n | Зависит |

```bash
# Поиск по портам
grep -hE ':9000/' findings/telegram_logs/cloudxlog/*_t7*.txt | grep -v 'android://'
grep -hE ':1880/' findings/telegram_logs/cloudxlog/*_t7*.txt
grep -hE ':10000/' findings/telegram_logs/cloudxlog/*_t7*.txt | grep -v 'android://'
```

**Пример (реализован):** 4 Webmin с root-доступом на публичных IP (128.199.x, 51.79.x, 34.126.x, 139.180.x) найдены через `:10000/` grep — не пойманы текстовым поиском по "webmin".

### Статистика по слоям (свежие данные 10-18 мая 2026)

| Слой | Метод | Находки | Active после проверки |
|------|-------|:-------:|:--------------------:|
| 1 — URL/домен | corp_search.py (127 паттернов) | 647K hits (41 корпоративных) | 0 |
| 2 — Email сотрудников | grep @company.com | 16 новых сотрудников 7 организаций | Pending |
| 3 — Victim pivot | Полный дамп жертвы | 15+ creds на жертву | Pending |

**Вывод:** Слой 1 даёт объём но low hit rate. Слой 2 выявляет сотрудников — ключевой для корпоративных targets. Слой 3 раскрывает полный профиль.

### Threat-Actor Priority Filtering & Tier-List Methodology

После intake → aggregate → corp_search → probe_rce → scan_secrets, каждый таргет
классифицируется по ценности для злоумышленника. Критерии:

1. **RCE potential** — даёт прямой shell на инфраструктуре компании (высший приоритет)
2. **Exfiltration value** — source code, IP, PII, secrets, financial data
3. **Company identity** — таргет должен быть идентифицирован (домен → WHOIS/SSL/web-search →
   организация, сектор, страна). Без идентификации компании ценность не определена.
4. **Private sector only** — gov/edu/military исключены (pursuit risk, политические не любят
   злоумышленники). Hosting-provider tenants (lemehost, zap-srv, vexyhost) помечаются отдельно.
5. **Pursuit-safe** — private-sector commercial entities, не government/critical-infrastructure

#### Tier-List

| Tier | Criteria | Examples |
|------|----------|----------|
| **S** | Direct RCE on self-hosted infra (LIVE + creds confirmed) | Jenkins Groovy, vCenter VM console, n8n code node, Coolify deploy, Harbor image push, phpMyAdmin root |
| **A** | Source-code & secrets exfil (self-hosted Git) + cloud admin | GitLab/Bitbucket self-hosted, AWS Console admin/root/IAM_ADMIN |
| **B** | DB admin (non-root), container admin, secrets mgmt | phpMyAdmin non-root, Portainer admin, Vault/ArgoCD |
| **C** | Remote access, mail, SSO, wiki (lateral value) | VPN/RDP, webmail, corporate SSO, Confluence |

#### Filtering pipeline

```
rce_candidates.tsv  →  exclude private IPs (10/172/192.168/127)
                    →  exclude gov/edu domains (.gov/.edu/.ac/univ-)
                    →  exclude official SaaS (jenkins.io, nexus.io, goharbor.io)
                    →  exclude CDN-hosted (cloudflare/AmazonS3/Vercel)
                    →  exclude gaming/consumer (poke-nexus, diamondnexus)
                    →  exclude hosting-provider tenants (lemehost, zap-srv, vexyhost)
                    →  identify company: SSL cert CN/Org + reverse-DNS + web-search
                    →  assign tier by service + RCE vector + company sector
```

#### Company identification (3-step)

1. **SSL certificate** — CN + organizationName из TLS handshake на :443
2. **Reverse DNS** — PTR record даёт hosting context (e.g. `mail.artoon.in` → Artoon)
3. **Web search** — `"domain.com" company` → LinkedIn/ZoomInfo/Crunchbase → sector, size, country

#### Pursuit-safe exclusion list

- `.gov.`, `.edu.`, `.ac.`, `univ-`, `nersc.gov`, `polito.it`, `grenoble`, `inria.fr`,
  `inrap.fr`, `epita.fr`, `isima.fr`, `utc.fr`, `utwente.nl`, `u-angers.fr`, `univ-nantes.fr`,
  `psu.ac.th`, `uajy.ac.id`, `sliit.lk`, `auburn.edu`, `duke.edu`, `kingston.ac.uk`,
  `aueb.gr`, `saclay`, `tau.ac.il`, `crio.do`
- Hosting providers (tenants, not companies): lemehost, zap-srv, zap-hosting, vexyhost,
  freakhosting, lwspanel, qovex, godlike, hosthavoc, bisecthosting, hstgr, contaboserver

### Ограничения

- Публичные log clouds содержат **преимущественно consumer-level** credentials (gaming, social, streaming)
- Корпоративные DevOps/admin credentials редки в публичных каналах — они уходят в **приватные клауды** ($200-1000/мес подписка)
- Свежесть данных: credentials из логов 7-14 дневной давности имеют ~60-80% rotation rate для корпоративных систем
- Слой 2 (email-домены) работает только если сотрудник использовал корпоративный email для личных/сторонних сервисов
- Банковские и financial credentials **не валидируются** (этические ограничения)

---

## Process
1. Log intake and classification (Phase 1)
2. Credential validation L1-L4 (Phase 2, graduated with operator confirmation)
3. Post-compromise scope: lateral paths, persistence, connected systems (Phase 3)
4. Data exposure and exfiltration assessment (Phase 4)
5. Fresh breach intake and cross-reference (continuous, see above)
6. Remediation priority matrix and disclosure preparation (Phase 5)
7. Responsible disclosure notifications to affected organizations
