You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

The buffer classes (such as IntBuffer, CharBuffer and ByteBuffer) defined in the java.nio package define wrap() methods, varying in parameters. The wrap() methods create a new Buffer object, however, the elements continue to persist in the backing array from which the buffer was created. If the buffer is altered by untrusted code, the backing array is maliciously modified. Likewise, the duplicate() method allows the creation of copies of the buffer but a caller may indirectly alter the contents of the backing array.

Noncompliant Code Example

This noncompliant code example declares a char array and allows untrusted code to obtain a copy using the getBufferCopy() method. The return value of this method is required to be of type CharBuffer.

final class Wrap {
  private char[] dataArray;
  
  public Wrap () {
    dataArray = new char[10];
    // initialize
  }
	
  public CharBuffer getBufferCopy() {
    return CharBuffer.wrap(dataArray);	
  }
}

Noncompliant Code Example

This noncompliant code example uses the duplicate() method to create and return a copy of the char array. The returned buffer allows the caller to indirectly modify the elements of the array.

final class Wrap {
  private char[] dataArray;

  Wrap () {
    dataArray = new char[10];
    // initialize
  }
	
  public CharBuffer getBufferCopy() {
    CharBuffer cb = CharBuffer.allocate(10);
    return cb.duplicate();
  }
}

Compliant Solution

This compliant solution returns a read-only view of the char array, in the form of a CharBuffer. Attempts to modify the elements of the CharBuffer result in a java.nio.ReadOnlyBufferException.

final class Wrap {
  private char[] dataArray;

  Wrap () {
    dataArray = new char[10];
    // initialize
  }
	
  public CharBuffer getBufferCopy() {
    CharBuffer cb = CharBuffer.allocate(10);
    return cb.asReadOnlyBuffer();
  }
}

Risk Assessment

Returning buffers created using the wrap() or duplicate() methods may allow an untrusted caller to alter the contents of the original data.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO37- J

medium

likely

low

P18

L1

Automated Detection

TODO

Related Vulnerabilities

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

References

[[API 06]] class CharBuffer
[[Hitchens 02]] 2.3 Duplicating Buffers


FIO36-J. Do not create multiple buffered wrappers on an InputStream      08. Input Output (FIO)      08. Input Output (FIO)

  • No labels