Skip to content

G602 (CWE-118): slice index out of range false positive #1406

@dev-gto

Description

@dev-gto

Hello all,

the gosec v2.22.10 (released yesterday) started to complain regarding false positives for G602 (CWE-118): slice index out of range

for instance, the following code shouldn't generate warning, should it?

package main

func main() {
	value := "1234567890"
	weight := []int{2, 3, 4, 5, 6, 7}
	wLen := len(weight)
	l := len(value) - 1

	addr := make([]any, 7)
	sum := 0
	weight[2] = 3
	for i := l; i >= 0; i-- {
		v := int(value[i] - '0')
		if v < 0 || v > 9 {
			println("invalid number at column", i+1)
			break
		}
		addr[2] = v
		sum += v * weight[(l-i)%wLen]
	}
	println(sum)
}
[/{redacted}/main.go:21] - G602 (CWE-118): slice index out of range (Confidence: HIGH, Severity: LOW)
    20: 		addr[2] = v
  > 21: 		sum += v * weight[(l-i)%wLen]
    22: 	}

Autofix: 

[/{redacted}/main.go:20] - G602 (CWE-118): slice index out of range (Confidence: HIGH, Severity: LOW)
    19: 		}
  > 20: 		addr[2] = v
    21: 		sum += v * weight[(l-i)%wLen]

Autofix: 

Summary:
  Gosec  : dev
  Files  : 1
  Lines  : 24
  Nosec  : 0
  Issues : 2

Can you please evaluate this?

Kind regards,

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions