Commit graph

161 commits

Author SHA1 Message Date
Oleksandr Redko
92de0ee7a2
Replace old golang.org links with new go.dev (#1271)
Some checks are pending
CI / test (map[go:1.22.10 golangci:latest]) (push) Waiting to run
CI / test (map[go:1.23.4 golangci:latest]) (push) Waiting to run
CI / coverage (push) Blocked by required conditions
Security Scan / build (push) Waiting to run
2024-12-16 15:18:51 +01:00
Cosmin Cojocar
229cf63a09 Remove the decryption funtions/methods from G407 check
Some checks failed
CI / test (map[go:1.22.9 golangci:latest]) (push) Has been cancelled
CI / test (map[go:1.23.3 golangci:latest]) (push) Has been cancelled
Security Scan / build (push) Has been cancelled
CI / coverage (push) Has been cancelled
The nonce in the decryption functions/methods is typically provided and
it should not be randomnly generated.

Change-Id: Id0df0d43aecb2aadb00b9fa901bd060a43a201c5
Signed-off-by: Cosmin Cojocar <ccojocar@google.com>
2024-11-26 10:14:30 +01:00
Dave Henderson
9b13cd5ab4 Fix G115 false positive when going from parsed uint to larger int
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
2024-11-26 09:36:56 +01:00
czechbol
1f3bdd9349
G115 Struct Attribute Checks (#1221)
* allow struct attributes checks

* fix explicit check results
2024-09-16 10:30:54 +02:00
czechbol
eaedce9a8b
Improvement the int conversion overflow logic to handle bound checks (#1194)
* add test cases

Signed-off-by: czechbol <adamludes@gmail.com>

* fix bounds check logic

Signed-off-by: czechbol <adamludes@gmail.com>

* tweak test cases

Signed-off-by: czechbol <adamludes@gmail.com>

* fix codestyle

Signed-off-by: czechbol <adamludes@gmail.com>

* improve bounds check logic

Signed-off-by: czechbol <adamludes@gmail.com>

* max recursion depth

Signed-off-by: czechbol <adamludes@gmail.com>

* add test case for len function

Signed-off-by: czechbol <adamludes@gmail.com>

* relax len function bounds checks

Co-authored-by: Ben Krieger <ben.krieger@intel.com>

* handle cases when convert instruction is after the if blocks

Signed-off-by: czechbol <adamludes@gmail.com>

* improve range check discovery, add tests

Signed-off-by: czechbol <adamludes@gmail.com>

* refactor for readability

Signed-off-by: czechbol <adamludes@gmail.com>

* add cap function test

Signed-off-by: czechbol <adamludes@gmail.com>

* calculate signed min without throwing overflow warnings

Signed-off-by: czechbol <adamludes@gmail.com>

* perform bounds checks int size calculations

Signed-off-by: czechbol <adamludes@gmail.com>

* basic equal operator logic

Signed-off-by: czechbol <adamludes@gmail.com>

* uintptr -> unsafe.Pointer test case

Signed-off-by: czechbol <adamludes@gmail.com>

* fix review comments

Signed-off-by: czechbol <adamludes@gmail.com>

* Rebase and fix go module

Change-Id: I8da6495eaaf25b1739389aa98492bd7df338085b
Signed-off-by: Cosmin Cojocar <ccojocar@google.com>

* fix false positive for negated value

Signed-off-by: czechbol <adamludes@gmail.com>

* fix range conditions

Signed-off-by: czechbol <adamludes@gmail.com>

* Ignore the golangci/gosec G115 warning

Change-Id: I0db56cb0a5f9ab6e815e2480ec0b66d7061b23d3
Signed-off-by: Cosmin Cojocar <ccojocar@google.com>

---------

Signed-off-by: czechbol <adamludes@gmail.com>
Signed-off-by: Cosmin Cojocar <ccojocar@google.com>
Co-authored-by: Ben Krieger <ben.krieger@intel.com>
Co-authored-by: Cosmin Cojocar <ccojocar@google.com>
2024-09-04 16:09:54 +02:00
William Bergeron-Drouin
ea5b2766bb
fix: G602 support for nested conditionals with bounds check (#1201)
* Recursive fix

* Add some more test cases

* Fix formatting

* Add depth check
2024-09-04 11:07:42 +02:00
Dimitar Banchev
a14ca4ac59 Added another test case in order to increase code coverage 2024-08-30 19:35:07 +02:00
Dimitar Banchev
b4c746962f Formatting problems(CI was not passing) 2024-08-30 19:35:07 +02:00
Dimitar Banchev
7f8f654235 Updated analyzer to use new way of initialization
* Removed old way of initializing analyzers
* Added the new analyzer to the rest of the default analyzers
* Fixed small bug in the rule
* Removed the test for the new analyzer from the file responsible for testing the rules
* Merged the diffrent examples into 1 variable
* Added tests for the analyzer
* Removed code that was used for testing rules, but it was used to test the analyzer
2024-08-30 19:35:07 +02:00
Dimitar Banchev
a26215cf23 Migrated the rule to the analyzers folder 2024-08-30 19:35:07 +02:00
Dimitar Banchev
0eb8143c23 Added new rule G407(hardcoded IV/nonce)
The rule is supposed to detect for the usage of hardcoded or static nonce/Iv in many encryption algorithms:

* The different modes of AES (mainly tested here)
* It should be able to work with ascon

Currently the rules doesn't check when constant variables are used.

TODO: Improve the rule, to detected for constatant variable usage
2024-08-30 19:35:07 +02:00
Ben Krieger
4ae73c8ba3 Fix conversion overflow false positive when using ParseUint 2024-08-28 08:58:42 +02:00
czechbol
bcec04e784 Fix conversion overflow false positives when they are checked or pre-determined
Signed-off-by: czechbol <adamludes@gmail.com>
2024-08-26 16:57:12 +02:00
Cosmin Cojocar
ab3f6c1c83 Fix false positive in conversion overflow check from uint8/int8 type
Change-Id: I543545e22fa12de0d85dcf92664a0a54e8f7244a
Signed-off-by: Cosmin Cojocar <ccojocar@google.com>
2024-08-22 09:47:52 +02:00
Cosmin Cojocar
8467f012e0 Add more test to cover more use cases for G115 rule
Change-Id: Icb60fe14ae12439c1ee0e507a407a23ce4c64c85
Signed-off-by: Cosmin Cojocar <ccojocar@google.com>
2024-08-21 15:00:06 +02:00
Rahul Gadi
81cda2f91f
Allow excluding analyzers globally (#1180)
* This change does not exclude analyzers for inline comment
* Changed the expected issues count for G103, G109 samples for test. Previously G115 has been included in the issue count
* Show analyzers IDs(G115, G602) in gosec usage help
* See #1175
2024-08-20 10:43:40 +02:00
Alex Gartner
08b94f9392 Resolve underlying type to detect overflows in type aliases 2024-07-20 10:06:43 +02:00
Alex Gartner
007626773c Fix multifile ignores 2024-07-15 09:00:36 +02:00
Dimitar Banchev
9a4a741e6b Added more rules
* Rule G406 responsible for the usage of deprecated MD4 and RIPEMD160 added.
* Rules G506, G507 responsible for tracking the usage of the already mentioned libraries added.
* Slight changes in the Makefile(`make clean` wasn't removing all expected files)
* Added license to `analyzer_test.go`
2024-06-25 13:18:27 +02:00
Dimitar Banchev
6382394ce8 Fixed coverage workflow
* Renamed file(removed space)
* Changed the expected issues ( 1 -> 2)
2024-06-24 15:25:54 +02:00
Dimitar Banchev
58e4fccc13 Split the G401 rule into two separate ones
Now the G401 rule is split into hashing and encryption algorithms.

G401 is responsible for checking the usage of MD5 and SHA1, with corresponding CWE of 328.
And G405(New rule) is responsible for checking the usege of DES and RC4, with corresponding CWE of 327.
2024-06-24 15:25:54 +02:00
Cosmin Cojocar
ac75d44f56 Fix nosec when applied to a block
Handle properly nosec directive when applied to a block or as a single
line on a multi-line issue.

Signed-off-by: Cosmin Cojocar <cosmin@cojocar.ch>
2024-05-28 12:54:05 +02:00
Cosmin Cojocar
4bf5667f66 Add a new rule to detect integer overflow on integer types conversion
Signed-off-by: Cosmin Cojocar <cosmin@cojocar.ch>
2024-05-27 13:03:01 +02:00
Cosmin Cojocar
dc5e5a99d0 Add a unit test to detect the false negative in rule G306 for os.ModePerm permissions
Signed-off-by: Cosmin Cojocar <cosmin@cojocar.ch>
2024-05-14 15:33:23 +02:00
Hiroki Yorimitsu
be378e682f Add support for math/rand/v2 added in Go 1.22 2024-03-07 16:33:18 +01:00
Cosmin Cojocar
2aad3f02a5 Fix lint warnings by properly formatting the files
Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-12-08 14:46:36 +01:00
Adam Kaplan
0e2a61899a chore: Refactor Sample Code to Separate Files
Split the code in `source.go` to individual sample files, one per rule.
This will help contributors submit samples for new rules, or
improvements to existing rules. The cgo sample was all that was left
after refactoring, which resulted in its own sample file.

Sample code was also formatted to have some level of consistency.
Each sample go "file" attempts to keep the formatting of `gofmt`, and
each code sample is in its own section in the sample file.

Signed-off-by: Adam Kaplan <adam@adambkaplan.com>
2023-12-08 14:46:36 +01:00
Cosmin Cojocar
3188e3fb8e Ensure ignores are handled properly for multi-line issues
Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-11-10 10:48:04 +01:00
Cosmin Cojocar
0ec6cd95d7 Refactor how ignored issues are tracked
Track ignored issues using file location instead of a AST node. There are issues linked to a different AST node than the original node used to start the scan.

Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-10-13 14:11:08 +02:00
Cosmin Cojocar
616520f44f
Update the list of unsafe functions detected by the unsafe rule (#1033)
Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-10-10 09:47:36 +02:00
Cosmin Cojocar
0d332a1027 Add a new rule which detects when a file is created with os.Create but the configured permissions are less than 0666
It seems that the os.Create will create by default a file with 0666 permissions.

This should be detected when the configured permissions are less than 0666. By default will not detect this case
unless the more restrictive mode is configured.

Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-09-25 13:24:34 +02:00
Cosmin Cojocar
e02e2f6d5b Redesign and reimplement the slice out of bounds check using SSA code representation
Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-09-20 10:19:51 +02:00
Cosmin Cojocar
6c93653a29
Fix hardcoded_credentials rule to only match on more specific patterns (#1009)
* Fix hardcoded_credentials rule to only match on more specific patterns

Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>

* Fix lint warnings

Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>

* Fix double escape in regexps

Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>

---------

Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-09-05 18:00:02 +02:00
Cosmin Cojocar
beef1250a4
Exclude maps from slince bounce check rule (#1006)
Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2023-08-23 17:17:14 +02:00
Alexander Yastrebov
21d13c9a9b
Ignore struct pointers in G601 (#1003)
Updates https://github.com/securego/gosec/issues/966

Signed-off-by: Alexander Yastrebov <yastrebov.alex@gmail.com>
2023-08-18 17:05:17 +02:00
Audun
bf7feda2b9
fix: correctly identify infixed concats as potential SQL injections (#987) 2023-07-25 17:13:07 +02:00
Morgen Malinoski
a018cf0fbb
Feature: G602 Slice Bound Checking (#973)
* Added slice bounds testing for slice expressions.

* Added checking slice index.

* Added test for reassigning slice.

* Store capacities on reslicing.

* Scope change clears map. Func name used to track slices.

* Map CallExpr to check bounds when passing to functions.

* Fixed linter errors.

* Updated rulelist with CWE mapping.

* Added comment for NewSliceBoundCheck.

* Addressed nil cap runtime error.

* Replaced usage of nil in call arg map with dummy callexprs.

* Updated comments, wrapped error return, addressed other review concerns.
2023-06-21 09:56:36 +02:00
Morgen Malinoski
abeab1092d
Feature: G101 match variable values and names (#971)
* G101 now checks LHS of ValueAssignments for patternValue.

* Added matching string literals in equality check.

* Added patternValue matching for ValueSpec.

* Ran gci to fix linter error.

* Added tests and updated regex to be more inclusive.

* Addressed short-circuit eval for isHighEntropy and non-standard ok variable.

* Resolved unhandled error and added more tests.

* Flattened code to make it more readable.

* Added better comments.

* Added new regex for Google API Key, GitHub PAT, and GoogleOAuth.

* Gofmt'ed the test cases.
2023-06-15 10:18:03 +02:00
futuretea
bd58600acf Recognize struct field in G601
Signed-off-by: futuretea <1913508671@qq.com>
2023-06-02 17:17:10 +02:00
Oleksandr Redko
1f689968ec Fix typos in comments, vars and tests 2023-05-30 08:26:41 +02:00
Matthieu MOREL
d6aeaad931
correct gci linter (#946)
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
2023-03-30 09:31:24 +02:00
Rick Moran
f823a7e92b
Check nil pointer when variable is declared in a different file 2023-03-08 14:42:45 +01:00
Cosmin Cojocar
d5a9c73723
Remove rule G307 which checks when an error is not handled when a file or socket connection is closed (#935)
* Remove read only types from unsafe defer rules

* Remove rule G307 which checks when an error is not handled when a file or socket connection is closed

This doesn't seem to bring much value from security perspective, and it caused a lot of controversy since
is a very common pattern in Go.

* Mentioned in documentation that rule G307 is retired

* Clean up the test for rule G307
2023-02-24 14:04:13 +01:00
bean.zhang
a624254e39
Update hardcoded_credentials.go fix: adaper equal expr which const value at left (#917)
* Update hardcoded_credentials.go

adaper equal expr which const value at left.
```
if "Tr0ub4dour_UPL&&LOlo" == pwd
```

* Update hardcoded_credentials.go

check ident not equal nil

* adapter const == key hardcoded, add testcases
2023-01-31 09:52:37 +01:00
Cosmin Cojocar
5874e63c9e
Track back when a file path was sanitized with filepath.Clean (#912)
* Track back when a file path was sanitized with filepath.Clean

* Remove unused argument to fix lint warnings
2023-01-09 16:26:20 +01:00
Cosmin Cojocar
fd280360cd
Fix the TLS config rule when parsing the settings from a variable (#911) 2023-01-09 15:10:44 +01:00
Dmitry Golushko
44f484fdc7
Additional types for bad defer check (#897)
* Additional types for bad defer check

* Ignore new check in tlsconfig.go
2022-11-30 09:38:46 +01:00
Sebastiaan van Stijn
0ae0174c25
Refactor to support duplicate imports with different aliases (#865)
The existing code assumed imports to be either imported, or imported with an
alias. Badly formatted files may have duplicate imports for a package, using
different aliases.

This patch refactors the code, and;

Introduces a new `GetImportedNames` function, which returns all name(s) and
aliase(s) for a package, which effectively combines `GetAliasedName` and
`GetImportedName`, but adding support for duplicate imports.

The old `GetAliasedName` and `GetImportedName` functions have been rewritten to
use the new function and marked deprecated, but could be removed if there are no
external consumers.

With this patch, the linter is able to detect issues in files such as;

    package main

    import (
        crand "crypto/rand"
        "math/big"
        "math/rand"
        rand2 "math/rand"
        rand3 "math/rand"
    )

    func main() {
        _, _ = crand.Int(crand.Reader, big.NewInt(int64(2))) // good

        _ = rand.Intn(2) // bad
        _ = rand2.Intn(2)  // bad
        _ = rand3.Intn(2)  // bad
    }

Before this patch, only a single issue would be detected:

    gosec --quiet .

    [main.go:14] - G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
        13:
      > 14: 	_ = rand.Intn(2) // bad
        15: 	_ = rand2.Intn(2)  // bad

With this patch, all issues are identified:

    gosec --quiet .

    [main.go:16] - G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
        15: 	_ = rand2.Intn(2)  // bad
      > 16: 	_ = rand3.Intn(2)  // bad
        17: }

    [main.go:15] - G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
        14: 	_ = rand.Intn(2) // bad
      > 15: 	_ = rand2.Intn(2)  // bad
        16: 	_ = rand3.Intn(2)  // bad

    [main.go:14] - G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
        13:
      > 14: 	_ = rand.Intn(2) // bad
        15: 	_ = rand2.Intn(2)  // bad

While working on this change, I noticed that ImportTracker.TrackFile() was not able
to find import aliases;  Analyser.Check() called both ImportTracker.TrackFile() and
ast.Walk(), which (with the updated ImportTracker) resulted in importes to be in-
correctly included multiple times (once with the correct alias, once with the default).

I updated ImportTracker.TrackFile() to fix this, but with the updated ImportTracker,
Analyser.Check() no longer has to call ImportTracker.TrackFile() separately, as ast.Walk()
already handles the file, and will find all imports.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-10-17 10:59:18 +02:00
Sebastiaan van Stijn
dfde579243 Fix false positives for G404 with aliased packages
It appears that `GetImportedName` returns _both_ aliased and non-aliased imports.
As a result, a file having both crypto/rand and math/rand (but aliased) would
trigger false positives on G404. Given the following file;

```go
package main

import (
	"crypto/rand"
	"math/big"
	rnd "math/rand"
)

func main() {
	_, _ = rand.Int(rand.Reader, big.NewInt(int64(2)))
	_ = rnd.Intn(2)
}
```

And patching for debugging;

```patch
diff --git a/helpers.go b/helpers.go
index 437d032..80f4233 100644
--- a/helpers.go
+++ b/helpers.go
@@ -250,6 +250,8 @@ func GetBinaryExprOperands(be *ast.BinaryExpr) []ast.Node {
 // GetImportedName returns the name used for the package within the
 // code. It will ignore initialization only imports.
 func GetImportedName(path string, ctx *Context) (string, bool) {
+       fmt.Printf("%+v", ctx.Imports.Imported)
+       os.Exit(1)
        importName, imported := ctx.Imports.Imported[path]
        if !imported {
                return "", false
```

Would show that `math/rand` was included in the list, using it's non-aliased
name (`:rand`).

    gosec -quiet .
    map[crypto/rand:rand math/big:big math/rand:rand]

This patch works around this problem by reversing the order in which imports
are resolved in `MatchCallByPackage()`. Aliased packages are tried first, after
which non-aliased imports are tried.

Given the example application mentioned above:

Before this patch:

```bash
gosec -quiet .
Results:

[/Users/sebastiaan/Projects/test/gosec-issue/main.go:10] - G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
    9: func main() {
  > 10: 	_, _ = rand.Int(rand.Reader, big.NewInt(int64(2)))
    11: 	_ = rnd.Intn(2)
```

With this patch applied:

```bash
    gosec --quiet .
    Results:

    [/Users/sebastiaan/Projects/test/gosec-issue/main.go:11] - G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
        10: 	_, _ = rand.Int(rand.Reader, big.NewInt(int64(2)))
      > 11: 	_ = rnd.Intn(2)
        12: }
```

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-09-05 09:49:02 +02:00
Cosmin Cojocar
0ba05e160a chore: fix lint warnings
Signed-off-by: Cosmin Cojocar <gcojocar@adobe.com>
2022-08-08 10:56:19 +02:00