---
title: Prevent LDAP injection
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Prevent LDAP injection
---

# Prevent LDAP injection

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `python-flask/ldap-injection`

**Language:** Python

**Severity:** Error

**Category:** Security

**CWE**: [90](https://cwe.mitre.org/data/definitions/90.html)

## Description{% #description %}

LDAP queries that use unsanitized inputs might allow attackers to inject unwanted elements into the query, allowing attackers to read or modify sensitive data, run code, and perform other unwanted actions.

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```python
from flask import Flask, request

app = Flask(__name__)

@app.route("/login", methods=["POST"])
def login():
    data = request.get_json()
    username = data.get("username", "")
    password = data.get("password", "")

    # Not compliant
    ldap_filter = f"(&(uid={username})(userPassword={password}))"

    return f"Filter: {ldap_filter}"
```

## Compliant Code Examples{% #compliant-code-examples %}

```python
from flask import request
import ldap

app = Flask(__name__)

@app.route("/login", methods=["POST"])
def login():
    data = request.get_json()
    username = ldap.filter.escape_filter_chars(data.get("username", ""))
    password = ldap.filter.escape_filter_chars(data.get("password", ""))

    ldap_filter = f"(&(uid={username})(userPassword={password}))"

    return f"Filter: {ldap_filter}"
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 