Methods return values to signify communicate failure or success or, and at other times, to update the caller's objects or fields. Security risks can arise if return values are simply ignored or if suitable action is not taken on their receipt. Return values may be ignored intentionally or even unintentionally. For example, when getter methods that return a value are named after an action, such as ProcessBuilder.redirectErrorStream()
, a programmer may not realize that a return value is expected. Incidentally, the only purpose of the redirectErrorStream()
method is to tell using a return value, whether the process builder merges standard error and standard output. The action of actually redirecting the error stream is performed by its overloaded single argument version. It is important to read the API documentation so that return values are not ignored.
...
This noncompliant code example attempts to delete a file, but does not check that whether the operation succeedshas succeeded.
Code Block | ||
---|---|---|
| ||
File someFile = new File("someFileName.txt"); // do something with someFile someFile.delete(); |
Compliant Solution
In the This compliant solution , checks the (boolean
) value returned by the delete()
method is checked and, if necessary, handles the error is handled.
Code Block | ||
---|---|---|
| ||
File someFile = new File("someFileName.txt"); // do something with someFile if (!someFile.delete()) { // handle the fact that the file has not been deleted } |
...
This noncompliant code example ignores the return value while making use of the String.replace
method. As a result, the original string is not updated even though it seems otherwise. The String.replace()
method does not modify the state of the String
but instead, returns a reference to a new String
object with the replacements in place.
...
Code Block | ||
---|---|---|
| ||
public class DoNotIgnore { public static void main(String[] args) { String original = "insecure"; original = original.replace( 'i', '9' ); System.out.println(original); } } |
Another source of coding bugs security vulnerabilities caused by ignoring return values is detailed in FIO02-J. Keep track of bytes read and account for character encoding while reading data.
...
Ignoring method return values may can lead to unanticipated program behavior.
...