Possible integer overflow when converting strings

Description

When you convert strings to integers in Go using strconv.Atoi, you might encounter an integer overflow if you assign the result to a smaller integer type like int16 or int32. This is because the size of int type in Go is not fixed and depends on the system architecture (32 bits on a 32-bit system and 64 bits on a 64-bit system). An overflow occurs if the strconv.Atoi return value is too large for the intended smaller integer type.

Remediations

  • Do verify the value from strconv.Atoi fits within the range of your target integer type before conversion.
    if intValue, err := strconv.Atoi(stringValue); err == nil {
    if intValue >= math.MinInt16 && intValue <= math.MaxInt16 {
    int16Value := int16(intValue)
    }
    }
  • Do use type-specific parsing functions like strconv.ParseInt with the appropriate bit size to ensure you get the type you need.
    if int64Value, err := strconv.ParseInt(stringValue, 10, 16); err == nil {
    int16Value := int16(int64Value)
    }
  • Do not cast the result of strconv.Atoi to a smaller integer type without ensuring the value is within the acceptable range for that type.
  • Do not ignore errors from strconv.Atoi. Always handle them to detect conversion problems, including possible overflows.

References

Associated CWE

Configuration

To skip this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --skip-rule=go_gosec_memory_math_big_rat

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=go_gosec_memory_math_big_rat