How to guard against Resource exhaustion and other vulnerabilities?

天涯浪子 提交于 2019-12-04 11:45:35

Any time you open a stream, ensure that a finally block closes the stream when finished.

If an IOException is thrown while reading from the stream in your code the stream will not be closed, hence the warning

Java 7 makes this easy with the try with resources construct. In java 6 or earlier you need to replicate with lots of boilerplate, eg

InputStream ins = null;
try {
  ins = conn.getInputStream();
  ...
} finally {
  IOUtils.closeQuietly(ins);
}

Using the IOUtils class from Apache Commons

You can write your own closeQuietly if you don't want to add the dependency

If AppScan is indicating a Denial of Service vulnerability associated with the readLine, it is probably not due to any concern over the failure to close the stream (however important this may be), but rather due to the unbounded nature of readLine. Since readLine continues to read input until a newline or CR-LF is read, if the input source is not trusted, you could potentially be fed an inordinately large amount of data without the expected CR-LF, resulting in a memory exhaustion condition.

To resolve this you could either ensure (through mechanisms outside your app) that the input size is limited to something safe and reasonable (although AppScan, Fortify and other tools will continue to complain about the readLine) or, better yet, you could replace your readLines with a bounded read routine that sets an absolute maximum on the number of characters that will be read into the buffer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!