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 会自动关闭资源
    }

​​​​​​​

相关推荐
郑州光合科技余经理11 分钟前
定制开发实战:海外版外卖系统PHP全栈解决方案
java·服务器·开发语言·javascript·git·uni-app·php
sg_knight13 分钟前
Docker Engine 升级指南:保障容器安全的关键步骤
java·spring boot·安全·spring·spring cloud·docker·容器
runepic19 分钟前
Python 批量合并多个 Excel 数据(自动补 0 + 生成明细)
java·python·excel
安科瑞小许20 分钟前
用户侧新能源并网:如何实现安全高效的“防逆流”运行
安全·能源·新能源·并网·防逆流
vx_bisheyuange22 分钟前
基于SpringBoot的失物招领平台的设计与实现
java·spring boot·后端·毕业设计
liebe1*122 分钟前
第十四章 网络安全方案设计
安全·web安全
顾安r23 分钟前
12.15 脚本网页 bash内建命令
java·前端·javascript·html·bash
Brookty25 分钟前
Java并发编程核心的基础知识
java·开发语言·java-ee·多线程·线程安全
hellotutu25 分钟前
Java 读取 Excel 文件
java·开发语言·excel
胡萝卜3.027 分钟前
构建安全的C++内存管理体系:从RAII到智能指针的完整解决方案
运维·开发语言·c++·人工智能·安全·智能指针·raii