Back | Home

SQL Injection and Remediation

What is SQL Injection?

SQL Injection is a type of security vulnerability that occurs when malicious SQL queries are inserted into input fields or parameters of a web application's SQL queries. Attackers can manipulate these queries to gain unauthorized access to a database, execute arbitrary SQL commands, and retrieve or modify sensitive data.

Example of SQL Injection

Consider a web application with a login form:

Remediation

To mitigate SQL Injection vulnerabilities, web developers should:

Source code example

Below is an example of Java code featuring a sql injection:


            import java.sql.*;

            public class SQLInjectionExample {
            
                public static void main(String[] args) {
                    String username = "' OR '1'='1"; // Simulate malicious SQL injection input
                    String password = "' OR '1'='1"; // Simulate malicious SQL injection input
            
                    try {
                        // Establishing a connection to the database
                        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/example_db", "username", "password");
            
                        // Constructing the SQL query with user input
                        String sqlQuery = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
            
                        // Creating a statement
                        Statement statement = connection.createStatement();
            
                        // Executing the SQL query
                        ResultSet resultSet = statement.executeQuery(sqlQuery);
            
                        // Checking if the result set contains any rows
                        if (resultSet.next()) {
                            // User authenticated
                            System.out.println("User authenticated successfully!");
                        } else {
                            // Authentication failed
                            System.out.println("Authentication failed!");
                        }
            
                        // Closing resources
                        resultSet.close();
                        statement.close();
                        connection.close();
            
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }