Compare commits

...
14 Commits
12 changed files with 79 additions and 45 deletions

No files matched your search

+16 -4
View File
@@ -22,11 +22,9 @@
</p> </p>
</p> </p>
Gitleaks is a SAST tool for detecting hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code. Gitleaks is a SAST tool for **detecting** and **preventing** hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code.
#### 💫⭐✨ Temporary README message 💫⭐✨ [![asciicast](https://asciinema.org/a/455683.svg)](https://asciinema.org/a/455683)
It would be so great if you could fill out this quick gitleaks [user survey](https://docs.google.com/forms/d/1poUqZfEamDY1kCp8v8hU6N3fUj8C5_lVNBD_cDe-GT4).
<3
## Getting Started ## Getting Started
Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the [releases page](https://github.com/zricethezav/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo. Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the [releases page](https://github.com/zricethezav/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo.
@@ -291,6 +289,20 @@ the generic rule has the string `generic` somewhere in the rule's `id`. If a sec
will be given precedence. will be given precedence.
## Sponsorships
<p align="left">
<a href="https://www.tines.com/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks">
<img alt="Tines Sponsorship" src="https://user-images.githubusercontent.com/15034943/146411864-4878f936-b4f7-49a0-b625-f9f40c704bfa.png" width=200>
</a>
</p>
<a href="https://www.typeform.com/">
<img src="https://user-images.githubusercontent.com/15034943/146945294-a6473d55-86b8-4f53-941e-7f185ad6b3d7.png" width=200/>
</a>
</p>
## Exit Codes ## Exit Codes
You can always set the exit code when leaks are encountered with the --exit-code flag. Default exit codes below: You can always set the exit code when leaks are encountered with the --exit-code flag. Default exit codes below:
``` ```
+21 -21
View File
@@ -2,33 +2,33 @@ title = "gitleaks config"
# Gitleaks rules are defined by regular expressions and entropy ranges. # Gitleaks rules are defined by regular expressions and entropy ranges.
# Some secrets have unique signatures which make detecting those secrets easy. # Some secrets have unique signatures which make detecting those secrets easy.
# Examples of those secrets would be Gitlab Personal Access Tokens, AWS keys, and Github Access Tokens. # Examples of those secrets would be Gitlab Personal Access Tokens, AWS keys, and Github Access Tokens.
# All these examples have defined prefixes like `glpat`, `AKIA`, `ghp_`, etc. # All these examples have defined prefixes like `glpat`, `AKIA`, `ghp_`, etc.
# #
# Other secrets might just be a hash which means we need to write more complex rules to verify # Other secrets might just be a hash which means we need to write more complex rules to verify
# that what we are matching is a secret. # that what we are matching is a secret.
# #
# Here is an example of a semi-generic secret # Here is an example of a semi-generic secret
# #
# discord_client_secret = "8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ" # discord_client_secret = "8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ"
# #
# We can write a regular expression to capture the variable name (identifier), # We can write a regular expression to capture the variable name (identifier),
# the assignment symbol (like '=' or ':='), and finally the actual secret. # the assignment symbol (like '=' or ':='), and finally the actual secret.
# The structure of a rule to match this example secret is below: # The structure of a rule to match this example secret is below:
# #
# Beginning string # Beginning string
# quotation # quotation
# │ End string quotation # │ End string quotation
# │ │ # │ │
# ▼ ▼ # ▼ ▼
# (?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"] # (?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]
# #
# ▲ ▲ ▲ # ▲ ▲ ▲
# │ │ │ # │ │ │
# │ │ │ # │ │ │
# identifier assignment symbol # identifier assignment symbol
# Secret # Secret
# #
[[rules]] [[rules]]
id = "gitlab-pat" id = "gitlab-pat"
description = "GitLab Personal Access Token" description = "GitLab Personal Access Token"
@@ -37,7 +37,7 @@ regex = '''glpat-[0-9a-zA-Z\-]{20}'''
[[rules]] [[rules]]
id = "aws-access-token" id = "aws-access-token"
description = "AWS" description = "AWS"
regex = '''AKIA[0-9A-Z]{16}''' regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
# Cryptographic keys # Cryptographic keys
[[rules]] [[rules]]
@@ -140,7 +140,7 @@ secretGroup = 3
[[rules]] [[rules]]
id = "slack-web-hook" id = "slack-web-hook"
description = "Slack Webhook" description = "Slack Webhook"
regex = '''https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}''' regex = '''https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8,12}/[a-zA-Z0-9_]{24}'''
[[rules]] [[rules]]
id = "twilio-api-key" id = "twilio-api-key"
@@ -381,7 +381,7 @@ secretGroup = 3
[[rules]] [[rules]]
id = "ionic-api-token" id = "ionic-api-token"
description = "Ionic API token" description = "Ionic API token"
regex = '''ion_(?i)[a-z0-9]{42}''' regex = '''(?i)(ionic[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](ion_[a-z0-9]{42})['\"]'''
[[rules]] [[rules]]
id = "linear-api-token" id = "linear-api-token"
+2
View File
@@ -17,6 +17,8 @@ type Options struct {
Redact bool Redact bool
} }
const MAXGOROUTINES = 4
func DetectFindings(cfg config.Config, b []byte, filePath string, commit string) []report.Finding { func DetectFindings(cfg config.Config, b []byte, filePath string, commit string) []report.Finding {
var findings []report.Finding var findings []report.Finding
linePairs := regexp.MustCompile("\n").FindAllIndex(b, -1) linePairs := regexp.MustCompile("\n").FindAllIndex(b, -1)
+12
View File
@@ -34,6 +34,10 @@ func TestDetectFindings(t *testing.T) {
File: "tmp.go", File: "tmp.go",
RuleID: "aws-access-key", RuleID: "aws-access-key",
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
StartLine: 1,
EndLine: 1,
StartColumn: 15,
EndColumn: 34,
}, },
}, },
}, },
@@ -69,6 +73,10 @@ func TestDetectFindings(t *testing.T) {
RuleID: "discord-api-key", RuleID: "discord-api-key",
Tags: []string{}, Tags: []string{},
Entropy: 3.7906237, Entropy: 3.7906237,
StartLine: 1,
EndLine: 1,
StartColumn: 7,
EndColumn: 93,
}, },
}, },
}, },
@@ -91,6 +99,10 @@ func TestDetectFindings(t *testing.T) {
RuleID: "generic-api-key", RuleID: "generic-api-key",
Tags: []string{}, Tags: []string{},
Entropy: 3.7906237, Entropy: 3.7906237,
StartLine: 1,
EndLine: 1,
StartColumn: 22,
EndColumn: 93,
}, },
}, },
}, },
+5 -5
View File
@@ -7,7 +7,6 @@ import (
"sync" "sync"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
godocutil "golang.org/x/tools/godoc/util"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report" "github.com/zricethezav/gitleaks/v8/report"
@@ -20,6 +19,7 @@ func FromFiles(source string, cfg config.Config, outputOptions Options) ([]repor
findings []report.Finding findings []report.Finding
mu sync.Mutex mu sync.Mutex
) )
concurrentGoroutines := make(chan struct{}, MAXGOROUTINES)
g, _ := errgroup.WithContext(context.Background()) g, _ := errgroup.WithContext(context.Background())
paths := make(chan string) paths := make(chan string)
g.Go(func() error { g.Go(func() error {
@@ -40,15 +40,15 @@ func FromFiles(source string, cfg config.Config, outputOptions Options) ([]repor
}) })
for pa := range paths { for pa := range paths {
p := pa p := pa
concurrentGoroutines <- struct{}{}
g.Go(func() error { g.Go(func() error {
defer func() {
<-concurrentGoroutines
}()
b, err := os.ReadFile(p) b, err := os.ReadFile(p)
if err != nil { if err != nil {
return err return err
} }
if !godocutil.IsText(b) {
return nil
}
fis := DetectFindings(cfg, b, p, "") fis := DetectFindings(cfg, b, p, "")
for _, fi := range fis { for _, fi := range fis {
// need to add 1 since line counting starts at 1 // need to add 1 since line counting starts at 1
+6 -7
View File
@@ -9,7 +9,6 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report" "github.com/zricethezav/gitleaks/v8/report"
godocutil "golang.org/x/tools/godoc/util"
) )
// FromGit accepts a gitdiff.File channel (structure output from `git log -p`) and a configuration // FromGit accepts a gitdiff.File channel (structure output from `git log -p`) and a configuration
@@ -19,16 +18,20 @@ func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Option
var findings []report.Finding var findings []report.Finding
mu := sync.Mutex{} mu := sync.Mutex{}
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
concurrentGoroutines := make(chan struct{}, MAXGOROUTINES)
commitMap := make(map[string]bool) commitMap := make(map[string]bool)
for f := range files { for f := range files {
// keep track of commits for logging // keep track of commits for logging
if f.PatchHeader != nil { if f.PatchHeader != nil {
commitMap[f.PatchHeader.SHA] = true commitMap[f.PatchHeader.SHA] = true
} }
wg.Add(1) wg.Add(1)
concurrentGoroutines <- struct{}{}
go func(f *gitdiff.File) { go func(f *gitdiff.File) {
defer wg.Done() defer func() {
wg.Done()
<-concurrentGoroutines
}()
if f.IsBinary { if f.IsBinary {
return return
} }
@@ -54,10 +57,6 @@ func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Option
continue continue
} }
if !godocutil.IsText([]byte(tf.Raw(gitdiff.OpAdd))) {
continue
}
for _, fi := range DetectFindings(cfg, []byte(tf.Raw(gitdiff.OpAdd)), f.NewName, commitSHA) { for _, fi := range DetectFindings(cfg, []byte(tf.Raw(gitdiff.OpAdd)), f.NewName, commitSHA) {
// don't add to start/end lines if finding is from a file only rule // don't add to start/end lines if finding is from a file only rule
if !strings.HasPrefix(fi.Match, "file detected") { if !strings.HasPrefix(fi.Match, "file detected") {
+13 -1
View File
@@ -14,11 +14,15 @@ func getLocation(linePairs [][]int, start int, end int) Location {
var ( var (
prevNewLine int prevNewLine int
location Location location Location
lineSet bool
_lineNum int
) )
for lineNum, pair := range linePairs { for lineNum, pair := range linePairs {
_lineNum = lineNum
newLineByteIndex := pair[0] newLineByteIndex := pair[0]
if prevNewLine <= start && start < newLineByteIndex { if prevNewLine <= start && start < newLineByteIndex {
lineSet = true
location.startLine = lineNum location.startLine = lineNum
location.endLine = lineNum location.endLine = lineNum
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1 location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
@@ -30,9 +34,17 @@ func getLocation(linePairs [][]int, start int, end int) Location {
location.endColumn = (end - prevNewLine) location.endColumn = (end - prevNewLine)
location.endLineIndex = newLineByteIndex location.endLineIndex = newLineByteIndex
} }
prevNewLine = pair[0] prevNewLine = pair[0]
} }
if !lineSet {
// if lines never get set then that means the secret is most likely
// on the last line of the diff output and the diff output does not have
// a newline
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
location.endColumn = (end - prevNewLine)
location.startLine = _lineNum + 1
location.endLine = _lineNum + 1
}
return location return location
} }
+1 -1
View File
@@ -7,7 +7,7 @@ import (
func writeJson(findings []Finding, w io.WriteCloser) error { func writeJson(findings []Finding, w io.WriteCloser) error {
if len(findings) == 0 { if len(findings) == 0 {
return nil findings = []Finding{}
} }
encoder := json.NewEncoder(w) encoder := json.NewEncoder(w)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
+1 -2
View File
@@ -39,9 +39,8 @@ func TestWriteJSON(t *testing.T) {
}}, }},
{ {
wantEmpty: true,
testReportName: "empty", testReportName: "empty",
expected: filepath.Join(expectPath, "report", "this_should_not_exist.json"), expected: filepath.Join(expectPath, "report", "empty.json"),
findings: []Finding{}}, findings: []Finding{}},
} }
-3
View File
@@ -14,9 +14,6 @@ const (
) )
func Write(findings []Finding, cfg config.Config, ext string, reportPath string) error { func Write(findings []Finding, cfg config.Config, ext string, reportPath string) error {
if len(findings) == 0 {
return nil
}
file, err := os.Create(reportPath) file, err := os.Create(reportPath)
if err != nil { if err != nil {
return err return err
+1 -1
View File
@@ -64,7 +64,7 @@ func messageText(f Finding) string {
} }
func getResults(findings []Finding) []Results { func getResults(findings []Finding) []Results {
var results []Results results := []Results{}
for _, f := range findings { for _, f := range findings {
r := Results{ r := Results{
Message: Message{ Message: Message{
+1
View File
@@ -0,0 +1 @@
[]