Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

Code Block
bgColor#FFcccc
DataInputStream dis = new DataInputStream(
  new FileInputStream("data""data"));  // Little-endian data might be read as big-endian
int serialNumber = dis.readInt();

...

Code Block
bgColor#ccccff
	 
DataInputStream dis = new DataInputStream(
  new FileInputStream("data""data"));

byte[] buffer= new byte[4];
int bytesRead = dis.read(buffer);  // Bytes are read into buffer
int serialNumber = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();

...

Code Block
bgColor#ccccff
	 
// read method
public static int readLittleEndianInteger(InputStream ips) throws IOException {
  byte[] buffer = new byte[4];
  int check = ips.read(buffer);

  if (check != 4) {
    throw new IOException(""Unexpected End of Stream"");
  }
 
  int result = (buffer[3] <<&lt;&lt; 24) | (buffer[2] <<&lt;&lt; 16) | (buffer[1] <<&lt;&lt; 8) | buffer[0];
  return result;
}

// write method
public static void writeLittleEndianInteger(int i, OutputStream ops) throws IOException {
  byte[] buffer = new byte[4];
  buffer[0] = (byte) i;
  buffer[1] = (byte) (i >>&gt;&gt; 8);
  buffer[2] = (byte) (i >>&gt;&gt; 16);
  buffer[3] = (byte) (i >>&gt;&gt; 24);
  ops.write(buffer);
}

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Class ByteBuffer: Methods {{wrap}} and {{order}}. Class Integer: method {{reverseBytes}}
\[[Harold 97|AA. Java References#Harold 97]\] Chapter 2: Primitive Data Types, Cross Platform issues
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 198|http://cwe.mitre.org/data/definitions/198.html] "&quot;Use of Incorrect Byte Ordering"&quot;

...

06. Integers (INT)      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;06. Integers (INT)      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;INT01-J. Provide mechanisms to handle unsigned data when required