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

文章探讨了UnreleasedResource问题如何可能导致DoS攻击,通过示例展示了如何使用try-catch-finally和try-with-resources来防止资源泄漏。推荐使用try-with-resources以提高代码可读性和防止错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

问题代码:

 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扫描出来)

        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会为我们管理文件流,大伙儿无需手动关闭流资源。强烈推荐使用!增加代码可读性和行数,也会避免犯错。
 

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

​​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙城桥少

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值