The write()
method, defined in the class java.io.OutputStream
, takes an argument of type int
intended to be between 0 and 255. Because a value of type int
may could be outside this range, failure to range check can result in the truncation of the higher order bits of the input.
...
Code Block | ||
---|---|---|
| ||
class ConsoleWrite { public static void main(String[] args) { //Any input value > 255 will result in unexpected output System.out.write(Integer.valueOf(args[0].toString())); System.out.flush(); } } |
Compliant Solution (Use System.out.print*
...
Methods)
Use alternative means to output integers, such as the System.out.print*
methods.
Code Block | ||
---|---|---|
| ||
class ConsoleWrite { public static void main(String[] args) { System.out.println(args[0]); } } |
Compliant Solution (Range-
...
Check Inputs)
Alternatively, perform range checking to be compliant. While this particular compliant solution still fails to display the original out-of-range integer, it behaves well when the corresponding read()
method is used to convert the byte
value back to a value of type int
. This is because it guarantees that the byte
variable will contain representable data.
...
Using the write()
method to output integers writes only the low-order 8 bits of the integers. This truncation may can result in unexpected values.
...
Automated detection of all uses of the write()
method is straightforward. Sound determination of whether the truncating behavior is correct is not feasible in the general case. Heuristic checks may could be useful.
Related Vulnerabilities
...