我有以下代码作为文件下载表,使用PG 复制
public void download(String table, Writer responseWriter) throws SQLException, IOException {
try (Connection conn = dataSource.getConnection()) {
CopyManager copyManager = new CopyManager(conn.unwrap(BaseConnection.class));
// SQL Injection can happen here!
String statement = "COPY " + table + " TO STDOUT WITH NULL ''";
copyManager.copyOut(statement, responseWriter);
}
}显然,这段代码容易执行SQL注入(表参数是从Spring控制器传递的)。当然,我可以做一些手工卫生,但如果有一种"PreparedStatement“的方式在CopyManager中这样做,我会更喜欢它。使用Spring的JdbcTemplate的额外积分。
发布于 2019-04-08 10:56:00
除了屏蔽SQL注入(恶意尝试将DELETE语句添加到COPY命令)之外,还有另一个问题。因为您的代码允许运行任何有效的表名,所以它仍然有暴露架构中任何表中包含的数据的风险。
因此,在这里要做的安全的事情可能是维护一个表的白名单,您希望允许用户访问这些表。任何与列表不匹配的输入表名称都将被拒绝。假设您的表列表驻留在List中,我们可以对您的代码进行以下更改:
public void download(String table, Writer responseWriter) throws SQLException, IOException {
// get list of all allowed tables
List<String> fileList = getAllowedTables();
if (!fileList.contains(table)) {
throw new IllegalAccessException("Someone tried to access a forbidden table.");
}
try (Connection conn = dataSource.getConnection()) {
CopyManager copyManager = new CopyManager(conn.unwrap(BaseConnection.class));
// SQL Injection can happen here!
String statement = "COPY " + table + " TO STDOUT WITH NULL ''";
copyManager.copyOut(statement, responseWriter);
}
}https://stackoverflow.com/questions/55571706
复制相似问题