1. Home
  2. Explore
  3. Computer Science
  4. SQL Injection Dangers

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

SQL Injection Dangers

🔒 SQL Injection Vulnerabilities: A Deep Dive

SQL injection remains a critical security vulnerability even in modern web applications, often leading to severe consequences such as data breaches, reputational damage, and legal penalties. Understanding how these attacks work and how to prevent them is paramount for any web developer.

🚨 The Danger of SQL Injection

SQL injection attacks occur when an attacker inserts or "injects" malicious SQL code into an input field, which is then executed by the database. If successful, this can lead to:

  • Data Exposure: Usernames, passwords (even hashed ones), and other sensitive information can be stolen.

  • Data Manipulation: Attackers can modify or delete data within the database.

  • System Compromise: In some cases, attackers can gain control over the server.

  • Legal and PR Issues: Data protection acts make such breaches illegal, resulting in fines and significant damage to a company's reputation.

Warning: Attempting SQL injection on unauthorized systems is illegal and can lead to severe penalties, including imprisonment. Demonstrations should only be performed on personal, authorized systems.


🛠️ Anatomy of a Vulnerable Website (Example: A "Bad" Hardware Shop)

Consider a simple e-commerce website, like a "bad" hardware shop, built with PHP and a MySQL database. When a user searches for a product (e.g., "hammer"), the website constructs an SQL query on the backend.

📝 How a Search Query Works (Normally)

  1. User Input: A user types "hammer" into a search box and clicks submit.

  2. POST Request: A POST request is sent to the PHP server.

  3. PHP Processing: PHP receives the input and constructs an SQL query, such as SELECT * FROM products WHERE name LIKE '%hammer%'.

  4. Database Query: The query is sent to the database.

  5. Results Display: The database returns matching rows, which PHP then displays on the screen.

💥 How SQL Injection Exploits This

The problem arises when the user input is not properly sanitized or escaped. If a special SQL command character (like a single quote ') is entered, the constructed SQL query can become malformed.

  • Malformed Query: The server might interpret the input as part of the SQL command itself, rather than just data.

  • Multiple Queries: The input could allow an attacker to execute entirely new, malicious SQL queries alongside the original one.


🔍 Identifying Vulnerability: The Single Quote Test

The first step in determining if a textbox is vulnerable to SQL injection is to input a single quote (').

  • Vulnerable Response: If the server returns a generic "server error" or an unexpected error message, it's a strong indicator of vulnerability. This means the single quote broke the SQL query syntax.

    • Example: SELECT * FROM products WHERE name LIKE '%'hammer%'' – the extra quote creates an invalid string.

  • Secure Response: A secure application would either:

    • Return no products (if no product name contains a single quote).

    • Properly escape the single quote, treating it as a literal character within the search term.


🧠 Crafting the Attack: Understanding the Backend Query

To exploit a vulnerable system, an attacker needs to hypothesize the structure of the backend SQL query.

💡 Query Hypothesis

Based on search behavior (e.g., searching for "amme" finds "hammer"), it's likely the query uses wildcards:

SELECT ? FROM ? WHERE ? LIKE '%[USER_INPUT]%'

  • ?: Placeholders for unknown column names, table names, or specific conditions.

  • [USER_INPUT]: The part controlled by the attacker.

🎨 Visualizing the Malformed Query

Using a text editor with SQL syntax highlighting can help visualize how an injected character breaks the query.

  • Original: SELECT ... WHERE column LIKE '%hammer%'

  • Injected ('): SELECT ... WHERE column LIKE '%'hammer%''

    • The syntax highlighter would show the second ' as unquoted, indicating a syntax error.


🎯 Targeting the Database Management System (DBMS)

Different DBMS (MySQL, PostgreSQL, SQL Server) have slightly different SQL dialects. Identifying the specific DBMS allows for more targeted attacks.

⏳ Time-Based Blind SQL Injection

One method to identify the DBMS and extract information, even without direct output, is time-based blind SQL injection. This relies on observing the server's response time.

  1. Neutralize the Remaining Query: Add a semicolon (;) to end the current query and a comment (-- or #) to ignore the rest of the original query.

    • Example Input: ' ; --

    • Resulting Query: SELECT ... WHERE column LIKE '%'; -- %'

    • This often results in all products being returned, as the LIKE '%' acts as a wildcard.

  2. Introduce a Sleep Function:

    • MySQL: Use the SLEEP(seconds) function.

      • Example Input: hammer' AND SLEEP(2)='1

      • Hypothesized Query: SELECT ... WHERE column LIKE '%hammer%' AND SLEEP(2)='1'

    • If the query processes two "hammer" items and each triggers a SLEEP(2), the total response time will be 4 seconds.

    • If the server does not sleep, it indicates that MySQL is likely not the DBMS, and the attacker would try equivalent functions for other DBMS (e.g., WAITFOR DELAY for SQL Server).


🚀 Extracting Data with UNION Attacks

Once the DBMS is identified (e.g., MySQL) and it's confirmed that output can be displayed, the next step is to use the UNION operator to extract sensitive information.

🧩 The UNION Operator

The UNION operator combines the result sets of two or more SELECT statements. For UNION to work, the SELECT statements must have:

  • The same number of columns.

  • Similar data types in corresponding columns.

1. Determining Column Count

An attacker can guess the number of columns the original SELECT statement returns by trying different numbers with a UNION subquery.

  • Example Input: hammer' UNION SELECT 1,2,3 FROM DUAL; --

    • DUAL is a placeholder table in MySQL often used for selecting single values.

    • If the output displays 1, 2, and 3 appended to the hammer products, it means the original query selects three columns. If it fails, the attacker adjusts the number of columns (e.g., 1,2,3,4).

2. Discovering Table Names (information_schema.tables)

With the column count known, the attacker can query MySQL's information_schema.tables to list all tables in the database.

  • Example Input: hammer' UNION SELECT table_name, table_schema, 3 FROM information_schema.tables; --

    • This query selects the table_name and table_schema (database name) and a placeholder 3 to match the three columns.

    • The output will append a list of all tables, including system tables and potentially application-specific tables like users or stock.

3. Discovering Column Names (information_schema.columns)

Once a potentially interesting table (e.g., users) is identified, the attacker needs to know its column names to extract data. This is done by querying information_schema.columns.

  • Example Input: hammer' UNION SELECT column_name, 2, 3 FROM information_schema.columns WHERE table_name = 'users'; --

    • This will output the column names from the users table, such as user_id, user_login, user_hash, and user_type.

4. Extracting User Credentials

With table and column names known, the final step is to extract the actual data.

  • Example Input: hammer' UNION SELECT user_login, user_hash, user_type FROM users; --

    • This query will append the user_login, user_hash (hashed password), and user_type for all users in the database to the original product list.

    • This reveals user credentials, including admin accounts, which can then be targeted for password cracking.


🛡️ Preventing SQL Injection

Preventing SQL injection is crucial and requires diligent coding practices.

1. Parameterized Queries (Prepared Statements)

  • This is the most effective defense. Instead of directly embedding user input into the SQL query string, placeholders are used. The database driver then sends the query structure and the user input separately. The database treats the input only as data, never as executable code.

  • Example:

    $stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE ?");
    $stmt->execute(["%{$searchTerm}%"]);

2. Input Sanitization and Escaping

  • Escaping: Using functions like mysqli_real_escape_string() (for MySQL) to escape special characters in user input. This converts characters like ' into \', making them literal parts of the string rather than SQL syntax.

  • Sanitization: Validating and cleaning user input to ensure it conforms to expected formats (e.g., ensuring an age field only contains numbers). This is a good practice but not a substitute for parameterized queries.

3. Least Privilege Principle

  • Database users should only have the minimum necessary permissions. For example, a web application user should not have DROP TABLE or DELETE privileges if it only needs to read and insert data.

4. Second-Order SQL Injections

  • Be aware of second-order SQL injections. This occurs when malicious input is initially escaped and stored safely in the database, but then later retrieved and used in another query without re-escaping or parameterization.

    • Example: A malicious username is stored. Later, when an admin views user profiles, the username is directly inserted into a new query, triggering the injection.

5. Web Application Firewalls (WAFs)

  • WAFs can provide an additional layer of defense by detecting and blocking common SQL injection patterns at the network level, though they are not foolproof.


📊 The Real-World Impact

Major companies continue to be victims of SQL injection attacks. These attacks are often automated using scripts (like Python scripts) that can quickly identify vulnerabilities and dump vast amounts of data. The ease with which sensitive data can be extracted makes SQL injection one of the most dangerous and persistent web security threats.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent