修复SonarQube问题:SQL注入、伪随机、安全热点

main
SLMS Development Team 5 months ago
parent 34aaea67b9
commit ae2b1cca72

@ -192,9 +192,13 @@ public class DatabaseInitializer {
*
*/
public void clearAllData() throws SQLException {
String[] tables = {"loans", "books", "users"};
for (String table : tables) {
String sql = "DELETE FROM " + table;
// 使用硬编码SQL语句避免SQL注入风险表名不可参数化
String[] deleteStatements = {
"DELETE FROM loans",
"DELETE FROM books",
"DELETE FROM users"
};
for (String sql : deleteStatements) {
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
pstmt.executeUpdate();
}

@ -4,8 +4,7 @@ import java.io.*;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
*
@ -13,6 +12,9 @@ import java.util.List;
*/
public class DatabaseMigrationTool {
// 允许操作的表白名单防止SQL注入
private static final Set<String> ALLOWED_TABLES = Set.of("books", "users", "loans");
private final DatabaseAdapter sourceAdapter;
private final DatabaseAdapter targetAdapter;
@ -276,6 +278,11 @@ public class DatabaseMigrationTool {
* @throws SQLException
*/
private int getRecordCount(DatabaseAdapter adapter, String tableName) throws SQLException {
// 白名单验证表名防止SQL注入
if (!ALLOWED_TABLES.contains(tableName)) {
throw new IllegalArgumentException("非法表名: " + tableName);
}
String sql = "SELECT COUNT(*) as count FROM " + tableName;
try (Connection conn = adapter.getConnection();
@ -336,6 +343,11 @@ public class DatabaseMigrationTool {
private void exportTable(Connection conn, FileWriter writer, String tableName)
throws SQLException, IOException {
// 白名单验证表名防止SQL注入
if (!ALLOWED_TABLES.contains(tableName)) {
throw new IllegalArgumentException("非法表名: " + tableName);
}
writer.write("-- 表: " + tableName + "\n");
try (Statement stmt = conn.createStatement();

@ -11,7 +11,7 @@ import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.security.SecureRandom;
/**
* Mock
@ -52,7 +52,8 @@ public class MockDataGenerator {
"伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军"
};
private final Random random = new Random();
// 使用 SecureRandom 替代 Random避免可预测的伪随机数
private final SecureRandom random = new SecureRandom();
private DatabaseConnection dbConnection;
public MockDataGenerator() {

Loading…
Cancel
Save