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 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.
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.
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();
}
}
|
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.
import 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();
}
}
|
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 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[API 06|AA. Java References#API 06]\] [class Scanner|http://java.sun.com/javase/6/docs/api/java/util/Scanner.html] |