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 arraybuffer.
Noncompliant Code Example
...
This compliant solution allocates a new CharBuffer and explicitly inserts the contents of the char array into it, before returning it.
| Code Block | ||
|---|---|---|
| ||
final class Wrap {
private char[] dataArray;
Wrap () {
dataArray = new char[10];
// initialize
}
public CharBuffer getBufferCopy() {
CharBuffer cb = CharBuffer.allocate(10);
cb.put(dataArray);
return cb;
}
}
|
...
| Code Block | ||
|---|---|---|
| ||
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// initialize
}
public CharBuffer getBufferCopy() {
return cb.duplicate();
}
}
|
If the CharBuffer obtained created by the duplicate() method is based on a CharBuffer obtained by using the wrap() method, then the contents of the backing char array can be modified maliciously by modifying the particular CharBuffer.
...