From 78e7ae626ab3273c6120009fba22f594f3dc2b3f Mon Sep 17 00:00:00 2001 From: Dave Henderson Date: Mon, 25 Nov 2024 21:04:20 -0500 Subject: [PATCH] Fix G115 false positive when going from parsed uint to larger int Signed-off-by: Dave Henderson --- analyzers/conversion_overflow.go | 7 ++++++- testutils/g115_samples.go | 34 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/analyzers/conversion_overflow.go b/analyzers/conversion_overflow.go index bebe9b8340..d2de110295 100644 --- a/analyzers/conversion_overflow.go +++ b/analyzers/conversion_overflow.go @@ -226,7 +226,12 @@ func isStringToIntConversion(instr *ssa.Convert, dstType string) bool { if err != nil { return false } - isSafe := bitSizeValue <= dstInt.size && signed == dstInt.signed + + // we're good if: + // - signs match and bit size is <= than destination + // - parsing unsigned and bit size is < than destination + isSafe := (bitSizeValue <= dstInt.size && signed == dstInt.signed) || + (bitSizeValue < dstInt.size && !signed) return isSafe } } diff --git a/testutils/g115_samples.go b/testutils/g115_samples.go index 9c889dc618..565050a4e1 100644 --- a/testutils/g115_samples.go +++ b/testutils/g115_samples.go @@ -426,6 +426,40 @@ import ( "strconv" ) +func main() { + var a string = "13" + b, _ := strconv.ParseUint(a, 10, 16) + c := int(b) + fmt.Printf("%d\n", c) +} + `, + }, 0, gosec.NewConfig()}, + {[]string{ + ` +package main + +import ( + "fmt" + "strconv" +) + +func main() { + var a string = "13" + b, _ := strconv.ParseUint(a, 10, 31) + c := int32(b) + fmt.Printf("%d\n", c) +} + `, + }, 0, gosec.NewConfig()}, + {[]string{ + ` +package main + +import ( + "fmt" + "strconv" +) + func main() { var a string = "13" b, _ := strconv.ParseInt(a, 10, 8)