Code review

String concatenation

One of the possible sinks in code when it comes to SQL Injection is using string concatenation instead of parametrized queries:

Vulnerable code samples:

  • Pasting the data directly from parameter without prepared statements

$id = $_GET['id']; // User input taken directly from GET request

$query = "SELECT * FROM users WHERE id = '$id'";
  • Concatenation

$username = $_GET['username'];
$password = $_GET['password'];

// Vulnerable SQL query using string concatenation (username and password)
$query = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'";

Non-vulnerable code sample:

$id = $_GET['id'];

$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

Usually web applications have huge amounts of code. That is why we often have to use regexes in order to search for queries.

Sample regex searching (in notepad++)

More regex payloads

In the table below you can find specific queries with concatenation usage inside the query.

Purpose

Regex Pattern

SELECT queries

(?i)\bselect\b\s+.+\s+\bfrom\b

INSERT queries

(?i)\binsert\b\s+\binto\b\s+\w+

UPDATE queries

(?i)\bupdate\b\s+\w+\s+\bset\b

DELETE queries

(?i)\bdelete\b\s+\bfrom\b\s+\w+

CREATE statements

`(?i)\bcreate\b\s+(table

DROP statements

`(?i)\bdrop\b\s+(table

ALTER statements

`(?i)\balter\b\s+(table

TRUNCATE statements

(?i)\btruncate\b\s+\btable\b

EXEC/EXECUTE calls

`(?i)\b(exec

MERGE statements

(?i)\bmerge\b\s+\w+\s+\busing\b

Last updated