The write() method, defined in the class java.io.OutputStream, takes an argument of type int the value of which must be in the range 0 to 255. Because a value of type int could be outside this range, failure to range check can result in the truncation of the higher-order bits of the argument.

The general contract for the write() method says that it writes one byte to the output stream. The byte to be written constitutes the eight lower-order bits of the argument b, passed to the write() method; the 24 high-order bits of b are ignored (see java.io.OutputStream.write() [API 2014] for more information).

Noncompliant Code Example

This noncompliant code example accepts a value from the user without validating it. Any value that is not in the range of 0 to 255 is truncated. For instance, write(303) prints / on ASCII-based systems because the lower-order 8 bits of 303 are used while the 24 high-order bits are ignored (303 % 256 = 47, which is the ASCII code for /). That is, the result is the remainder of the input divided by 256.

class ConsoleWrite {
  public static void main(String[] args) { 
    // Any input value > 255 will result in unexpected output
    System.out.write(Integer.valueOf(args[0]));
    System.out.flush();
  }
}

Compliant Solution (Range-Check Inputs)

This compliant solution prints the corresponding character only if the input integer is in the proper range. If the input is outside the representable range of an int, the Integer.valueOf() method throws a NumberFormatException. If the input can be represented by an int but is outside the range required by write(), this code throws an ArithmeticException.

class FileWrite {
  public static void main(String[] args)
                          throws NumberFormatException, IOException { 
    // Perform range checking  
    int value = Integer.valueOf(args[0]);
    if (value < 0 || value > 255) {
      throw new ArithmeticException("Value is out of range");
    }
  
    System.out.write(value);
    System.out.flush(); 
  }
}

Compliant Solution (writeInt())

This compliant solution uses the writeInt() method of the DataOutputStream class, which can output the entire range of values representable as an int:

class FileWrite {
  public static void main(String[] args)
                          throws NumberFormatException, IOException { 
    DataOutputStream dos = new DataOutputStream(System.out);
    dos.writeInt(Integer.valueOf(args[0].toString()));
    System.out.flush(); 
  }     
}

Risk Assessment

Using the write() method to output integers outside the range 0 to 255 will result in truncation.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO09-J

Low

Unlikely

Medium

P2

L3

Automated Detection

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 could be useful.

Tool
Version
Checker
Description
CodeSonar
8.1p0

JAVA.NULL.RET.UNCHECKED

Call Might Return Null (Java)

Coverity7.5CHECKED_RETURNImplemented
Parasoft Jtest

2024.1

CERT.FIO09.ARGWRITEDo not rely on the write() method to output integers outside the range 0 to 255

Related Guidelines

MITRE CWE

CWE-252, Unchecked Return Value

Bibliography



3 Comments

  1. Why does OutputStream.write() take an int when it clearly wants a byte? (Is this a Java design wart?)

    The CCE & NCCE are sending a String to write(), not an int.

    Finally, ints can also be < 0, so you need to ensure that int i >= 0 && i <= 255 before passing it to OutputStream.write().

    1. Why does OutputStream.write() take an int when it clearly wants a byte? (Is this a Java design wart?)

      The value to be written is to be regarded as unsigned byte. In Java there are no unsigned primitives. Because shorts are a pain to be used, int is used instead (wink)

      OK, seriously. The write-method is a mirror to the read()-method that returns an int because it needs a special value for signaling the end of the stream (-1). So you can't just return a byte, because that way all possible values that can be used in Byte are occupied already.

       Finally, ints can also be < 0, so you need to ensure that int i >= 0 && i <= 255 before passing it to OutputStream.write().

      Actually you can write e.g. -1 and it happens in reality (because there are people who use write(int) using a byte). How the int-value is to be interpreted is described e.g. in the Javadoc of OutputStream and is already described in the text above. So implementing an own OutputStream where you check for -1 and interpret that as "end of stream" as it is defined in read() of InputStream is a bug (maybe worth another article here).