Incorrect integer conversions

Incorrect integer conversions

Description

Converting an integer to a narrower Go type discards high bits when the value is out of range.

Potential impact

A changed size limit or identifier can lead to excessive resource use or an incorrect authorization decision.

Remediation

For strings, use strconv.ParseInt or strconv.ParseUint with the destination width and signedness, and handle errors. For existing integers, check the lower and upper bounds before converting.

Examples

Before

go
n, _ := strconv.ParseInt(value, 10, 64)
small := int32(n)

After

The excerpts belong inside a function that returns an error.

go
n, err := strconv.ParseInt(value, 10, 32)
if err != nil {
    return err
}
small := int32(n)

For a value outside the signed 32-bit range, strconv.ParseInt(value, 10, 32) returns a boundary value and an error. The example converts to int32 only after the error check passes.

References