Fortofy扫描安全漏洞解决——Unreleased Resource: Streams未释放资源漏洞

问题描述:

大部分 Unreleased Resource 问题只会导致一般的软件可靠性问题,但如果攻击者能够故意触发资源泄漏,该攻击者就有可能通过耗尽资源池的方式发起 denial of service 攻击。

问题代码:

java 复制代码
 FileInputStream inputStream = new FileInputStream(sourcePath);
 FileOutputStream outputStream = new FileOutputStream(destinationPath);
 byte[] buffer = new byte[1024];
 int bytesRead;
 while ((bytesRead = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, bytesRead);
 }
 // 注意:这里缺少关闭资源的代码

解决方案1:使用try-catch-finally,在finally语句块中关闭资源(一般还是会被Fortofy扫描出来)

java 复制代码
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(sourcePath);
            outputStream = new FileOutputStream(destinationPath);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

解决方案2:使用try-with-resources方式解决(不会被Fortofy检测出漏洞)

try-with-resources 大家不太常见,格式就是在try与catch语句块之间加入小括号,我们在小括号之中编写开启文件流代码,try-with-resources 会为我们管理文件流,大伙儿无需手动关闭流资源。强烈推荐使用!增加代码可读性和行数,也会避免犯错。

java 复制代码
    try (
            FileInputStream inputStream = new FileInputStream(sourcePath);
            FileOutputStream outputStream = new FileOutputStream(destinationPath)
        ) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } // try-with-resources 会自动关闭资源
    }

​​​​​​​

相关推荐
简色17 分钟前
题库批量(文件)导入的全链路优化实践
java·数据库·mysql·mybatis·java-rabbitmq
程序员飞哥26 分钟前
如何设计多级缓存架构并解决一致性问题?
java·后端·面试
一只小松许️34 分钟前
深入理解:Rust 的内存模型
java·开发语言·rust
前端小马1 小时前
前后端Long类型ID精度丢失问题
java·前端·javascript·后端
Lisonseekpan1 小时前
Java Caffeine 高性能缓存库详解与使用案例
java·后端·spring·缓存
SXJR2 小时前
Spring前置准备(七)——DefaultListableBeanFactory
java·spring boot·后端·spring·源码·spring源码·java开发
心态特好2 小时前
详解WebSocket及其妙用
java·python·websocket·网络协议
Haooog4 小时前
98.验证二叉搜索树(二叉树算法题)
java·数据结构·算法·leetcode·二叉树
武子康4 小时前
Java-143 深入浅出 MongoDB NoSQL:MongoDB、Redis、HBase、Neo4j应用场景与对比
java·数据库·redis·mongodb·性能优化·nosql·hbase
jackaroo20204 小时前
后端_基于注解实现的请求限流
java