Description
Using the result of arithmetic on lengths directly as an allocation size can cause integer overflow or wraparound.
Potential impact
- The buffer may be smaller than expected, or the program may panic at runtime.
- Input sizes may be used to cause denial of service.
Remediation
- Bound input lengths and multiplication operands before performing arithmetic.
- Verify that the calculation cannot exceed the type's maximum value.
Examples
Before
go
func allocateImage(width, height int) []byte {
return make([]byte, width*height)
}
After
go
func allocateImage(width, height int) []byte {
const maxBufferBytes = 64 * 1024 * 1024
if width <= 0 || height <= 0 || width > maxBufferBytes/height {
return nil
}
size := width * height
return make([]byte, size)
}
Explanation:
- Before: Multiplying the supplied width and height without checking them may overflow or wrap around before allocation.
- After: Rejecting nonpositive values first prevents division errors. The code checks against the service's buffer limit before multiplication. Because the limit fits in
int, the accepted multiplication cannot overflow, and excessive allocations within the integer range are also rejected.