TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › NoSQL, LDAP and Template Injection

NoSQL, LDAP and Template Injection

SQL is not the only language an application builds from user input. Document databases take query objects, directory servers take LDAP filters, e-mail and page templates take template syntax, and every one of them has its own injection. The pattern is always the one you know: data crosses into a place where it is interpreted as code or structure. This lesson shows three of them as small, self-contained Python models (no database servers, no network): operator injection into a MongoDB-style query, filter injection into LDAP, and template injection through Python's own str.format. Each is followed by its detection and fix. The full engines aren't run here, so treat these as faithful models of the mechanism, and test real products in your lab.

NoSQL operator injection

MongoDB-style queries are JSON documents. {"user": "alice", "password": "x"} matches equal values, but {"password": {"$ne": ""}} means "password not equal to empty", which is true for everyone. A login handler that copies JSON from the request body straight into the query lets the client send an object where the developer expected a string. The matcher below implements the few operators needed to show it.

python · try it yourself
import json

USERS = [{"user": "admin", "password": "h$admin-lab", "role": "admin"},
         {"user": "bob", "password": "h$bob-lab", "role": "user"}]

def matches(doc, query):                       # a tiny subset of MongoDB's query language
    for field, cond in query.items():
        value = doc.get(field)
        if isinstance(cond, dict):
            for op, arg in cond.items():
                if op == "$ne" and value == arg: return False
                if op == "$gt" and not (value is not None and value > arg): return False
                if op == "$regex" and not __import__("re").search(arg, str(value)): return False
        elif value != cond:
            return False
    return True

def login_vulnerable(body):
    q = json.loads(body)
    return [u["user"] for u in USERS if matches(u, {"user": q["user"], "password": q["password"]})]

def login_fixed(body):
    q = json.loads(body)
    user, pw = q.get("user"), q.get("password")
    if not isinstance(user, str) or not isinstance(pw, str):     # the fix: types, not just values
        return "400 user and password must be strings"
    return [u["user"] for u in USERS if matches(u, {"user": user, "password": pw})]

for body in ['{"user": "bob", "password": "h$bob-lab"}',
             '{"user": "admin", "password": {"$ne": ""}}',
             '{"user": {"$gt": ""}, "password": {"$gt": ""}}',
             '{"user": "admin", "password": {"$regex": "^h\\\\$a"}}']:
    print(f"{body:52} vulnerable: {login_vulnerable(body)!s:18} fixed: {login_fixed(body)}")
{"user": "bob", "password": "h$bob-lab"}             vulnerable: ['bob']            fixed: ['bob']
{"user": "admin", "password": {"$ne": ""}}           vulnerable: ['admin']          fixed: 400 user and password must be strings
{"user": {"$gt": ""}, "password": {"$gt": ""}}       vulnerable: ['admin', 'bob']   fixed: 400 user and password must be strings
{"user": "admin", "password": {"$regex": "^h\\$a"}}  vulnerable: ['admin']          fixed: 400 user and password must be strings

$ne logs in as admin with no password, $gt on both fields matches every user, and $regex turns the login into a blind oracle that leaks the stored value prefix by prefix (as in blind SQLi). Real passwords would of course be hashed, and the check done in code, which also kills this attack; the type check is the general fix for every field. Form-encoded bodies carry the same risk in frameworks that parse password[$ne]= into an object (PHP, Express with the extended query parser).

LDAP filter injection

Directory lookups use filters like (&(uid=alice)(objectClass=person)) (RFC 4515). Built by string concatenation, the characters *, (, ) and \ let input change the filter's structure. RFC 4515 defines escapes for them: \2a, \28, \29, \5c, and \00 for NUL.

python · try it yourself
def ldap_escape(value: str) -> str:
    out = []
    for ch in value:
        out.append({"\\": r"\5c", "*": r"\2a", "(": r"\28", ")": r"\29", "\0": r"\00"}.get(ch, ch))
    return "".join(out)

def build_filter(uid, safe):
    v = ldap_escape(uid) if safe else uid
    return f"(&(uid={v})(objectClass=person))"

for uid in ["alice", "*", "alice)(|(uid=*", "adm*"]:
    print(f"{uid!r:18} unsafe: {build_filter(uid, False):42} safe: {build_filter(uid, True)}")
'alice'            unsafe: (&(uid=alice)(objectClass=person))         safe: (&(uid=alice)(objectClass=person))
'*'                unsafe: (&(uid=*)(objectClass=person))             safe: (&(uid=\2a)(objectClass=person))
'alice)(|(uid=*'   unsafe: (&(uid=alice)(|(uid=*)(objectClass=person)) safe: (&(uid=alice\29\28|\28uid=\2a)(objectClass=person))
'adm*'             unsafe: (&(uid=adm*)(objectClass=person))          safe: (&(uid=adm\2a)(objectClass=person))

A bare * turns "find this user" into "find any user"; adm* is a wildcard oracle for enumerating names; the third input injects a new sub-filter. Escaped, all of them become literal characters in the value. Libraries do this for you: ldap3.utils.conv.escape_filter_chars, ldap.filter.escape_filter_chars in python-ldap, Spring LDAP's LdapEncoder.filterEncode. Distinguished names need a different escape (RFC 4514) than filters.

Template injection

Server-side template injection (SSTI) happens when user input becomes part of a template rather than a value passed into it. Template languages can call methods and read attributes, so the input can reach application internals; in Jinja2, Twig, Freemarker and others it often leads to code execution. Python's str.format is a small template language with attribute and index access, and it shows the mechanism without any template engine: a "customisable greeting" feature lets users write the format string.

python · try it yourself
import string

SECRET_KEY = "lab-only-signing-key-0042"           # what an attacker wants

class User:
    def __init__(self, name):
        self.name = name
    def display(self):
        return self.name.title()

def greeting_vulnerable(user_template, user):
    return user_template.format(user=user)          # the user controls the TEMPLATE

def greeting_fixed(user_template, user):
    values = {"name": user.display()}               # only plain strings, chosen by the server
    return string.Template(user_template).safe_substitute(values)

u = User("ana")
print(greeting_vulnerable("Hello {user.name}!", u))
print(greeting_vulnerable("{user.display.__globals__[SECRET_KEY]}", u))
print(greeting_vulnerable("{user.__class__.__init__.__globals__[__name__]}", u))
print(greeting_fixed("Hello $name!", u))
print(greeting_fixed("${user.display.__globals__}", u))
Hello ana!
lab-only-signing-key-0042
__main__
Hello Ana!
${user.display.__globals__}

Attribute access walked from the user object to its method, from the method to the module's globals, and read the signing key. The fixed version uses string.Template, which only substitutes $name from a dictionary of plain strings and never evaluates attributes; anything else stays literal text. The same rule applies to real engines: never build a template from user input (render_template_string(f"Hello {name}") in Flask is the classic bug); pass input as a variable into a fixed template, and if users must write templates, use a logic-less or sandboxed engine (Jinja2's SandboxedEnvironment, Liquid, Mustache).

How these injections are detected

Injection Testing probe (in scope) Log / code signal
NoSQL send {"$ne": null}, {"$gt": ""}, [$ne]= in forms; compare responses request bodies with $ keys; code passing req.body fields into find() without type checks
LDAP *, ), *)(uid=* in user names; a login or search that returns more results filters built with +/f-strings; LDAP server logs with wildcard-heavy filters from the app account
Template {{7*7}}, ${7*7}, <%= 7*7 %>, {7*7}; a 49 in the response means evaluation render_template_string, Template(user_input), .format( on user-provided strings; template errors in logs

How they are fixed

  • NoSQL: enforce types with a schema validator (Pydantic, Joi, Mongoose schemas with strict), strip or reject keys starting with $ (express-mongo-sanitize, Mongoose's sanitizeFilter option), never pass request objects directly as queries, avoid $where and server-side JavaScript.
  • LDAP: escape filter values with the library function, bind with a least-privilege account, validate user names against a pattern.
  • Templates: fixed templates with user data as variables; auto-escaping on; sandboxed or logic-less engines for user-authored templates.

Pitfalls

  • "NoSQL means no injection." The language changed, the mistake didn't.
  • Escaping for the wrong context: an LDAP filter escape doesn't protect a DN, and HTML escaping doesn't protect a template.
  • Client-side template injection (AngularJS {{…}} in server-rendered HTML) is the browser-side cousin; it executes in the user's origin, like XSS.

Practice

1. An Express login does db.users.findOne({user: req.body.user, pass: req.body.pass}). Write the minimal fix.

if (typeof req.body.user !== 'string' || typeof req.body.pass !== 'string') return res.sendStatus(400); before the query, then compare a password hash in code rather than in the query.

2. A page shows "Hello 49" when you register the name {{7*7}}. What does it tell you and what next?

The name is rendered as template code, not as a value: server-side template injection. In an authorised test, identify the engine from its syntax and error messages, report it as critical, and recommend passing the name as a variable to a fixed template.

Test yourself

Why did {"password": {"$ne": ""}} log in as admin?

  1. The password was empty
  2. The handler accepted an object, which the database interprets as an operator: 'not equal to empty' matches any password
  3. MongoDB has no passwords
  4. JSON parsing failed

Which LDAP filter characters must be escaped in values?

  1. Only quotes
  2. *, (, ), \ and NUL
  3. Only spaces
  4. = and ,

What is the root cause of template injection?

  1. Missing HTTPS
  2. User input becomes part of the template itself instead of a value passed into it
  3. Old Python versions
  4. Large templates

A harmless first probe for template injection is:

  1. Deleting a file
  2. {{7*7}} and looking for 49 in the response
  3. A long string
  4. A SQL quote