Creating multiple scanners Java programs can get input from a user by creating a Scanner
on System.in
. A program can even get input from a user by creating multiple Scanners
on System.in
upsets the predictability of program behavior, especially and using each. While this program will work properly when System.in refers to the console, it will crash when System.in has been re-directed, which could lead to exploitable behavior.
Although the Java standard does not specifically mention this behavior, code running on Eclipse with Java 1.6 exhibits this behavior.
Do not create multiple Scanners
on System.in
; create and use only one, either by passing it as an argument to the methods that need it or centralizing its use in a single place.
Noncompliant Code Example
This noncompliant code example creates multiple Scanners
on System.in
. Although it will work when System.in
refers to a console, it crashes when System.in
has been redirected.
Code Block | ||
---|---|---|
| ||
import java.util.Scanner; |
...
public final class InputLibrary{ |
...
public static int getInt() |
...
{ Scanner in = new Scanner(System.in); return in.nextInt(); } public static double getDouble() { Scanner in = new Scanner(System.in); |
...
return in. |
...
nextDouble(); |
...
} public static void main(String[] args) { System.out. |
...
print(" |
...
Enter int: "); |
...
int i=getInt();
System.out.print("Enter double: ");
double d=getDouble();
}
}
|
Compliant Solution
Create and use only a single Scanner
on System.in
. This code example stores the Scanner
as a class variable so all methods can access it. However, if a program were to use this library in conjunction with other input from a user that also needs a Scanner
on System.in
, the library would need to be modified so that all code uses the same Scanner
instead of creating separate ones.
Code Block | ||
---|---|---|
| ||
import |
}
Compliant Code Example
...
java.util.Scanner; |
...
public final class InputLibrary{ |
...
private static Scanner in=new Scanner(System.in); |
...
public static int getInt() |
...
{
return in.nextInt();
}
public static double getDouble() {
return in.nextDouble();
}
public static void main(String[] args) {
System.out.print("Enter int: ");
int i=getInt();
System.out.print("Enter double: ");
double d=getDouble();
}
}
|
Risk Assessment
Creating multiple Scanners
on System.in
can crash the program when System.in
is re-directed.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO39-J | low | unlikely | medium | P2 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] [class Scanner|http://java.sun.com/javase/6/docs/api/java/lang/Scanner.html] |
public static int getDouble(){ Â Â Â Â Â System.out.println("Please enter a double:"); Â Â Â Â Â return in.nextDouble(); Â Â }
}