Description
When sizing an image buffer, multiplying width by height can overflow int and pass the wrong length to make.
Potential impact
The buffer may be too small, or a runtime panic may interrupt request processing.
Remediation
Choose a maximum byte size for the buffer that fits in int. Check that both dimensions are positive, then check the limit before multiplying.
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)
}
At one byte per pixel, the comparison of width with maxBufferBytes/height limits the buffer to 64 MiB. For other formats, apply the limit to the actual byte count, including bytes per pixel and any row padding.