Methods return values to signify failure or success or, 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.
Noncompliant Code Example
This noncompliant code example attempt to delete a file, but does not check that the operation succeeds.
Code Block | ||
---|---|---|
| ||
File someFile = new File("someFileName.txt");
// do something with someFile
someFile.delete();
|
Compliant Solution
In the compliant solution, the (boolean
) value returned by the delete()
method is checked and, if necessary, 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 } |
Noncompliant Code Example
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.
Code Block | ||
---|---|---|
| ||
public class Ignore { public static void main(String[] args) { String original = "insecure"; original.replace( 'i', '9' ); System.out.println (original); } } |
Compliant Solution
The compliant solution correctly updates the original
string object by assigning to it the return value.
...
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] method [delete()|http://java.sun.com/javase/6/docs/api/java/io/File.html#delete()] \[[API 06|AA. Java References#API 06]\] method [replace()|http://java.sun.com/javase/6/docs/api/java/lang/String.html#replace(char,%20char)] \[[Green 08|AA. Java References#Green 08]\] ["String.replace"|http://mindprod.com/jgloss/gotchas.html] \[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 252|http://cwe.mitre.org/data/definitions/252.html] "Unchecked Return Value" |
...