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

​​​​​​​

相关推荐
AI语宙漫游指南8 分钟前
487个带毒仓库、仿冒品三项审计全绿:最近 Skills 染毒事件及自查方案
安全·aigc·agent
耀耀_很无聊12 分钟前
17_Spring Boot 使用 MDC 实现 TraceId 日志追踪
java·spring boot·后端
@SmartSi24 分钟前
AgentScope Java 入门 15:如何使用 RAG 检索增强生成为 Agent 接入外部知识库
java·agentscope
那明眸似水31 分钟前
OpenEuler 22.03 实战部署 Harbor 2.12 并推送 K8s 镜像全记录
java·容器·kubernetes
持敬chijing36 分钟前
JAVA与CVE漏洞5-FastJSON 反序列化漏洞
java·网络安全·系统安全·网络攻击模型·安全威胁分析
JAVA面经实录91737 分钟前
Java 后端专属提示词模板
java·重构·bug·ai编程
安教安全员通关宝38 分钟前
学习笔记:安全员A证、B证、C证的区别与适用岗位
笔记·学习·安全·题库·安全员c·安全员考试
用户3721574261351 小时前
Java 裁切 PDF 页面:去除多余白边、批量裁剪与局部图片导出
java
野生技术架构师1 小时前
高级 Java 工程师面试八股(2026 精选版)
java·开发语言·面试
wuminyu1 小时前
OpenJDK学习笔记:Native线程如何回调Java
java·linux·c语言·jvm·c++