Compare commits

...
7 Commits
Author SHA1 Message Date
Zachary Rice 7f229faf12 include default newline pairs when calculating location (#1038)
* include default newline pairs when calculating location
2022-11-20 12:34:38 -06:00
Becojo d0733f96f3 Add rule for fine-grained GitHub PAT (#1026) 2022-11-09 17:02:35 -06:00
Zachary Rice 6ef704f28f Add scanning from a pipe with --pipe (#1012) 2022-10-13 09:08:43 -05:00
Zachary 7cfebca510 add a few fingerprints for test data 2022-10-12 19:34:14 -05:00
Ricky GrassmuckandZachary Rice 6d801ed61c Add support for following symlinks (#1010)
* Add support for following symlinks

* Update detect/detect.go

Co-authored-by: Zachary Rice <zricezrice@gmail.com>

* Update cmd/detect.go

Co-authored-by: Zachary Rice <zricezrice@gmail.com>
2022-10-12 19:28:53 -05:00
sergiomarotco e15ab0dc2a fix bug in readme (#1011)
--max-target-megabytes INT
2022-10-12 09:22:37 -05:00
Zachary Rice c39e7640e2 define log-opts, odd that this wasn't failing before... (#1009) 2022-10-11 07:11:02 -05:00
20 changed files with 263 additions and 51 deletions

No files matched your search

+8 -1
View File
@@ -652,7 +652,9 @@ bc26e979c5911cf647c1bede0b3700ebaaa454c8:checks_test.go:aws-access-token:36
8f352bd840f028b481dc725b77d2f4904b77913b:checks_test.go:aws-access-token:34 8f352bd840f028b481dc725b77d2f4904b77913b:checks_test.go:aws-access-token:34
ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29:checks_test.go:aws-access-token:37 ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29:checks_test.go:aws-access-token:37
06c9e824d5985c8e8789321ae70de7ace3b093dc:main.go:aws-access-token:15 06c9e824d5985c8e8789321ae70de7ace3b093dc:main.go:aws-access-token:15
6d801ed61cf4d75d176cbf9062ec6ad706c9d1eb:detect/detect_test.go:private-key:567
6d801ed61cf4d75d176cbf9062ec6ad706c9d1eb:testdata/repos/symlinks/source_file/id_ed25519:private-key:1
acce01f2338434a78f6a4a06a097b0fd23280484:README.md:aws-access-token:218
README.md:aws-access-token:204 README.md:aws-access-token:204
README.md:aws-access-token:205 README.md:aws-access-token:205
README.md:aws-access-token:244 README.md:aws-access-token:244
@@ -743,3 +745,8 @@ testdata/repos/nogit/main.go:aws-access-token:20
bfbc39eb185a217ead81a7174026f1c55f963660:cmd/generate/config/rules/jwt.go:jwt:17 bfbc39eb185a217ead81a7174026f1c55f963660:cmd/generate/config/rules/jwt.go:jwt:17
bfbc39eb185a217ead81a7174026f1c55f963660:cmd/generate/config/rules/jwt.go:jwt:19 bfbc39eb185a217ead81a7174026f1c55f963660:cmd/generate/config/rules/jwt.go:jwt:19
acce01f2338434a78f6a4a06a097b0fd23280484:README.md:aws-access-token:220 acce01f2338434a78f6a4a06a097b0fd23280484:README.md:aws-access-token:220
99d620c719020fa24baa831299f0c964da79875e:detect/detect_test.go:aws-access-token:514
111c8b47b65627db117bd20be85ff0aee8961eb9:detect/detect_test.go:private-key:567
99d620c719020fa24baa831299f0c964da79875e:detect/detect_test.go:aws-access-token:512
99d620c719020fa24baa831299f0c964da79875e:detect/detect_test.go:aws-access-token:513
+20 -20
View File
@@ -138,29 +138,29 @@ Usage:
Available Commands: Available Commands:
completion generate the autocompletion script for the specified shell completion generate the autocompletion script for the specified shell
detect Detect secrets in code detect detect secrets in code
help Help about any command help Help about any command
protect Protect secrets in code protect protect secrets in code
version Display gitleaks version version display gitleaks version
Flags: Flags:
-c, --config string config file path -b, --baseline-path string path to baseline with issues that can be ignored
order of precedence: -c, --config string config file path
1. --config/-c order of precedence:
2. env var GITLEAKS_CONFIG 1. --config/-c
3. (--source/-s)/.gitleaks.toml 2. env var GITLEAKS_CONFIG
If none of the three options are used, then gitleaks will use the default config 3. (--source/-s)/.gitleaks.toml
--exit-code string exit code when leaks have been encountered (default: 1) If none of the three options are used, then gitleaks will use the default config
-h, --help help for gitleaks --exit-code int exit code when leaks have been encountered (default 1)
-l, --log-level string log level (debug, info, warn, error, fatal) (default "info") -h, --help help for gitleaks
--no-banner suppress banner -l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
--redact redact secrets from logs and stdout --max-target-megabytes int files larger than this will be skipped
-f, --report-format string output format (json, csv, sarif) --no-banner suppress banner
-r, --report-path string report file --redact redact secrets from logs and stdout
-b, --baseline-path path to a previously generated report with known issues that gitleaks should ignore -f, --report-format string output format (json, csv, sarif) (default "json")
-s, --source string path to source (git repo, directory, file) -r, --report-path string report file
-v, --verbose show verbose output from scan -s, --source string path to source (default: $PWD) (default ".")
--max-target-megabytes files larger than this will be skipped -v, --verbose show verbose output from scan
Use "gitleaks [command] --help" for more information about a command. Use "gitleaks [command] --help" for more information about a command.
``` ```
+19 -1
View File
@@ -18,6 +18,9 @@ func init() {
rootCmd.AddCommand(detectCmd) rootCmd.AddCommand(detectCmd)
detectCmd.Flags().String("log-opts", "", "git log options") detectCmd.Flags().String("log-opts", "", "git log options")
detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set") detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set")
detectCmd.Flags().Bool("pipe", false, "scan input from stdin, ex: `cat some_file | gitleaks detect --pipe`")
detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files")
} }
var detectCmd = &cobra.Command{ var detectCmd = &cobra.Command{
@@ -89,6 +92,11 @@ func runDetect(cmd *cobra.Command, args []string) {
} }
} }
// set follow symlinks flag
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
log.Fatal().Err(err).Msg("")
}
// set exit code // set exit code
exitCode, err := cmd.Flags().GetInt("exit-code") exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil { if err != nil {
@@ -102,6 +110,10 @@ func runDetect(cmd *cobra.Command, args []string) {
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("could not call GetBool() for no-git") log.Fatal().Err(err).Msg("could not call GetBool() for no-git")
} }
fromPipe, err := cmd.Flags().GetBool("pipe")
if err != nil {
log.Fatal().Err(err)
}
// start the detector scan // start the detector scan
if noGit { if noGit {
@@ -110,7 +122,13 @@ func runDetect(cmd *cobra.Command, args []string) {
// don't exit on error, just log it // don't exit on error, just log it
log.Error().Err(err).Msg("") log.Error().Err(err).Msg("")
} }
} else if fromPipe {
findings, err = detector.DetectReader(os.Stdin, 10)
if err != nil {
// log fatal to exit, no need to continue since a report
// will not be generated when scanning from a pipe...for now
log.Fatal().Err(err).Msg("")
}
} else { } else {
var logOpts string var logOpts string
logOpts, err = cmd.Flags().GetString("log-opts") logOpts, err = cmd.Flags().GetString("log-opts")
+1
View File
@@ -73,6 +73,7 @@ func main() {
// configRules = append(configRules, rules.GCPServiceAccount()) // configRules = append(configRules, rules.GCPServiceAccount())
configRules = append(configRules, rules.GCPAPIKey()) configRules = append(configRules, rules.GCPAPIKey())
configRules = append(configRules, rules.GitHubPat()) configRules = append(configRules, rules.GitHubPat())
configRules = append(configRules, rules.GitHubFineGrainedPat())
configRules = append(configRules, rules.GitHubOauth()) configRules = append(configRules, rules.GitHubOauth())
configRules = append(configRules, rules.GitHubApp()) configRules = append(configRules, rules.GitHubApp())
configRules = append(configRules, rules.GitHubRefresh()) configRules = append(configRules, rules.GitHubRefresh())
+16
View File
@@ -23,6 +23,22 @@ func GitHubPat() *config.Rule {
return validate(r, tps, nil) return validate(r, tps, nil)
} }
func GitHubFineGrainedPat() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub Fine-Grained Personal Access Token",
RuleID: "github-fine-grained-pat",
Regex: regexp.MustCompile(`github_pat_[0-9a-zA-Z_]{82}`),
Keywords: []string{"github_pat_"},
}
// validate
tps := []string{
generateSampleSecret("github", "github_pat_"+secrets.NewSecret(alphaNumeric("82"))),
}
return validate(r, tps, nil)
}
func GitHubOauth() *config.Rule { func GitHubOauth() *config.Rule {
// define rule // define rule
r := config.Rule{ r := config.Rule{
+5
View File
@@ -16,6 +16,7 @@ import (
func init() { func init() {
protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state") protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state")
protectCmd.Flags().String("log-opts", "", "git log options")
rootCmd.AddCommand(protectCmd) rootCmd.AddCommand(protectCmd)
} }
@@ -66,6 +67,10 @@ func runProtect(cmd *cobra.Command, args []string) {
log.Fatal().Err(err).Msg("") log.Fatal().Err(err).Msg("")
} }
if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
log.Fatal().Err(err).Msg("")
}
// get log options for git scan // get log options for git scan
logOpts, err := cmd.Flags().GetString("log-opts") logOpts, err := cmd.Flags().GetString("log-opts")
if err != nil { if err != nil {
+8
View File
@@ -1976,6 +1976,14 @@ keywords = [
"ghu_","ghs_", "ghu_","ghs_",
] ]
[[rules]]
description = "GitHub Fine-Grained Personal Access Token"
id = "github-fine-grained-pat"
regex = '''github_pat_[0-9a-zA-Z_]{82}'''
keywords = [
"github_pat_",
]
[[rules]] [[rules]]
description = "GitHub OAuth Access Token" description = "GitHub OAuth Access Token"
id = "github-oauth" id = "github-oauth"
+70 -6
View File
@@ -4,19 +4,21 @@ import (
"bufio" "bufio"
"context" "context"
"fmt" "fmt"
"io"
"io/fs"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"sync" "sync"
"github.com/h2non/filetype"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect/git" "github.com/zricethezav/gitleaks/v8/detect/git"
"github.com/zricethezav/gitleaks/v8/report" "github.com/zricethezav/gitleaks/v8/report"
"github.com/fatih/semgroup" "github.com/fatih/semgroup"
"github.com/gitleaks/go-gitdiff/gitdiff" "github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/h2non/filetype"
ahocorasick "github.com/petar-dambovaliev/aho-corasick" ahocorasick "github.com/petar-dambovaliev/aho-corasick"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/spf13/viper" "github.com/spf13/viper"
@@ -52,6 +54,9 @@ type Detector struct {
// files larger than this will be skipped // files larger than this will be skipped
MaxTargetMegaBytes int MaxTargetMegaBytes int
// followSymlinks is a flag to enable scanning symlink files
FollowSymlinks bool
// commitMap is used to keep track of commits that have been scanned. // commitMap is used to keep track of commits that have been scanned.
// This is only used for logging purposes and git scans. // This is only used for logging purposes and git scans.
commitMap map[string]bool commitMap map[string]bool
@@ -85,7 +90,8 @@ type Fragment struct {
Raw string Raw string
// FilePath is the path to the file if applicable // FilePath is the path to the file if applicable
FilePath string FilePath string
SymlinkFile string
// CommitSHA is the SHA of the commit if applicable // CommitSHA is the SHA of the commit if applicable
CommitSHA string CommitSHA string
@@ -194,6 +200,7 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
finding := report.Finding{ finding := report.Finding{
Description: rule.Description, Description: rule.Description,
File: fragment.FilePath, File: fragment.FilePath,
SymlinkFile: fragment.SymlinkFile,
RuleID: rule.RuleID, RuleID: rule.RuleID,
Match: fmt.Sprintf("file detected: %s", fragment.FilePath), Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
Tags: rule.Tags, Tags: rule.Tags,
@@ -241,6 +248,7 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
finding := report.Finding{ finding := report.Finding{
Description: rule.Description, Description: rule.Description,
File: fragment.FilePath, File: fragment.FilePath,
SymlinkFile: fragment.SymlinkFile,
RuleID: rule.RuleID, RuleID: rule.RuleID,
StartLine: loc.startLine, StartLine: loc.startLine,
EndLine: loc.endLine, EndLine: loc.endLine,
@@ -384,11 +392,16 @@ func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanT
return d.findings, nil return d.findings, nil
} }
type scanTarget struct {
Path string
Symlink string
}
// DetectFiles accepts a path to a source directory or file and begins a scan of the // DetectFiles accepts a path to a source directory or file and begins a scan of the
// file or directory. // file or directory.
func (d *Detector) DetectFiles(source string) ([]report.Finding, error) { func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
s := semgroup.NewGroup(context.Background(), 4) s := semgroup.NewGroup(context.Background(), 4)
paths := make(chan string) paths := make(chan scanTarget)
s.Go(func() error { s.Go(func() error {
defer close(paths) defer close(paths)
return filepath.Walk(source, return filepath.Walk(source,
@@ -403,7 +416,25 @@ func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
return nil return nil
} }
if fInfo.Mode().IsRegular() { if fInfo.Mode().IsRegular() {
paths <- path paths <- scanTarget{
Path: path,
Symlink: "",
}
}
if fInfo.Mode().Type() == fs.ModeSymlink && d.FollowSymlinks {
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
return err
}
realPathFileInfo, _ := os.Stat(realPath)
if realPathFileInfo.IsDir() {
log.Debug().Msgf("found symlinked directory: %s -> %s [skipping]", path, realPath)
return nil
}
paths <- scanTarget{
Path: realPath,
Symlink: path,
}
} }
return nil return nil
}) })
@@ -411,7 +442,7 @@ func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
for pa := range paths { for pa := range paths {
p := pa p := pa
s.Go(func() error { s.Go(func() error {
b, err := os.ReadFile(p) b, err := os.ReadFile(p.Path)
if err != nil { if err != nil {
return err return err
} }
@@ -426,7 +457,10 @@ func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
fragment := Fragment{ fragment := Fragment{
Raw: string(b), Raw: string(b),
FilePath: p, FilePath: p.Path,
}
if p.Symlink != "" {
fragment.SymlinkFile = p.Symlink
} }
for _, finding := range d.Detect(fragment) { for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1 // need to add 1 since line counting starts at 1
@@ -446,6 +480,36 @@ func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
return d.findings, nil return d.findings, nil
} }
// DetectReader accepts an io.Reader and a buffer size for the reader in KB
func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, error) {
reader := bufio.NewReader(r)
buf := make([]byte, 0, 1000*bufSize)
findings := []report.Finding{}
for {
n, err := reader.Read(buf[:cap(buf)])
buf = buf[:n]
if err != nil {
if err != io.EOF {
return findings, err
}
break
}
fragment := Fragment{
Raw: string(buf),
}
for _, finding := range d.Detect(fragment) {
findings = append(findings, finding)
if d.Verbose {
printFinding(finding)
}
}
}
return findings, nil
}
// Detect scans the given fragment and returns a list of findings // Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding { func (d *Detector) Detect(fragment Fragment) []report.Finding {
var findings []report.Finding var findings []report.Finding
+79 -17
View File
@@ -18,8 +18,13 @@ const repoBasePath = "../testdata/repos/"
func TestDetect(t *testing.T) { func TestDetect(t *testing.T) {
tests := []struct { tests := []struct {
cfgName string cfgName string
fragment Fragment fragment Fragment
// NOTE: for expected findings, all line numbers will be 0
// because line deltas are added _after_ the finding is created.
// I.e, if the finding is from a --no-git file, the line number will be
// increase by 1 in DetectFromFiles(). If the finding is from git,
// the line number will be increased by the patch delta.
expectedFindings []report.Finding expectedFindings []report.Finding
wantError error wantError error
}{ }{
@@ -85,8 +90,8 @@ func TestDetect(t *testing.T) {
File: "tmp.go", File: "tmp.go",
RuleID: "pypi-upload-token", RuleID: "pypi-upload-token",
Tags: []string{"key", "pypi"}, Tags: []string{"key", "pypi"},
StartLine: 1, StartLine: 0,
EndLine: 1, EndLine: 0,
StartColumn: 1, StartColumn: 1,
EndColumn: 86, EndColumn: 86,
Entropy: 1.9606875, Entropy: 1.9606875,
@@ -108,8 +113,8 @@ func TestDetect(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, StartLine: 0,
EndLine: 1, EndLine: 0,
StartColumn: 15, StartColumn: 15,
EndColumn: 34, EndColumn: 34,
Entropy: 3.0841837, Entropy: 3.0841837,
@@ -132,8 +137,8 @@ func TestDetect(t *testing.T) {
RuleID: "sidekiq-secret", RuleID: "sidekiq-secret",
Tags: []string{}, Tags: []string{},
Entropy: 2.6098502, Entropy: 2.6098502,
StartLine: 1, StartLine: 0,
EndLine: 1, EndLine: 0,
StartColumn: 8, StartColumn: 8,
EndColumn: 60, EndColumn: 60,
}, },
@@ -155,8 +160,8 @@ func TestDetect(t *testing.T) {
RuleID: "sidekiq-secret", RuleID: "sidekiq-secret",
Tags: []string{}, Tags: []string{},
Entropy: 2.6098502, Entropy: 2.6098502,
StartLine: 1, StartLine: 0,
EndLine: 1, EndLine: 0,
StartColumn: 21, StartColumn: 21,
EndColumn: 74, EndColumn: 74,
}, },
@@ -178,8 +183,8 @@ func TestDetect(t *testing.T) {
RuleID: "sidekiq-sensitive-url", RuleID: "sidekiq-sensitive-url",
Tags: []string{}, Tags: []string{},
Entropy: 2.984234, Entropy: 2.984234,
StartLine: 1, StartLine: 0,
EndLine: 1, EndLine: 0,
StartColumn: 8, StartColumn: 8,
EndColumn: 58, EndColumn: 58,
}, },
@@ -226,8 +231,8 @@ func TestDetect(t *testing.T) {
RuleID: "discord-api-key", RuleID: "discord-api-key",
Tags: []string{}, Tags: []string{},
Entropy: 3.7906237, Entropy: 3.7906237,
StartLine: 1, StartLine: 0,
EndLine: 1, EndLine: 0,
StartColumn: 7, StartColumn: 7,
EndColumn: 93, EndColumn: 93,
}, },
@@ -257,8 +262,8 @@ func TestDetect(t *testing.T) {
RuleID: "generic-api-key", RuleID: "generic-api-key",
Tags: []string{}, Tags: []string{},
Entropy: 3.7906237, Entropy: 3.7906237,
StartLine: 1, StartLine: 0,
EndLine: 1, EndLine: 0,
StartColumn: 22, StartColumn: 22,
EndColumn: 93, EndColumn: 93,
}, },
@@ -470,7 +475,7 @@ func TestFromGit(t *testing.T) {
} }
} }
// TestFromGit tests the FromGit function // TestFromFiles tests the FromFiles function
func TestFromFiles(t *testing.T) { func TestFromFiles(t *testing.T) {
tests := []struct { tests := []struct {
cfgName string cfgName string
@@ -491,6 +496,7 @@ func TestFromFiles(t *testing.T) {
Secret: "AKIALALEMEL33243OLIA", Secret: "AKIALALEMEL33243OLIA",
Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"", Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"",
File: "../testdata/repos/nogit/main.go", File: "../testdata/repos/nogit/main.go",
SymlinkFile: "",
RuleID: "aws-access-key", RuleID: "aws-access-key",
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Entropy: 3.0841837, Entropy: 3.0841837,
@@ -537,6 +543,7 @@ func TestFromFiles(t *testing.T) {
} }
cfg, _ := vc.Translate() cfg, _ := vc.Translate()
detector := NewDetector(cfg) detector := NewDetector(cfg)
detector.FollowSymlinks = true
findings, err := detector.DetectFiles(tt.source) findings, err := detector.DetectFiles(tt.source)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
@@ -546,6 +553,61 @@ func TestFromFiles(t *testing.T) {
} }
} }
func TestDetectWithSymlinks(t *testing.T) {
tests := []struct {
cfgName string
source string
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "symlinks/file_symlink"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "Asymmetric Private Key",
StartLine: 1,
EndLine: 1,
StartColumn: 1,
EndColumn: 35,
Match: "-----BEGIN OPENSSH PRIVATE KEY-----",
Secret: "-----BEGIN OPENSSH PRIVATE KEY-----",
Line: "-----BEGIN OPENSSH PRIVATE KEY-----",
File: "../testdata/repos/symlinks/source_file/id_ed25519",
SymlinkFile: "../testdata/repos/symlinks/file_symlink/symlinked_id_ed25519",
RuleID: "apkey",
Tags: []string{"key", "AsymmetricPrivateKey"},
Entropy: 3.587164,
Fingerprint: "../testdata/repos/symlinks/source_file/id_ed25519:apkey:1",
},
},
},
}
for _, tt := range tests {
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigType("toml")
err := viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, _ := vc.Translate()
detector := NewDetector(cfg)
detector.FollowSymlinks = true
findings, err := detector.DetectFiles(tt.source)
if err != nil {
t.Error(err)
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
func moveDotGit(from, to string) error { func moveDotGit(from, to string) error {
repoDirs, err := os.ReadDir("../testdata/repos") repoDirs, err := os.ReadDir("../testdata/repos")
if err != nil { if err != nil {
+10
View File
@@ -24,6 +24,16 @@ func location(fragment Fragment, matchIndex []int) Location {
// default startLineIndex to 0 // default startLineIndex to 0
location.startLineIndex = 0 location.startLineIndex = 0
// Fixes: https://github.com/zricethezav/gitleaks/issues/1037
// When a fragment does NOT have any newlines, a default "newline"
// will be counted to make the subsequent location calculation logic work
// for fragments will no newlines.
if len(fragment.newlineIndices) == 0 {
fragment.newlineIndices = [][]int{
{len(fragment.Raw), len(fragment.Raw) + 1},
}
}
for lineNum, pair := range fragment.newlineIndices { for lineNum, pair := range fragment.newlineIndices {
_lineNum = lineNum _lineNum = lineNum
newLineByteIndex := pair[0] newLineByteIndex := pair[0]
+4
View File
@@ -131,6 +131,10 @@ func printFinding(f report.Finding) {
fmt.Printf("%-12s %s\n", "Secret:", secret) fmt.Printf("%-12s %s\n", "Secret:", secret)
fmt.Printf("%-12s %s\n", "RuleID:", f.RuleID) fmt.Printf("%-12s %s\n", "RuleID:", f.RuleID)
fmt.Printf("%-12s %f\n", "Entropy:", f.Entropy) fmt.Printf("%-12s %f\n", "Entropy:", f.Entropy)
if f.File == "" {
fmt.Println("")
return
}
fmt.Printf("%-12s %s\n", "File:", f.File) fmt.Printf("%-12s %s\n", "File:", f.File)
fmt.Printf("%-12s %d\n", "Line:", f.StartLine) fmt.Printf("%-12s %d\n", "Line:", f.StartLine)
if f.Commit == "" { if f.Commit == "" {
+2
View File
@@ -16,6 +16,7 @@ func writeCsv(f []Finding, w io.WriteCloser) error {
err := cw.Write([]string{"RuleID", err := cw.Write([]string{"RuleID",
"Commit", "Commit",
"File", "File",
"SymlinkFile",
"Secret", "Secret",
"Match", "Match",
"StartLine", "StartLine",
@@ -35,6 +36,7 @@ func writeCsv(f []Finding, w io.WriteCloser) error {
err = cw.Write([]string{f.RuleID, err = cw.Write([]string{f.RuleID,
f.Commit, f.Commit,
f.File, f.File,
f.SymlinkFile,
f.Secret, f.Secret,
f.Match, f.Match,
strconv.Itoa(f.StartLine), strconv.Itoa(f.StartLine),
+1
View File
@@ -28,6 +28,7 @@ func TestWriteCSV(t *testing.T) {
EndColumn: 2, EndColumn: 2,
Message: "opps", Message: "opps",
File: "auth.py", File: "auth.py",
SymlinkFile: "",
Commit: "0000000000000000", Commit: "0000000000000000",
Author: "John Doe", Author: "John Doe",
Email: "johndoe@gmail.com", Email: "johndoe@gmail.com",
+3 -3
View File
@@ -22,9 +22,9 @@ type Finding struct {
Secret string Secret string
// File is the name of the file containing the finding // File is the name of the file containing the finding
File string File string
SymlinkFile string
Commit string Commit string
// Entropy is the shannon entropy of Value // Entropy is the shannon entropy of Value
Entropy float32 Entropy float32
+1
View File
@@ -30,6 +30,7 @@ func TestWriteJSON(t *testing.T) {
EndColumn: 2, EndColumn: 2,
Message: "opps", Message: "opps",
File: "auth.py", File: "auth.py",
SymlinkFile: "",
Commit: "0000000000000000", Commit: "0000000000000000",
Author: "John Doe", Author: "John Doe",
Email: "johndoe@gmail.com", Email: "johndoe@gmail.com",
+5 -1
View File
@@ -109,11 +109,15 @@ func getResults(findings []Finding) []Results {
} }
func getLocation(f Finding) []Locations { func getLocation(f Finding) []Locations {
uri := f.File
if f.SymlinkFile != "" {
uri = f.SymlinkFile
}
return []Locations{ return []Locations{
{ {
PhysicalLocation: PhysicalLocation{ PhysicalLocation: PhysicalLocation{
ArtifactLocation: ArtifactLocation{ ArtifactLocation: ArtifactLocation{
URI: f.File, URI: uri,
}, },
Region: Region{ Region: Region{
StartLine: f.StartLine, StartLine: f.StartLine,
+2 -2
View File
@@ -1,2 +1,2 @@
RuleID,Commit,File,Secret,Match,StartLine,EndLine,StartColumn,EndColumn,Author,Message,Date,Email,Fingerprint RuleID,Commit,File,SymlinkFile,Secret,Match,StartLine,EndLine,StartColumn,EndColumn,Author,Message,Date,Email,Fingerprint
test-rule,0000000000000000,auth.py,a secret,line containing secret,1,2,1,2,John Doe,opps,10-19-2003,johndoe@gmail.com,fingerprint test-rule,0000000000000000,auth.py,,a secret,line containing secret,1,2,1,2,John Doe,opps,10-19-2003,johndoe@gmail.com,fingerprint
1 RuleID Commit File SymlinkFile Secret Match StartLine EndLine StartColumn EndColumn Author Message Date Email Fingerprint
2 test-rule 0000000000000000 auth.py a secret line containing secret 1 2 1 2 John Doe opps 10-19-2003 johndoe@gmail.com fingerprint
+1
View File
@@ -8,6 +8,7 @@
"Match": "line containing secret", "Match": "line containing secret",
"Secret": "a secret", "Secret": "a secret",
"File": "auth.py", "File": "auth.py",
"SymlinkFile": "",
"Commit": "0000000000000000", "Commit": "0000000000000000",
"Entropy": 0, "Entropy": 0,
"Author": "John Doe", "Author": "John Doe",
+1
View File
@@ -0,0 +1 @@
../source_file/id_ed25519
+7
View File
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACA8YWKYztuuvxUIMomc3zv0OdXCT57Cc2cRYu3TMbX9XAAAAJDiKO3C4ijt
wgAAAAtzc2gtZWQyNTUxOQAAACA8YWKYztuuvxUIMomc3zv0OdXCT57Cc2cRYu3TMbX9XA
AAAECzmj8DGxg5YHtBK4AmBttMXDQHsPAaCyYHQjJ4YujRBTxhYpjO266/FQgyiZzfO/Q5
1cJPnsJzZxFi7dMxtf1cAAAADHJvb3RAZGV2aG9zdAE=
-----END OPENSSH PRIVATE KEY-----