简体   繁体   中英

Determining if my code contains hard-coded SQL queries?

Here is a method authenticate the user password. It verify the user email and password from the database.

public long authenticate(String email, String encodePassword) {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try (
        Connection conn = DriverManager.getConnection("jdbc:connection", "adminusername","password");/* a) Database User Profile: root is who the user is b) Database user password */
        Statement stmt = conn.createStatement();
    ) /* execute mysql queries */ {
        String query = "Select id from User where email = '" + email + "' and password = '" + encodePassword + "'";
        System.out.println("query: " + query);
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            // if the user id is there get it
            return rs.getLong("id");                
        }           
    } catch (SQLException e) {
        e.printStackTrace();
    }   

    // if the user id not there return -1 (authority failed)
    return -1; 
}

To determine whether my lecture is right that I have hard-coded SQL queries values in my code

Your lecturer is trying to warn you about SQL injection.

SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve. This might include data belonging to other users, or any other data that the application itself is able to access. In many cases, an attacker can modify or delete this data, causing persistent changes to the application's content or behavior.

The corresponding part in your code is the following

String query = "Select id from User where email = '" + email + "' and password = '" + encodePassword + "'";

If the query returns the id of a user, then the login is successful. Otherwise, it is rejected.

Here, an attacker can log in as any user without a password simply by using the SQL comment sequence -- to remove the password check from the WHERE clause of the query. For example, submitting the email some@email'-- and a blank password results in the following query:

SELECT id FROM users WHERE email = 'some@email'--' AND password = ''

This query returns the user whose email is some@email and successfully logs the attacker in as that user without checking the password.

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