Description
Converting a large integer directly to a smaller integer type can truncate or wrap its value. If the result controls a security-sensitive size or permission, this may bypass validation.
Potential impact
- Limits or identifiers may become unintended values.
- Incorrect values may cause denial of service or authorization errors.
Remediation
- Call
strconv.ParseIntorstrconv.ParseUintwith the required bit size and check the error. - Check explicit upper and lower bounds before conversion.
Examples
Before
go
n, _ := strconv.ParseInt(value, 10, 64)
small := int32(n)
After
This excerpt belongs inside a function that returns an error.
go
n, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return err
}
small := int32(n)
Explanation:
- Before: A value parsed into a larger integer type may be truncated or wrapped when converted to a smaller type.
- After: Parse within the 32-bit range and reject errors before using the value. On overflow,
ParseIntreturns a boundary value together with an error, so ignoring the error is unsafe.