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

​​​​​​​

相关推荐
重生之后端学习1 小时前
02-前端Web开发(JS+Vue+Ajax)
java·开发语言·前端·javascript·vue.js
字节源流7 小时前
关于maven的依赖下不下来的问题
java·maven
pjx9878 小时前
服务间的“握手”:OpenFeign声明式调用与客户端负载均衡
java·运维·spring·负载均衡
prinrf('千寻)8 小时前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
Blurpath8 小时前
免费代理IP服务有哪些隐患?如何安全使用?
网络·安全·ip代理·住宅ip
老华带你飞8 小时前
实习记录小程序|基于SSM+Vue的实习记录小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·实习记录小程序
在未来等你9 小时前
互联网大厂Java求职面试:AI与大模型应用集成及云原生挑战
java·微服务·ai·kubernetes·大模型·embedding·spring ai
源码技术栈9 小时前
SaaS基于云计算、大数据的Java云HIS平台信息化系统源码
java·大数据·云计算·云his·his系统·云医院·区域his
编程、小哥哥9 小时前
互联网大厂Java面试:从Spring Boot到微服务架构的技术深挖
java·spring boot·redis·微服务·prometheus·面试技巧
揽你·入怀9 小时前
数据结构:ArrayList简单实现与常见操作实例详解
java·开发语言