Integer Overflow or Wraparound

ID

go.integer_overflow

Severity

high

Resource

Risky Values

Language

Go

Tags

CWE:190, CWE:681, NIST.SP.800-53, PCI-DSS:6.5.6

Description

Integer overflow occurs when an operation attempts to create a numeric value that is outside the range that can be represented with a given number of bits.

In the Go language, such issues might arise due to arithmetic operations that exceed the range of int, uint, int64, uint64, etc.

Rationale

Integer overflow can lead to unexpected behavior, logic errors, or even critical vulnerabilities such as buffer overflows if unchecked values control memory allocation.

In Go, integer overflow wraps around by default, meaning an overflowed value won’t throw an error but will start from the minimum possible value of the type.

package integer_overflow

import (
	"strconv"
)

func dummy(value string) int32 {
	parsed, err := strconv.Atoi(value) // Convert string to integer
	if err != nil {
		panic(err) // Panic if conversion fails
	}
	return int32(parsed) // FLAW: May cause overflow if 'parsed' exceeds int32 limits
}

In this code, if the value string represents a number larger than int32 can hold, converting int to int32 will wrap the value, causing overflow.

Remediation

To mitigate integer overflow:

  1. Use appropriate data validation to ensure input values are within the allowable range before conversion.

  2. Check if the parsed value exceeds the maximum or minimum bounds.

  3. Consider using a larger data type or a library like math/big if the input value can be very large.

package main

import (
	"fmt"
	"math"
	"strconv"
)

func dummySafe(value string) (int32, error) {
	parsed, err := strconv.Atoi(value) // Convert string to integer
	if err != nil {
		return 0, err // Return error if conversion fails
	}
	if parsed > math.MaxInt32 || parsed < math.MinInt32 {
		return 0, fmt.Errorf("value out of int32 range") // Return error if out of range
	}
	return int32(parsed), nil // Safely return converted value
}

References

  • CWE-190 : Integer Overflow or Wraparound.

  • CWE-681 : Incorrect Conversion between Numeric Types.