You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

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.

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.

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.

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();
  }
}

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

[[API 06]] class Scanner

  • No labels