首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用PostgreSQL复制JDBC防止SQL注入

用PostgreSQL复制JDBC防止SQL注入
EN

Stack Overflow用户
提问于 2019-04-08 10:49:32
回答 1查看 491关注 0票数 4

我有以下代码作为文件下载表,使用PG 复制

代码语言:javascript
复制
    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的额外积分。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-08 10:56:00

除了屏蔽SQL注入(恶意尝试将DELETE语句添加到COPY命令)之外,还有另一个问题。因为您的代码允许运行任何有效的表名,所以它仍然有暴露架构中任何表中包含的数据的风险。

因此,在这里要做的安全的事情可能是维护一个表的白名单,您希望允许用户访问这些表。任何与列表不匹配的输入表名称都将被拒绝。假设您的表列表驻留在List中,我们可以对您的代码进行以下更改:

代码语言:javascript
复制
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);
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55571706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档