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

​​​​​​​

相关推荐
科技小E1 小时前
打手机检测算法AI智能分析网关V4守护公共/工业/医疗等多场景安全应用
人工智能·安全·智能手机
行云流水剑3 小时前
【学习记录】使用 Kali Linux 与 Hashcat 进行 WiFi 安全分析:合法的安全测试指南
linux·学习·安全
KKKlucifer3 小时前
加密通信 + 行为分析:运营商行业安全防御体系重构
网络·安全·重构
有梦想的骇客4 小时前
书籍“之“字形打印矩阵(8)0609
java·算法·矩阵
炎码工坊4 小时前
微服务通信安全实战:JWT在分布式架构中的应用与最佳实践
安全·网络安全·云原生·系统安全·安全架构
yours_Gabriel4 小时前
【java面试】微服务篇
java·微服务·中间件·面试·kafka·rabbitmq
hashiqimiya6 小时前
android studio中修改java逻辑对应配置的xml文件
xml·java·android studio
liuzhenghua666 小时前
Python任务调度模型
java·运维·python
結城6 小时前
mybatisX的使用,简化springboot的开发,不用再写entity、mapper以及service了!
java·spring boot·后端
小前端大牛马6 小时前
java教程笔记(十一)-泛型
java·笔记·python