go.lang.correctness.overflow.overflow.integer-overflow-int32

profile photo of semgrepsemgrep
Author
4,989
Download Count*

Detected conversion of the result of a strconv.Atoi command to an int32. This could lead to an integer overflow, which could possibly result in unexpected behavior and even privilege escalation. Instead, use strconv.ParseInt.

Run Locally

Run in CI

Defintion

rules:
  - id: integer-overflow-int32
    message: Detected conversion of the result of a strconv.Atoi command to an
      int32. This could lead to an integer overflow, which could possibly result
      in unexpected behavior and even privilege escalation. Instead, use
      `strconv.ParseInt`.
    languages:
      - go
    severity: WARNING
    patterns:
      - pattern: |
          $F, $ERR := strconv.Atoi($NUM)
          ...
          int32($F)
      - metavariable-comparison:
          metavariable: $NUM
          comparison: $NUM > 2147483647 or $NUM < -2147483648
          strip: true
    metadata:
      category: correctness
      technology:
        - go
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

overflow.go

package main

import (
	"fmt"
	"strconv"
)

func mainInt16Ex1() {
	// ruleid: integer-overflow-int16
	bigValue, err := strconv.Atoi("2147483648")
	if err != nil {
		panic(err)
	}
	value := int16(bigValue)
	fmt.Println(value)
}

func mainInt16Ex2() {
	// ok: integer-overflow-int16
	bigValue, err := strconv.Atoi("10")
	if err != nil {
		panic(err)
	}
	value := int16(bigValue)
	fmt.Println(value)
}

func mainInt32Ex1() {
	// ruleid: integer-overflow-int32
	bigValue, err := strconv.Atoi("2147483648")
	if err != nil {
		panic(err)
	}
	value := int32(bigValue)
	fmt.Println(value)
}

func mainInt32Ex2() {
	// ok: integer-overflow-int32
	bigValue, err := strconv.Atoi("10")
	if err != nil {
		panic(err)
	}
	value := int32(bigValue)
	fmt.Println(value)
}

func main() {
	mainInt16Ex1()
	mainInt16Ex2()
	mainInt32Ex1()
	mainInt32Ex2()
}