Injection attacks are among the oldest and most dangerous vulnerabilities. An attacker inserts malicious code into input data, which the application then executes.
Types of injection¶
- SQL injection: Inserting SQL code into queries
- NoSQL injection: Manipulating MongoDB queries
- OS command injection: Executing system commands
- LDAP injection: Manipulating LDAP queries
SQL Injection — example¶
BAD¶
query = f”SELECT * FROM users WHERE username = ‘{username}’“
Attacker: username = admin’ –¶
CORRECT — parameterized query¶
cursor.execute(“SELECT * FROM users WHERE username = %s”, (username,))
NoSQL Injection¶
// BAD — MongoDB db.users.find({ username: req.body.username, password: req.body.password }); // Attacker: { “password”: { “$ne”: “” } } // CORRECT const username = String(req.body.username);
OS Command Injection¶
BAD¶
os.system(f”ping {user_input}”)
CORRECT¶
import subprocess subprocess.run([“ping”, “-c”, “4”, validated_ip], capture_output=True)
Prevention¶
- Parameterized queries (prepared statements)
- Validate inputs (whitelist > blacklist)
- ORM (SQLAlchemy, Prisma, Entity Framework)
- Least privilege DB accounts
- WAF + SAST in CI/CD
Key Takeaway¶
Never insert user input directly into queries. Parameterized queries and ORMs are the primary defense.