Excessive memory allocation from user input

Excessive memory allocation from user input

Description

A small request can use a large amount of memory if it supplies an unchecked length or repeat count to make, bytes.Repeat or strings.Repeat.

Potential impact

Memory exhaustion or a runtime panic can interrupt service.

Remediation

Reject parsing errors, negative values and sizes above the allowed maximum before allocating. Limit request bodies and uploads separately. For repetitions, bound both the count and the output size in bytes.

Examples

Before

go
size, _ := strconv.Atoi(r.FormValue("n"))
buf := make([]byte, size)

After

go
size, err := strconv.Atoi(r.FormValue("n"))
if err != nil || size < 0 || size > 4096 {
    return nil
}
buf := make([]byte, size)

The example creates the byte slice only if strconv.Atoi succeeds and size is between 0 and 4096 inclusive.

References