Link Search Menu Expand Document

NoSQL Injection in Java

Java frameworks with Elasticsearch

Vulnerable example

Elasticsearch allows database queries to be performed in many ways, one of which is by using search templates. This feature allows for the specification of partial queries using the Mustache template language, which is then filled with proper values right before the execution.

Care must be taken though because by using the {{{...}}} notation, Mustache will not perform any escaping of the (possibly) user-supplied value. A malicious user might escape the JSON string and alter the query semantics. As an example, consider the following Elasticsearch query that filters according to a value provided by the user:

{
    "query": {
        "match": {
            "somefield": {
                "query": "{{{somevalue}}}"
            }
        }
    }
}

By replacing somevalue in the snippet above with the payload ","zero_terms_query":"all, it is possible to transform the query into a match-all query, thus nullifying the filter:

{
    "query": {
        "match": {
            "somefield": {
                "query": "",
                "zero_terms_query": "all"
            }
        }
    }
}

Prevention

To avoid this threat, the developer should opt for the use of the {{...}} Mustache construct when dealing with untrusted data, as it properly escapes double quotes. The above query should be re-written as:

{
    "query": {
        "match": {
            "somefield": {
                "query": "{{somevalue}}"
            }
        }
    }
}

References

CWE-943 - Improper Neutralization of Special Elements in Data Query Logic OWASP - NoSQL Injection