gpt4 book ai didi

java - 确定我的代码是否包含硬编码的 SQL 查询?

转载 作者:行者123 更新时间:2023-11-29 15:38:56 26 4
gpt4 key购买 nike

这是一种验证用户密码的方法。它验证数据库中的用户电子邮件和密码。

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;
}

为了确定我的讲座是否正确,我在代码中硬编码了 SQL 查询值

最佳答案

您的讲师试图警告您有关 SQL 注入(inject)的问题。

SQL 注入(inject)是一种 Web 安全漏洞,允许攻击者干扰应用程序对其数据库进行的查询。它通常允许攻击者查看他们通常无法检索的数据。这可能包括属于其他用户的数据,或应用程序本身能够访问的任何其他数据。在许多情况下,攻击者可以修改或删除此数据,从而导致应用程序的内容或行为发生持久更改。

代码中相应的部分如下

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

如果查询返回用户的id,则登录成功。否则,将被拒绝。

在这里,攻击者只需使用 SQL 注释序列 -- 从查询的 WHERE 子句中删除密码检查,就可以以任何用户身份登录而无需密码。例如,提交电子邮件 some@email'-- 和空白密码将导致以下查询:

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

此查询返回电子邮件为 some@email 的用户,并在不检查密码的情况下成功以该用户身份登录攻击者。

关于java - 确定我的代码是否包含硬编码的 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57889034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com