| Wiki Markup |
|---|
Buffer classes defined in the {{ |
java.nio |
IntBuffer, CharBuffer and ByteBuffer) define a variety of wrap() methods. Although these wrap() methods create a new Buffer object, the new Buffer is backed by the array for which it is created. According to the JavaDoc for these methods}} package, such as {{IntBuffer}}, {{CharBuffer}} and {{ByteBuffer}}, define a variety of {{wrap()}} methods. Although these methods create a new {{Buffer}} object, the new {{Buffer}} is backed by the array for which it is created. According to the Java API for these methods \[[API 2006|AA. Bibliography#API 06]\]: |
The new buffer will be backed by the given character array; that is, modifications to the buffer will cause the array to be modified and vice versa.
Consequently, exposing the buffer Exposing these buffers to untrusted code exposes the backing array to malicious modification. Likewise, the duplicate() methods create additional buffers that are backed by the original buffer's backing array; exposing such additional buffers to untrusted code affords the same opportunity for malicious modification of the contents of the original buffer's backing store.
...
This noncompliant code example declares a char array, wraps it with within a Buffer and exposes that Buffer to untrusted code via the getBufferCopy() method. The return value of this method is of type CharBuffer.
| Code Block | ||
|---|---|---|
| ||
final class Wrap {
private char[] dataArray;
public Wrap () {
dataArray = new char[10];
// Initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray);
}
}
|
...
This noncompliant code example uses invokes the duplicate() method to create and return a copy of the CharBuffer. As stated in the contract for the duplicate() method, the returned buffer is backed by the same array as is the original buffer. Consequently, a caller can modify the elements of the backing array; these modifications also affect the original buffer.
...
When the CharBuffer created by the duplicate() method is based on a CharBuffer originally obtained returned by using the wrap() method, modifying the CharBuffer returned by the duplicate() method also modifies the contents of the backing char array; this property can be useful to a malicious attacker.
Compliant Solution (asReadOnlyBuffer())
...