Compare commits

..
8 Commits
Author SHA1 Message Date
Paulo Correia 6f75511665 Added option to specify .gitleaksignore path (#1179) 2023-06-05 17:03:26 -05:00
Oleksandr Redko 190ac977be Fix closing file in writeJson and writeSarif (#1187) 2023-06-05 10:43:04 -05:00
Oleksandr Redko 6dbb0c5af5 Simplify tests by using T.TempDir (#1186) 2023-05-30 07:24:59 -05:00
Oleksandr Redko 6705461b33 Fix typos in *.md, comments and logs (#1185) 2023-05-30 07:08:42 -05:00
Zachary Rice 9869eab4c2 Update README.md 2023-05-01 19:01:05 -05:00
Zachary Rice 16f1ec0f1e Update bug_report.md 2023-05-01 17:10:00 -05:00
Zachary Rice 8d80a5a5a2 Adding discord channel to readme 2023-05-01 16:43:06 -05:00
Dariusz Porowski 146f69e51b 🐛 fix(sarif): update report to pass validator (#1167)
* 🐛 fix(sarif): update report to pass validator

* ✅ test(sarif): update sarif report testdata
2023-04-28 14:15:18 -05:00
19 changed files with 73 additions and 49 deletions

No files matched your search

+8
View File
@@ -27,3 +27,11 @@ If applicable, add screenshots to help explain your problem.
Add any other context about the problem here. Add any other context about the problem here.
cc @zricethezav cc @zricethezav
<!--
Check out the Secret Scanning Discord Server for live discussions:
https://discord.gg/sydS6AHTUP
--->
+1 -1
View File
@@ -78,7 +78,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
token that is unique enough not to require an identifier then you can use token that is unique enough not to require an identifier then you can use
this function. For example, Pulumi's API Token has the prefix `pul-` which is this function. For example, Pulumi's API Token has the prefix `pul-` which is
unique enough to use `generateUniqueToken`. But something like Beamer's API unique enough to use `generateUniqueToken`. But something like Beamer's API
token that has a `b_` prefix is not unqiue enough to use `generateUniqueToken`, token that has a `b_` prefix is not unique enough to use `generateUniqueToken`,
so instead we use `generateSemiGenericRegex` and require a `beamer` so instead we use `generateSemiGenericRegex` and require a `beamer`
identifier is part of the rule. identifier is part of the rule.
If a token's prefix has more than `3` characters then you could If a token's prefix has more than `3` characters then you could
+3 -1
View File
@@ -25,6 +25,8 @@
</p> </p>
</p> </p>
### Join our Discord! [![Discord](https://img.shields.io/discord/1102689410522284044.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/sydS6AHTUP)
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. 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.
``` ```
@@ -270,7 +272,7 @@ Gitleaks offers a configuration format you can follow to write your own secret d
title = "Gitleaks title" title = "Gitleaks title"
# Extend the base (this) configuration. When you extend a configuration # Extend the base (this) configuration. When you extend a configuration
# the base rules take precendence over the extended rules. I.e, if there are # the base rules take precedence over the extended rules. I.e., if there are
# duplicate rules in both the base configuration and the extended configuration # duplicate rules in both the base configuration and the extended configuration
# the base rules will override the extended rules. # the base rules will override the extended rules.
# Another thing to know with extending configurations is you can chain together # Another thing to know with extending configurations is you can chain together
+18 -1
View File
@@ -20,7 +20,7 @@ func init() {
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("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") detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files")
detectCmd.Flags().StringP("gitleaks-ignore-path","i",".","path to .gitleaksignore file or folder containing one")
} }
var detectCmd = &cobra.Command{ var detectCmd = &cobra.Command{
@@ -81,6 +81,23 @@ func runDetect(cmd *cobra.Command, args []string) {
log.Fatal().Err(err).Msg("") log.Fatal().Err(err).Msg("")
} }
gitleaksIgnorePath, err:= cmd.Flags().GetString("gitleaks-ignore-path")
if err != nil {
log.Fatal().Err(err).Msg("could not get .gitleaksignore path")
}
if fileExists(gitleaksIgnorePath) {
if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(source, ".gitleaksignore")) { if fileExists(filepath.Join(source, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil { if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore") log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
+2 -2
View File
@@ -28,9 +28,9 @@ func TelegramBotToken() *config.Rule {
minToken := secrets.NewSecret(numeric("5") + ":A" + alphaNumericExtendedShort("34")) minToken := secrets.NewSecret(numeric("5") + ":A" + alphaNumericExtendedShort("34"))
maxToken := secrets.NewSecret(numeric("16") + ":A" + alphaNumericExtendedShort("34")) maxToken := secrets.NewSecret(numeric("16") + ":A" + alphaNumericExtendedShort("34"))
tps := []string{ tps := []string{
// variable assigment // variable assignment
generateSampleSecret("telegram", validToken), generateSampleSecret("telegram", validToken),
// URL contaning token // URL containing token
generateSampleSecret("url", "https://api.telegram.org/bot"+validToken+"/sendMessage"), generateSampleSecret("url", "https://api.telegram.org/bot"+validToken+"/sendMessage"),
// object constructor // object constructor
`const bot = new Telegraf("` + validToken + `")`, `const bot = new Telegraf("` + validToken + `")`,
+18
View File
@@ -17,6 +17,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") protectCmd.Flags().String("log-opts", "", "git log options")
protectCmd.Flags().StringP("gitleaks-ignore-path","i",".","path to .gitleaksignore file or folder containing one")
rootCmd.AddCommand(protectCmd) rootCmd.AddCommand(protectCmd)
} }
@@ -74,6 +75,23 @@ func runProtect(cmd *cobra.Command, args []string) {
log.Fatal().Err(err).Msg("") log.Fatal().Err(err).Msg("")
} }
gitleaksIgnorePath, err:= cmd.Flags().GetString("gitleaks-ignore-path")
if err != nil {
log.Fatal().Err(err).Msg("could not get .gitleaksignore path")
}
if fileExists(gitleaksIgnorePath) {
if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(source, ".gitleaksignore")) { if fileExists(filepath.Join(source, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil { if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore") log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
+1 -1
View File
@@ -13,7 +13,7 @@ import (
func IsNew(finding report.Finding, baseline []report.Finding) bool { func IsNew(finding report.Finding, baseline []report.Finding) bool {
// Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that // Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that
// the code requires maintanance if/when the Finding struct changes // the code requires maintenance if/when the Finding struct changes
for _, b := range baseline { for _, b := range baseline {
if finding.Author == b.Author && if finding.Author == b.Author &&
+1 -1
View File
@@ -23,7 +23,7 @@ func TestDetect(t *testing.T) {
fragment Fragment fragment Fragment
// NOTE: for expected findings, all line numbers will be 0 // NOTE: for expected findings, all line numbers will be 0
// because line deltas are added _after_ the finding is created. // 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 // 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, // increase by 1 in DetectFromFiles(). If the finding is from git,
// the line number will be increased by the patch delta. // the line number will be increased by the patch delta.
expectedFindings []report.Finding expectedFindings []report.Finding
+1 -1
View File
@@ -74,7 +74,7 @@ func filter(findings []report.Finding, redact bool) []report.Finding {
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1) genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1) betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
log.Trace().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch) log.Trace().Msgf("skipping %s finding (%s), %s rule takes precedence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
include = false include = false
break break
} }
+3 -9
View File
@@ -1,6 +1,7 @@
package report package report
import ( import (
"bytes"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -45,42 +46,35 @@ func TestWriteCSV(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".csv")) tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".csv"))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
err = writeCsv(test.findings, tmpfile) err = writeCsv(test.findings, tmpfile)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if test.wantEmpty { if test.wantEmpty {
if len(got) > 0 { if len(got) > 0 {
t.Errorf("Expected empty file, got %s", got) t.Errorf("Expected empty file, got %s", got)
} }
os.Remove(tmpfile.Name())
continue continue
} }
want, err := os.ReadFile(test.expected) want, err := os.ReadFile(test.expected)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if string(got) != string(want) { if !bytes.Equal(got, want) {
err = os.WriteFile(strings.Replace(test.expected, ".csv", ".got.csv", 1), got, 0644) err = os.WriteFile(strings.Replace(test.expected, ".csv", ".got.csv", 1), got, 0644)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
t.Errorf("got %s, want %s", string(got), string(want)) t.Errorf("got %s, want %s", string(got), string(want))
} }
os.Remove(tmpfile.Name())
} }
} }
+1 -1
View File
@@ -38,7 +38,7 @@ type Finding struct {
// Rule is the name of the rule that was matched // Rule is the name of the rule that was matched
RuleID string RuleID string
// unique identifer // unique identifier
Fingerprint string Fingerprint string
} }
+2
View File
@@ -9,6 +9,8 @@ func writeJson(findings []Finding, w io.WriteCloser) error {
if len(findings) == 0 { if len(findings) == 0 {
findings = []Finding{} findings = []Finding{}
} }
defer w.Close()
encoder := json.NewEncoder(w) encoder := json.NewEncoder(w)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
return encoder.Encode(findings) return encoder.Encode(findings)
+3 -11
View File
@@ -1,6 +1,7 @@
package report package report
import ( import (
"bytes"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -46,44 +47,35 @@ func TestWriteJSON(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
// create tmp file using os.TempDir() tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".json"))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
err = writeJson(test.findings, tmpfile) err = writeJson(test.findings, tmpfile)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if test.wantEmpty { if test.wantEmpty {
if len(got) > 0 { if len(got) > 0 {
os.Remove(tmpfile.Name())
t.Errorf("Expected empty file, got %s", got) t.Errorf("Expected empty file, got %s", got)
} }
os.Remove(tmpfile.Name())
continue continue
} }
want, err := os.ReadFile(test.expected) want, err := os.ReadFile(test.expected)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if string(got) != string(want) { if !bytes.Equal(got, want) {
err = os.WriteFile(strings.Replace(test.expected, ".json", ".got.json", 1), got, 0644) err = os.WriteFile(strings.Replace(test.expected, ".json", ".got.json", 1), got, 0644)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
t.Errorf("got %s, want %s", string(got), string(want)) t.Errorf("got %s, want %s", string(got), string(want))
} }
os.Remove(tmpfile.Name())
} }
} }
+1 -6
View File
@@ -11,7 +11,6 @@ import (
const ( const (
expectPath = "../testdata/expected/" expectPath = "../testdata/expected/"
tmpPath = "../testdata/tmp"
) )
func TestReport(t *testing.T) { func TestReport(t *testing.T) {
@@ -80,22 +79,18 @@ func TestReport(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
tmpfile, err := os.Create(filepath.Join(tmpPath, strconv.Itoa(i)+test.ext)) tmpfile, err := os.Create(filepath.Join(t.TempDir(), strconv.Itoa(i)+test.ext))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
err = Write(test.findings, config.Config{}, test.ext, tmpfile.Name()) err = Write(test.findings, config.Config{}, test.ext, tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
os.Remove(tmpfile.Name())
if len(got) == 0 && !test.wantEmpty { if len(got) == 0 && !test.wantEmpty {
t.Errorf("got empty file with extension " + test.ext) t.Errorf("got empty file with extension " + test.ext)
+4 -1
View File
@@ -10,10 +10,11 @@ import (
func writeSarif(cfg config.Config, findings []Finding, w io.WriteCloser) error { func writeSarif(cfg config.Config, findings []Finding, w io.WriteCloser) error {
sarif := Sarif{ sarif := Sarif{
Schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json", Schema: "https://json.schemastore.org/sarif-2.1.0.json",
Version: "2.1.0", Version: "2.1.0",
Runs: getRuns(cfg, findings), Runs: getRuns(cfg, findings),
} }
defer w.Close()
encoder := json.NewEncoder(w) encoder := json.NewEncoder(w)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
@@ -34,6 +35,7 @@ func getTool(cfg config.Config) Tool {
Driver: Driver{ Driver: Driver{
Name: driver, Name: driver,
SemanticVersion: version, SemanticVersion: version,
InformationUri: "https://github.com/gitleaks/gitleaks",
Rules: getRules(cfg), Rules: getRules(cfg),
}, },
} }
@@ -164,6 +166,7 @@ type Rules struct {
type Driver struct { type Driver struct {
Name string `json:"name"` Name string `json:"name"`
SemanticVersion string `json:"semanticVersion"` SemanticVersion string `json:"semanticVersion"`
InformationUri string `json:"informationUri"`
Rules []Rules `json:"rules"` Rules []Rules `json:"rules"`
} }
+3 -10
View File
@@ -1,6 +1,7 @@
package report package report
import ( import (
"bytes"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@@ -48,10 +49,8 @@ func TestWriteSarif(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
// create tmp file using os.TempDir() tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".json"))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
viper.Reset() viper.Reset()
@@ -76,29 +75,24 @@ func TestWriteSarif(t *testing.T) {
err = writeSarif(cfg, test.findings, tmpfile) err = writeSarif(cfg, test.findings, tmpfile)
fmt.Println(cfg) fmt.Println(cfg)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if test.wantEmpty { if test.wantEmpty {
if len(got) > 0 { if len(got) > 0 {
os.Remove(tmpfile.Name())
t.Errorf("Expected empty file, got %s", got) t.Errorf("Expected empty file, got %s", got)
} }
os.Remove(tmpfile.Name())
continue continue
} }
want, err := os.ReadFile(test.expected) want, err := os.ReadFile(test.expected)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if string(got) != string(want) { if !bytes.Equal(got, want) {
err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644) err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
@@ -106,6 +100,5 @@ func TestWriteSarif(t *testing.T) {
t.Errorf("got %s, want %s", string(got), string(want)) t.Errorf("got %s, want %s", string(got), string(want))
} }
os.Remove(tmpfile.Name())
} }
} }
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json", "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0", "version": "2.1.0",
"runs": [ "runs": [
] ]
+2 -1
View File
@@ -1,5 +1,5 @@
{ {
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json", "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0", "version": "2.1.0",
"runs": [ "runs": [
{ {
@@ -7,6 +7,7 @@
"driver": { "driver": {
"name": "gitleaks", "name": "gitleaks",
"semanticVersion": "v8.0.0", "semanticVersion": "v8.0.0",
"informationUri": "https://github.com/gitleaks/gitleaks",
"rules": [ "rules": [
{ {
"id": "aws-access-key", "id": "aws-access-key",
-1
View File
@@ -1 +0,0 @@
nothing should be saved here