Show List

SQL injection

SQL Injection is a type of attack where malicious code is injected into an application's SQL statement input field, potentially allowing an attacker to access or manipulate the database behind the application. This is usually done by an attacker who tries to enter SQL code as part of their input, tricking the application into executing unintended SQL commands.

To prevent SQL Injection, you can use techniques such as parameterized queries, prepared statements, and input validation.

Parameterized queries use placeholders for user input in SQL statements, which are then passed as parameters to the database engine. This prevents the user input from being treated as executable code and eliminates the risk of SQL Injection attacks.

Here's an example of a parameterized query using Python and SQLite3:

python
Copy code
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() user_id = 1 username = 'Alice' cursor.execute('SELECT * FROM users WHERE id=? AND username=?', (user_id, username)) rows = cursor.fetchall() for row in rows: print(row) conn.close()

In this example, the SQL statement is written with placeholders ? instead of directly embedding user input into the statement. The user input is then passed as a separate parameter to the execute method, which takes care of properly escaping any special characters.

Prepared statements work similarly to parameterized queries, but they are precompiled by the database engine and cached for reuse. This can provide a performance boost over parameterized queries, especially in high-volume applications.

Here's an example of a prepared statement using PHP and MySQL:

php
Copy code
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id AND username = :username'); $stmt->execute(['id' => 1, 'username' => 'Alice']); $rows = $stmt->fetchAll(); foreach ($rows as $row) { echo $row['id'] . ' ' . $row['username'] . "\n"; }

In this example, the prepared statement is created with named placeholders :id and :username. The user input is then passed as an associative array to the execute method, which replaces the placeholders with the actual values.

Input validation involves checking user input for unexpected or malicious characters before allowing it to be processed by the application. This can be done using regular expressions, whitelisting, or blacklisting.

Here's an example of input validation using Java and JDBC:

java
Copy code
int userId = Integer.parseInt(request.getParameter("id")); String username = request.getParameter("username"); if (!username.matches("[A-Za-z0-9]+")) { throw new IllegalArgumentException("Invalid username"); } PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ? AND username = ?"); stmt.setInt(1, userId); stmt.setString(2, username); ResultSet rs = stmt.executeQuery(); while (rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("username")); }

In this example, the user input for id is converted to an integer using Integer.parseInt to ensure it is a valid integer. The user input for username is then checked using a regular expression to only allow alphanumeric characters. Finally, a prepared statement is used to execute the SQL query, passing the user input as parameters.

By using parameterized queries, prepared statements, and input validation, you can greatly reduce the risk of SQL Injection attacks in your applications.


    Leave a Comment


  • captcha text