Java does not support the use of unsigned types, except for the 16 bit char datatype. Sometimes, it is necessary to interoperate with native languages such as C or C++ that use unsigned types extensively. The standard practice to deal with unsigned input is to read values into Java's larger signed primitives. For example, a signed long can be used to hold an unsigned integer obtained from native code.
This example incorrectly uses a generic method for reading in integer data irrespective of the signedness. It assumes that the value is always signed and treats the most significant bit (MSB) as the sign bit causing misinterpretations about the actual sign and magnitude of the integer.
public static int getInteger(DataInputStream is) throws IOException {
return is.readInt();
}
|
This compliant solution assumes that the unsigned integer has 32 bits. It reads in an unsigned integer value into a long variable using the readInt() method. If the read integer is unsigned, the most significant bit may be turned on. Consequently, all the higher order bits of the resulting long are set because of sign extension, and these must be masked off as demonstrated. For other integer sizes, the mask size should vary depending on the size of the unsigned integer.
public static long getInteger(DataInputStream is) throws IOException {
return is.readInt() & 0xFFFFFFFFL;
}
|
Treating an unsigned type as signed can result in misinterpretations and can lead to lost or misinterpreted data.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
INT08-J |
low |
unlikely |
medium |
P2 |
L3 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[API 2006|AA. Bibliography#API 06]\] Class DataInputStream: method {{readInt}}
\[[Harold 1997|AA. Bibliography#Harold 97]\] Chapter 2: Primitive Data Types, Cross Platform Issues, Unsigned Integers
\[[Hitchens 2002|AA. Bibliography#Hitchens 02]\] 2.4.5 Accessing Unsigned Data |
INT07-J. Provide methods to read and write Little-Endian data 06. Integers (INT) INT09-J. Do not rely on the write() method to output integers outside the range 0 to 255