Skip to content

Resolve vulnerability: Improper neutralization of special elements used in an SQL command ('SQL Injection')

MR created from vulnerability: Improper neutralization of special elements used in an SQL command ('SQL Injection')

AI GENERATED FIX

The suggested code changes were generated by GitLab Duo Vulnerability Resolution, an AI feature. Use this feature with caution. Before you run a pipeline or apply the code changes, carefully review and test them, to ensure that they solve the vulnerability.

The large language model that generated the suggested code changes was provided with the entire file that contains the vulnerable lines of code. It is not aware of any functionality outside of this context.

Please see our documentation for more information about this feature.

Description:

Potential SQL Injection vulnerability detected in JDBC Statement execution. SQL Injection is a critical security vulnerability that occurs when an attacker can manipulate a SQL query. Using raw SQL queries with string concatenation or untrusted user input directly in the Statement methods can expose your application to SQL Injection attacks.

To mitigate SQL Injection vulnerabilities, use PreparedStatement with parameterized queries. This ensures that user input is treated as data and not executable code.

Secure Code Example:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    private Connection connection;

    public UserDao(Connection connection) {
        this.connection = connection;
    }

    public void getUserByUsername(String username) throws SQLException {
        String sql = "SELECT * FROM users WHERE username = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                // Process the result
            }
        }
    }
}

Analysis:

根据漏洞报告和源代码分析,这是一个真实的SQL注入漏洞,而非误报。以下是分析要点:

  1. 漏洞类型:

    • CWE-89: SQL注入
    • OWASP A03:2021 - 注入
    • 使用不安全的Statement直接执行用户输入的查询字符串
  2. 问题代码:

    • 直接使用statement.executeQuery(query)执行用户输入的query参数
    • 用户输入未经过任何过滤或参数化处理
  3. 安全影响:

    • 攻击者可构造恶意SQL语句进行注入攻击
    • 可能导致数据泄露、数据篡改或数据库服务器被控制
    • 特别危险的是这是一个WebGoat教学示例,本应演示安全编码实践
  4. 上下文考虑:

    • 虽然这是一个教学示例(可能故意展示漏洞),但从安全角度仍需修复
    • 修复方案应保持原有功能同时消除注入风险

Summary:

  1. 报告漏洞:

    • SQL注入漏洞(CWE-89),由于直接使用Statement执行用户输入的查询字符串
  2. 修复方案:

    • 将Statement替换为PreparedStatement
    • 使用参数化查询(?占位符)
    • 通过setString()方法安全地绑定用户输入
    • 保持原有功能不变(仍能查询部门信息)
  3. 安全效果:

    • 用户输入将被视为数据而非SQL代码
    • 有效防止SQL注入攻击
    • 符合OWASP推荐的安全编码实践

Identifiers:

  • A1:2017 - Injection
  • SAST Rules ID - java_inject_rule-SqlInjection
  • A03:2021 - Injection
  • CWE-89
  • java-jdbc-sqli-taint

合并请求报告

加载中