What is Injection? Security Vulnerability Basics

Share

TL;DR

Injection attacks happen when user input is treated as code or commands. SQL injection inserts database commands. Command injection runs shell commands. XSS injects JavaScript. Prevention is simple: never concatenate user input directly into queries or commands. Use parameterized queries and proper encoding.

The Simple Explanation

Your app takes user input and puts it somewhere: a database query, a command line, HTML output. If you do not properly separate "data" from "code," attackers can include their own code in their input. The system cannot tell the difference and executes the malicious code.

Types of Injection

TypeWhat Gets InjectedPrevention
SQL InjectionDatabase queriesParameterized queries
XSSJavaScript in HTMLOutput encoding
Command InjectionShell commandsAvoid shell, use APIs
LDAP InjectionDirectory queriesInput validation
Template InjectionTemplate engine codeSandbox templates

Common Prevention Pattern

SQL: Wrong vs Right

// WRONG: String concatenation const query = SELECT * FROM users WHERE id = ${userId};

// RIGHT: Parameterized query const query = 'SELECT * FROM users WHERE id = $1'; db.query(query, userId);

Command: Wrong vs Right

// WRONG: Shell command with user input exec(convert ${filename} output.png);

// RIGHT: Use library APIs, not shell const sharp = require('sharp'); await sharp(filename).toFile('output.png');

Key Principles

  • Never trust input: Treat all user data as potentially malicious
  • Use parameterization: Keep data separate from code
  • Encode output: Context-appropriate encoding for HTML, JS, etc.
  • Validate input: Reject unexpected formats and characters
  • Least privilege: Limit what database users and processes can do

What are the most common types of injection?

SQL injection (inserting SQL commands), XSS (injecting JavaScript), command injection (shell commands), LDAP injection, XPath injection, and template injection. SQL injection and XSS are the most common. The prevention is the same: never trust user input and use parameterized queries or proper encoding.

How do I prevent injection attacks?

Use parameterized queries or prepared statements for databases, never concatenate user input into queries or commands. Sanitize and validate all input. Use framework-provided escaping functions. Apply the principle of least privilege to database users and system accounts.

Why is injection ranked number one in OWASP Top 10?

Injection has historically been the most common and dangerous vulnerability category. It can lead to complete data breaches, data manipulation, and system compromise. It is also relatively easy to exploit and often results from simple coding mistakes like string concatenation with user input.

Find Injection Vulnerabilities

Scan your app for injection and other security issues.

Start Free Scan
Security Glossary

What is Injection? Security Vulnerability Basics