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/C++ that use unsigned types extensively. The standard practice to deal with unsigned types is to read their values into Java's larger signed
primitives. For example, a signed long
is used to hold an unsigned integer
.
Noncompliant Code Example
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 thus treats the most significant bit (MSB) as the sign bit causing misinterpretations about the actual magnitude of the integer.
public static int getInteger(DataInputStream is) throws IOException { return is.readInt(); }
Compliant Solution
This compliant solution assumes that the unsigned integer has 32 bits. It reads in an unsigned integer value into an array of four bytes. The bytes are left shifted by the appropriate amount and OR'ed together. However, when the bytes are shifted they are promoted to int
(the last byte is promoted to an int
to compute the bitwise-OR). If the byte is negative, then all the higher order bits of the resulting int
will be set due to sign extension, and these have to be masked off. Finally, the whole int
expression may be negative when it is promoted to the long
result
and, again, the higher order bits have to be masked off. (cf. [[Harold 97]] but the code there is incorrect)
public static long readInt(InputStream is) throws IOException { byte[] buffer = new byte[4]; int check = is.read(buffer); if (check != 4) throw new IOException("Unexpected End of Stream!"); long result = (buffer[0] << 24) | (0x00FFFFFF&(buffer[1] << 16)) | (0x0000FFFF&(buffer[2] << 8)) | (0x000000FF&buffer[3]); result &= 0xFFFFFFFFL; return result; }
Risk Assessment
Treating an unsigned type as signed can result in misinterpretations and can lead to erroneous calculations.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
SEC01-J |
low |
unlikely |
low |
P3 |
L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[API 06]] Class DataInputStream: method readInt
[[Harold 97]] Chapter 2: Primitive Data Types, Cross Platform Issues, Unsigned Integers
INT00-J. Provide methods to read and write Little-Endian data 04. Integers (INT) 04. Integers (INT)