SQL Injection - PostgreSQL - Time Based
Reference
Plugin Id: 40022 | CWE: 89
Resources
Remediation
-
Use built-in Object Data Models: Instead of directly passing user input to the SQL server, use built-in Object Data Models (ODMs) or Object Relational Mapping (ORM) frameworks to gather and manipulate data. These frameworks provide methods and functions that automatically sanitize user input and prevent SQL injection vulnerabilities.
-
Parameterized queries: Instead of concatenating user input directly into SQL statements, use parameterized queries in the language framework. Parameterized queries separate the SQL code from the user input, preventing SQL injection attacks. Here’s an example in Python using the psycopg2 library:
import psycopg2 # Establish a connection to the PostgreSQL database conn = psycopg2.connect(database="mydatabase", user="myuser", password="mypassword", host="localhost", port="5432") # Create a cursor object cursor = conn.cursor() # Execute a parameterized query query = "SELECT * FROM users WHERE username = %s AND password = %s" cursor.execute(query, (username, password)) # Fetch the results results = cursor.fetchall() # Close the cursor and connection cursor.close() conn.close()
In this example, the
username
andpassword
variables are passed as parameters to theexecute
method, ensuring that they are properly sanitized. -
Input validation: Implement input validation on the server-side to ensure that user input meets the expected format and constraints. This can include checking for valid data types, length limits, and using regular expressions to validate input. By validating input before using it in SQL statements, you can prevent SQL injection attacks.
About
Most SQL injection problems occur when user input is not properly sanitized and is directly passed to the back-end SQL server. This allows attackers to inject malicious SQL commands into the application.
Risks
SQL injection vulnerabilities can lead to various risks, including:
-
Enumeration of column names: Attackers can use SQL injection to gather information about the database structure, such as the names of tables and columns. This information can be used for further attacks or unauthorized access.
-
Data retrieval: Attackers can manipulate SQL queries to retrieve sensitive data from the database, such as usernames, passwords, or other confidential information.
-
Remote code execution: In some cases, SQL injection vulnerabilities can be exploited to execute arbitrary code on the server, leading to complete compromise of the application and underlying system.
Most StackHawk tests for SQL injection are time-based, where the scanner attempts to make the SQL server perform time-based actions and increase the response time of the application.