Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL injection Attack in Java

I am trying to achieve one of the scenario using java code. I am writing some bad code to analyse it over sonarqube.

I tried to test "SQL queries should not be vulnerable to injection attacks" from https://rules.sonarsource.com/java/tag/SonarSecurity/RSPEC-3649. Below is the code that i am trying to analyse,

package group;
import java.util.*;
import java.io.PrintStream;
import java.nio.file.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
import javax.naming.*;

public class SonarDemo {

    public static void main(String[] args) {
        PrintStream o = System.out; //NOSONAR

        String pass = args[0];//request.getParameter("pass");
        String user = args[1];
        String query = "SELECT * FROM users WHERE user = '" + user + "' AND pass = '" + pass + "'"; // Unsafe
        Properties connectionProps = new Properties();
        connectionProps.put("user", user);
        connectionProps.put("password", pass);
        java.sql.Connection connection = null;
        try {
            connection = java.sql.DriverManager.getConnection("jdbc:localhost:sql1;create=true",connectionProps);
            java.sql.Statement statement = connection.createStatement();
            java.sql.ResultSet resultSet = statement.executeQuery(query);
            Files.exists(Paths.get("/home/", user));

            String filter = "(&(uid=" + user + ")(userPassword=" + pass + "))"; // Unsafe

            LdapContext ctx = new InitialLdapContext();
            NamingEnumeration<SearchResult> results = ctx.search("ou=system", filter, new SearchControls());

        } catch (Exception e){
            o.println("Exception");
        }

    }

}

But there is some Issue in code where sonarqube isn't able to pick up this code and show there is an issue with injection attack.

How to modify this code to create some SQL injection attack so that my sonarqube can able to show this error on dashboard?

In short- Modifying above code to create injection attack as as mentioned here https://rules.sonarsource.com/java/tag/SonarSecurity/RSPEC-3649


1 Answers

User provided data such as URL parameters should always be considered as untrusted and tainted.

AFAIK runtime args are not recognized as input from the user. To reproduce the issue try taking user and pass from the URL parameters of a request.

public boolean authenticate(javax.servlet.http.HttpServletRequest request, java.sql.Connection connection) throws SQLException {
  String user = request.getParameter("user");
  String pass = request.getParameter("pass");
}
like image 90
Arpit Sharma Avatar answered Sep 02 '26 06:09

Arpit Sharma