Piotr Karwasz created COLLECTIONS-903:
-----------------------------------------

             Summary: Validate the capacity read in AbstractHashedMap and 
AbstractReferenceMap doReadObject() as the constructors do
                 Key: COLLECTIONS-903
                 URL: https://issues.apache.org/jira/browse/COLLECTIONS-903
             Project: Commons Collections
          Issue Type: Improvement
          Components: Map
            Reporter: Piotr Karwasz


The constructors of {{AbstractHashedMap}} normalize the requested capacity 
through {{calculateNewCapacity()}} before allocating the table: it is rounded 
up to a power of two and capped at {{MAXIMUM_CAPACITY}}.

Deserialization skips that step. Both {{doReadObject()}} methods allocate the 
table directly from the value read from the stream:

{code:java}
// AbstractHashedMap.doReadObject()
final int capacity = in.readInt();
final int size = in.readInt();
init();
threshold = calculateThreshold(capacity, loadFactor);
data = new HashEntry[capacity];
{code}

{code:java}
// AbstractReferenceMap.doReadObject()
final int capacity = in.readInt();
init();
data = new HashEntry[capacity];
{code}

As a result, a stream can produce tables that the constructors would never 
create. These include tables whose length is not a power of two (the index 
computation assumes one), tables larger than {{MAXIMUM_CAPACITY}}, and a 
{{NegativeArraySizeException}} instead of an {{InvalidObjectException}} for 
negative values.

Following Oracle's Secure Coding Guidelines for Java SE, Guideline 8-3 ("View 
deserialization the same as object construction"), {{doReadObject()}} should 
apply the same checks as the constructors:

{code:java}
final int capacity = calculateNewCapacity(in.readInt());
{code}

In {{AbstractHashedMap}}, the stream also carries the number of entries, and 
the table is rebuilt with {{put()}} anyway. The initial allocation can 
therefore also be limited to what {{size}} and {{loadFactor}} require, with the 
table growing as entries are actually read.

This brings deserialization in line with the constructors. It does not make 
deserializing untrusted data supported. See 
https://commons.apache.org/threat-model-0.1.0.html.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to