gosec
gosec copied to clipboard
False Positive for G602 with bounds check using switch
Summary
I'm getting false positives for G602 when using a switch statement for bounds checking.
Steps to reproduce the behavior
Run gosec against this test case:
func main() {
args := []any{"1"}
switch len(args) - 1 {
case 1:
_ = args[1]
}
}
Output:
[/Users/david/Downloads/try-gosec/main.go:7] - G602 (CWE-118): slice index out of range (Confidence: HIGH, Severity: LOW)
6: case 1:
> 7: _ = args[1]
8: }
Autofix:
Summary:
Gosec : dev
Files : 1
Lines : 9
Nosec : 0
Issues : 1
gosec version
Just installed 1fb6a46 from GitHub.
Go version (output of 'go version')
go version go1.23.2 darwin/arm64
Operating system / Environment
macOS Sequoia
Expected behavior
No issues found.
Actual behavior
False positive for G602.
FWIW, I created this the case based on this code:
func Slice(args ...any) SliceSelector {
const (
startArg = 0
endArg = 1
stepArg = 2
)
// Set defaults.
s := SliceSelector{0, math.MaxInt, 1}
switch len(args) - 1 {
case stepArg:
//nolint:gosec // disable G602 https://github.com/securego/gosec/issues/1250
switch step := args[stepArg].(type) {
case int:
s.step = step
case nil:
// Nothing to do
default:
panic("Third value passed to NewSlice is not an integer")
}
fallthrough
case endArg:
//nolint:gosec // disable G602 https://github.com/securego/gosec/issues/1250
switch end := args[endArg].(type) {
case int:
s.end = end
case nil:
// Negative step: end with minimum int.
if s.step < 0 {
s.end = math.MinInt
}
default:
panic("Second value passed to NewSlice is not an integer")
}
fallthrough
case startArg:
switch start := args[startArg].(type) {
case int:
s.start = start
case nil:
// Negative step: start with maximum int.
if s.step < 0 {
s.start = math.MaxInt
}
default:
panic("First value passed to NewSlice is not an integer")
}
}
return s
}
Can I work on this?
Sure, I assigned it to you.