JDK-4918916 : (coll) Security BUG in ArrayList constructor from Collection
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 1.4.1
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_2000
  • CPU: x86
  • Submitted: 2003-09-08
  • Updated: 2018-12-19
  • Resolved: 2006-09-28
Related Reports
Relates :  
Name: rl43681			Date: 09/08/2003

java version "1.4.1_02"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_02-b06)
Java HotSpot(TM) Client VM (build 1.4.1_02-b06, mixed mode)

The code in ArrayList constructor from Collection allowes the caller to hold a reference to the internal "elementData" of ArrayList. Then, it can modify it w/o calling the list itself.

This is because the code calls c.toArray() with the *internal* elementData. Then, the implementor of c can hold a reference to it...

Current code:
    public ArrayList(Collection c) {
        size = c.size();
        // Allow 10% room for growth
        elementData = new Object[

  Suggested code:
    public ArrayList(Collection c) {
        Object[] a = c.toArray();
        size = a.length;
        // Allow 10% room for growth
        elementData = new Object[
        System.arraycopy(a, 0, elementData, 0, size);

This bug can be reproduced always.
(Incident Review ID: 206459) 

EVALUATION Jason writes: "I agree, not a defect. Collection.toArray states that the returned array must be safe, so the "evilCollection" breaks the Collection interface contract. So I really don't see why the ArrayList (and everyone else) should have to defend against that." Three Collection Framework maintainers agree: Not a Defect. Time to close this.

WORK AROUND Use new ArrayList(new ArrayList(evilCollection))

EVALUATION The implementation of the ArrayList(Collection) constructor was changed by 6347106: (coll) Make ArrayList(Collection) more threadsafe to use toArray() instead of toArray(Collection). Unfortunately, the problem remains; a malicious argument collection can retain a reference to the returned array and later mutate the internal representation of the ArrayList. Sorry, ArrayList is not suitable for uses where the source is completely untrusted.

EVALUATION It's not clear that this represents a real security bug in ArrayList. Any collection whose toArray method retained a reference to the generated array and later modified it would trash any users of the array. This is a borderline case, where defensive programming may or may not be worthwhile. ###@###.### 2003-11-09