简体   繁体   中英

JAVA - Possible SQL Injection

So I have this snippet of code:

String username = props.getProperty("jdbc.username");
try {
                String username = parts[1];

                // Check procedure
                System.out.println("Checking user");

                // Check database user table for username
                conn = getSQLConnection();
                Statement stat = conn.createStatement();
                ResultSet user = stat.executeQuery( "SELECT * FROM USER WHERE log_id='" + username + "';" );
                // Check given password against user entry
                if(user.next()){
                    System.out.println("User Exists: " + username);
                    sendMessage("true");
                    return;
                }
                else{

                    System.out.println("User Does Not Exist: " + username);
                    sendMessage("false user");
                    return;
                }

For educational purposes, is the SQL statement protected from an SQL injection even though I know where the input is coming from?

ResultSet user = stat.executeQuery( "SELECT * FROM USER WHERE log_id='" + username + "';" );

This is subject to SQL injection.

Imagine what happens if username has this value:

John'; delete from user where 'a' = 'a

And yes, as*load of Java JDBC SQL tutorials get this wrong. Basically, always use PreparedStatement s.

Not only because this makes it safe ot use even if username has malicious values as the above, but also, and more importantly, because the same query can be reused by the RDBMS engine for all further invocations.

In short, there is no reason at all not to use them. And tutorials demonstrating SQL using string concatenation should die a painful, SQL injection death.

As explained in this post , one rogue attacker can do the following to yoour application:

  • call a sleep function so that all your database connections will be busy, therefore making your application unavailable
  • extracting sensitive data from the DB
  • bypassing the user authentication

And it's not just SQL that can be affected. Even JPQL can be compromised if you are not using bind parameters.

Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM