4
0

detect.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. package detect
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/zricethezav/gitleaks/v8/config"
  12. "github.com/zricethezav/gitleaks/v8/detect/codec"
  13. "github.com/zricethezav/gitleaks/v8/logging"
  14. "github.com/zricethezav/gitleaks/v8/regexp"
  15. "github.com/zricethezav/gitleaks/v8/report"
  16. "github.com/zricethezav/gitleaks/v8/sources"
  17. ahocorasick "github.com/BobuSumisu/aho-corasick"
  18. "github.com/fatih/semgroup"
  19. "github.com/rs/zerolog"
  20. "github.com/spf13/viper"
  21. "golang.org/x/exp/maps"
  22. )
  23. const (
  24. gitleaksAllowSignature = "gitleaks:allow"
  25. // SlowWarningThreshold is the amount of time to wait before logging that a file is slow.
  26. // This is useful for identifying problematic files and tuning the allowlist.
  27. SlowWarningThreshold = 5 * time.Second
  28. )
  29. var (
  30. newLineRegexp = regexp.MustCompile("\n")
  31. )
  32. // Detector is the main detector struct
  33. type Detector struct {
  34. // Config is the configuration for the detector
  35. Config config.Config
  36. // Redact is a flag to redact findings. This is exported
  37. // so users using gitleaks as a library can set this flag
  38. // without calling `detector.Start(cmd *cobra.Command)`
  39. Redact uint
  40. // verbose is a flag to print findings
  41. Verbose bool
  42. // MaxDecodeDepths limits how many recursive decoding passes are allowed
  43. MaxDecodeDepth int
  44. // MaxArchiveDepth limits how deep the sources will explore nested archives
  45. MaxArchiveDepth int
  46. // files larger than this will be skipped
  47. MaxTargetMegaBytes int
  48. // followSymlinks is a flag to enable scanning symlink files
  49. FollowSymlinks bool
  50. // NoColor is a flag to disable color output
  51. NoColor bool
  52. // IgnoreGitleaksAllow is a flag to ignore gitleaks:allow comments.
  53. IgnoreGitleaksAllow bool
  54. // commitMutex is to prevent concurrent access to the
  55. // commit map when adding commits
  56. commitMutex *sync.Mutex
  57. // commitMap is used to keep track of commits that have been scanned.
  58. // This is only used for logging purposes and git scans.
  59. commitMap map[string]bool
  60. // findingMutex is to prevent concurrent access to the
  61. // findings slice when adding findings.
  62. findingMutex *sync.Mutex
  63. // findings is a slice of report.Findings. This is the result
  64. // of the detector's scan which can then be used to generate a
  65. // report.
  66. findings []report.Finding
  67. // prefilter is a ahocorasick struct used for doing efficient string
  68. // matching given a set of words (keywords from the rules in the config)
  69. prefilter ahocorasick.Trie
  70. // a list of known findings that should be ignored
  71. baseline []report.Finding
  72. // path to baseline
  73. baselinePath string
  74. // gitleaksIgnore
  75. gitleaksIgnore map[string]struct{}
  76. // Sema (https://github.com/fatih/semgroup) controls the concurrency
  77. Sema *semgroup.Group
  78. // report-related settings.
  79. ReportPath string
  80. Reporter report.Reporter
  81. TotalBytes atomic.Uint64
  82. }
  83. // Fragment is an alias for sources.Fragment for backwards compatibility
  84. //
  85. // Deprecated: This will be replaced with sources.Fragment in v9
  86. type Fragment sources.Fragment
  87. // NewDetector creates a new detector with the given config
  88. func NewDetector(cfg config.Config) *Detector {
  89. return &Detector{
  90. commitMap: make(map[string]bool),
  91. gitleaksIgnore: make(map[string]struct{}),
  92. findingMutex: &sync.Mutex{},
  93. commitMutex: &sync.Mutex{},
  94. findings: make([]report.Finding, 0),
  95. Config: cfg,
  96. prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
  97. Sema: semgroup.NewGroup(context.Background(), 40),
  98. }
  99. }
  100. // NewDetectorDefaultConfig creates a new detector with the default config
  101. func NewDetectorDefaultConfig() (*Detector, error) {
  102. viper.SetConfigType("toml")
  103. err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
  104. if err != nil {
  105. return nil, err
  106. }
  107. var vc config.ViperConfig
  108. err = viper.Unmarshal(&vc)
  109. if err != nil {
  110. return nil, err
  111. }
  112. cfg, err := vc.Translate()
  113. if err != nil {
  114. return nil, err
  115. }
  116. return NewDetector(cfg), nil
  117. }
  118. func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
  119. logging.Debug().Str("path", gitleaksIgnorePath).Msgf("found .gitleaksignore file")
  120. file, err := os.Open(gitleaksIgnorePath)
  121. if err != nil {
  122. return err
  123. }
  124. defer func() {
  125. // https://github.com/securego/gosec/issues/512
  126. if err := file.Close(); err != nil {
  127. logging.Warn().Err(err).Msgf("Error closing .gitleaksignore file")
  128. }
  129. }()
  130. scanner := bufio.NewScanner(file)
  131. replacer := strings.NewReplacer("\\", "/")
  132. for scanner.Scan() {
  133. line := strings.TrimSpace(scanner.Text())
  134. // Skip lines that start with a comment
  135. if line == "" || strings.HasPrefix(line, "#") {
  136. continue
  137. }
  138. // Normalize the path.
  139. // TODO: Make this a breaking change in v9.
  140. s := strings.Split(line, ":")
  141. switch len(s) {
  142. case 3:
  143. // Global fingerprint.
  144. // `file:rule-id:start-line`
  145. s[0] = replacer.Replace(s[0])
  146. case 4:
  147. // Commit fingerprint.
  148. // `commit:file:rule-id:start-line`
  149. s[1] = replacer.Replace(s[1])
  150. default:
  151. logging.Warn().Str("fingerprint", line).Msg("Invalid .gitleaksignore entry")
  152. }
  153. d.gitleaksIgnore[strings.Join(s, ":")] = struct{}{}
  154. }
  155. return nil
  156. }
  157. // DetectBytes scans the given bytes and returns a list of findings
  158. func (d *Detector) DetectBytes(content []byte) []report.Finding {
  159. return d.DetectString(string(content))
  160. }
  161. // DetectString scans the given string and returns a list of findings
  162. func (d *Detector) DetectString(content string) []report.Finding {
  163. return d.Detect(Fragment{
  164. Raw: content,
  165. })
  166. }
  167. // DetectSource scans the given source and returns a list of findings
  168. func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]report.Finding, error) {
  169. err := source.Fragments(ctx, func(fragment sources.Fragment, err error) error {
  170. logContext := logging.With()
  171. if len(fragment.FilePath) > 0 {
  172. logContext = logContext.Str("path", fragment.FilePath)
  173. }
  174. if len(fragment.CommitSHA) > 6 {
  175. logContext = logContext.Str("commit", fragment.CommitSHA[:7])
  176. d.addCommit(fragment.CommitSHA)
  177. } else if len(fragment.CommitSHA) > 0 {
  178. logContext = logContext.Str("commit", fragment.CommitSHA)
  179. d.addCommit(fragment.CommitSHA)
  180. logger := logContext.Logger()
  181. logger.Warn().Msg("commit SHAs should be >= 7 characters long")
  182. }
  183. logger := logContext.Logger()
  184. if err != nil {
  185. // Log the error and move on to the next fragment
  186. logger.Error().Err(err).Send()
  187. return nil
  188. }
  189. // both the fragment's content and path should be empty for it to be
  190. // considered empty at this point because of path based matches
  191. if len(fragment.Raw) == 0 && len(fragment.FilePath) == 0 {
  192. logger.Trace().Msg("skipping empty fragment")
  193. return nil
  194. }
  195. var timer *time.Timer
  196. // Only start the timer in debug mode
  197. if logger.GetLevel() <= zerolog.DebugLevel {
  198. timer = time.AfterFunc(SlowWarningThreshold, func() {
  199. logger.Debug().Msgf("Taking longer than %s to inspect fragment", SlowWarningThreshold.String())
  200. })
  201. }
  202. for _, finding := range d.Detect(Fragment(fragment)) {
  203. d.AddFinding(finding)
  204. }
  205. // Stop the timer if it was created
  206. if timer != nil {
  207. timer.Stop()
  208. }
  209. return nil
  210. })
  211. if _, isGit := source.(*sources.Git); isGit {
  212. logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
  213. logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
  214. }
  215. return d.Findings(), err
  216. }
  217. // Detect scans the given fragment and returns a list of findings
  218. func (d *Detector) Detect(fragment Fragment) []report.Finding {
  219. if fragment.Bytes == nil {
  220. d.TotalBytes.Add(uint64(len(fragment.Raw)))
  221. }
  222. d.TotalBytes.Add(uint64(len(fragment.Bytes)))
  223. var (
  224. findings []report.Finding
  225. logger = func() zerolog.Logger {
  226. l := logging.With().Str("path", fragment.FilePath)
  227. if fragment.CommitSHA != "" {
  228. l = l.Str("commit", fragment.CommitSHA)
  229. }
  230. return l.Logger()
  231. }()
  232. )
  233. // check if filepath is allowed
  234. if fragment.FilePath != "" {
  235. // is the path our config or baseline file?
  236. if fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath) {
  237. logging.Trace().Msg("skipping file: matches config or baseline path")
  238. return findings
  239. }
  240. }
  241. // check if commit or filepath is allowed.
  242. if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, d.Config.Allowlists); isAllowed {
  243. event.Msg("skipping file: global allowlist")
  244. return findings
  245. }
  246. // add newline indices for location calculation in detectRule
  247. newlineIndices := newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
  248. // setup variables to handle different decoding passes
  249. currentRaw := fragment.Raw
  250. encodedSegments := []*codec.EncodedSegment{}
  251. currentDecodeDepth := 0
  252. decoder := codec.NewDecoder()
  253. for {
  254. // build keyword map for prefiltering rules
  255. keywords := make(map[string]bool)
  256. normalizedRaw := strings.ToLower(currentRaw)
  257. matches := d.prefilter.MatchString(normalizedRaw)
  258. for _, m := range matches {
  259. keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
  260. }
  261. for _, rule := range d.Config.Rules {
  262. if len(rule.Keywords) == 0 {
  263. // if no keywords are associated with the rule always scan the
  264. // fragment using the rule
  265. findings = append(findings, d.detectRule(fragment, newlineIndices, currentRaw, rule, encodedSegments)...)
  266. continue
  267. }
  268. // check if keywords are in the fragment
  269. for _, k := range rule.Keywords {
  270. if _, ok := keywords[strings.ToLower(k)]; ok {
  271. findings = append(findings, d.detectRule(fragment, newlineIndices, currentRaw, rule, encodedSegments)...)
  272. break
  273. }
  274. }
  275. }
  276. // increment the depth by 1 as we start our decoding pass
  277. currentDecodeDepth++
  278. // stop the loop if we've hit our max decoding depth
  279. if currentDecodeDepth > d.MaxDecodeDepth {
  280. break
  281. }
  282. // decode the currentRaw for the next pass
  283. currentRaw, encodedSegments = decoder.Decode(currentRaw, encodedSegments)
  284. // stop the loop when there's nothing else to decode
  285. if len(encodedSegments) == 0 {
  286. break
  287. }
  288. }
  289. return filter(findings, d.Redact)
  290. }
  291. // detectRule scans the given fragment for the given rule and returns a list of findings
  292. func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
  293. var (
  294. findings []report.Finding
  295. logger = func() zerolog.Logger {
  296. l := logging.With().Str("rule-id", r.RuleID).Str("path", fragment.FilePath)
  297. if fragment.CommitSHA != "" {
  298. l = l.Str("commit", fragment.CommitSHA)
  299. }
  300. return l.Logger()
  301. }()
  302. )
  303. // check if commit or file is allowed for this rule.
  304. if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, r.Allowlists); isAllowed {
  305. event.Msg("skipping file: rule allowlist")
  306. return findings
  307. }
  308. if r.Path != nil {
  309. if r.Regex == nil && len(encodedSegments) == 0 {
  310. // Path _only_ rule
  311. if r.Path.MatchString(fragment.FilePath) || (fragment.WindowsFilePath != "" && r.Path.MatchString(fragment.WindowsFilePath)) {
  312. finding := report.Finding{
  313. Commit: fragment.CommitSHA,
  314. RuleID: r.RuleID,
  315. Description: r.Description,
  316. File: fragment.FilePath,
  317. SymlinkFile: fragment.SymlinkFile,
  318. Match: "file detected: " + fragment.FilePath,
  319. Tags: r.Tags,
  320. }
  321. if fragment.CommitInfo != nil {
  322. finding.Author = fragment.CommitInfo.AuthorName
  323. finding.Date = fragment.CommitInfo.Date
  324. finding.Email = fragment.CommitInfo.AuthorEmail
  325. finding.Link = createScmLink(fragment.CommitInfo.Remote, finding)
  326. finding.Message = fragment.CommitInfo.Message
  327. }
  328. return append(findings, finding)
  329. }
  330. } else {
  331. // if path is set _and_ a regex is set, then we need to check both
  332. // so if the path does not match, then we should return early and not
  333. // consider the regex
  334. if !(r.Path.MatchString(fragment.FilePath) || (fragment.WindowsFilePath != "" && r.Path.MatchString(fragment.WindowsFilePath))) {
  335. return findings
  336. }
  337. }
  338. }
  339. // if path only rule, skip content checks
  340. if r.Regex == nil {
  341. return findings
  342. }
  343. // if flag configure and raw data size bigger then the flag
  344. if d.MaxTargetMegaBytes > 0 {
  345. rawLength := len(currentRaw) / 1_000_000
  346. if rawLength > d.MaxTargetMegaBytes {
  347. logger.Debug().
  348. Int("size", rawLength).
  349. Int("max-size", d.MaxTargetMegaBytes).
  350. Msg("skipping fragment: size")
  351. return findings
  352. }
  353. }
  354. // use currentRaw instead of fragment.Raw since this represents the current
  355. // decoding pass on the text
  356. for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) {
  357. // Extract secret from match
  358. secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n")
  359. // For any meta data from decoding
  360. var metaTags []string
  361. currentLine := ""
  362. // Check if the decoded portions of the segment overlap with the match
  363. // to see if its potentially a new match
  364. if len(encodedSegments) > 0 {
  365. segments := codec.SegmentsWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1])
  366. if len(segments) == 0 {
  367. // This item has already been added to a finding
  368. continue
  369. }
  370. matchIndex = codec.AdjustMatchIndex(segments, matchIndex)
  371. metaTags = append(metaTags, codec.Tags(segments)...)
  372. currentLine = codec.CurrentLine(segments, currentRaw)
  373. } else {
  374. // Fixes: https://github.com/gitleaks/gitleaks/issues/1352
  375. // removes the incorrectly following line that was detected by regex expression '\n'
  376. matchIndex[1] = matchIndex[0] + len(secret)
  377. }
  378. // determine location of match. Note that the location
  379. // in the finding will be the line/column numbers of the _match_
  380. // not the _secret_, which will be different if the secretGroup
  381. // value is set for this rule
  382. loc := location(newlineIndices, fragment.Raw, matchIndex)
  383. if matchIndex[1] > loc.endLineIndex {
  384. loc.endLineIndex = matchIndex[1]
  385. }
  386. finding := report.Finding{
  387. Commit: fragment.CommitSHA,
  388. RuleID: r.RuleID,
  389. Description: r.Description,
  390. StartLine: fragment.StartLine + loc.startLine,
  391. EndLine: fragment.StartLine + loc.endLine,
  392. StartColumn: loc.startColumn,
  393. EndColumn: loc.endColumn,
  394. Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
  395. Match: secret,
  396. Secret: secret,
  397. File: fragment.FilePath,
  398. SymlinkFile: fragment.SymlinkFile,
  399. Tags: append(r.Tags, metaTags...),
  400. }
  401. if fragment.CommitInfo != nil {
  402. finding.Author = fragment.CommitInfo.AuthorName
  403. finding.Date = fragment.CommitInfo.Date
  404. finding.Email = fragment.CommitInfo.AuthorEmail
  405. finding.Link = createScmLink(fragment.CommitInfo.Remote, finding)
  406. finding.Message = fragment.CommitInfo.Message
  407. }
  408. if !d.IgnoreGitleaksAllow && strings.Contains(finding.Line, gitleaksAllowSignature) {
  409. logger.Trace().
  410. Str("finding", finding.Secret).
  411. Msg("skipping finding: 'gitleaks:allow' signature")
  412. continue
  413. }
  414. if currentLine == "" {
  415. currentLine = finding.Line
  416. }
  417. // Set the value of |secret|, if the pattern contains at least one capture group.
  418. // (The first element is the full match, hence we check >= 2.)
  419. groups := r.Regex.FindStringSubmatch(finding.Secret)
  420. if len(groups) >= 2 {
  421. if r.SecretGroup > 0 {
  422. if len(groups) <= r.SecretGroup {
  423. // Config validation should prevent this
  424. continue
  425. }
  426. finding.Secret = groups[r.SecretGroup]
  427. } else {
  428. // If |secretGroup| is not set, we will use the first suitable capture group.
  429. for _, s := range groups[1:] {
  430. if len(s) > 0 {
  431. finding.Secret = s
  432. break
  433. }
  434. }
  435. }
  436. }
  437. // check entropy
  438. entropy := shannonEntropy(finding.Secret)
  439. finding.Entropy = float32(entropy)
  440. if r.Entropy != 0.0 {
  441. // entropy is too low, skip this finding
  442. if entropy <= r.Entropy {
  443. logger.Trace().
  444. Str("finding", finding.Secret).
  445. Float32("entropy", finding.Entropy).
  446. Msg("skipping finding: low entropy")
  447. continue
  448. }
  449. }
  450. // check if the result matches any of the global allowlists.
  451. if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, d.Config.Allowlists); isAllowed {
  452. event.Msg("skipping finding: global allowlist")
  453. continue
  454. }
  455. // check if the result matches any of the rule allowlists.
  456. if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, r.Allowlists); isAllowed {
  457. event.Msg("skipping finding: rule allowlist")
  458. continue
  459. }
  460. findings = append(findings, finding)
  461. }
  462. return findings
  463. }
  464. // AddFinding synchronously adds a finding to the findings slice
  465. func (d *Detector) AddFinding(finding report.Finding) {
  466. globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine)
  467. if finding.Commit != "" {
  468. finding.Fingerprint = fmt.Sprintf("%s:%s:%s:%d", finding.Commit, finding.File, finding.RuleID, finding.StartLine)
  469. } else {
  470. finding.Fingerprint = globalFingerprint
  471. }
  472. // check if we should ignore this finding
  473. logger := logging.With().Str("finding", finding.Secret).Logger()
  474. if _, ok := d.gitleaksIgnore[globalFingerprint]; ok {
  475. logger.Debug().
  476. Str("fingerprint", globalFingerprint).
  477. Msg("skipping finding: global fingerprint")
  478. return
  479. } else if finding.Commit != "" {
  480. // Awkward nested if because I'm not sure how to chain these two conditions.
  481. if _, ok := d.gitleaksIgnore[finding.Fingerprint]; ok {
  482. logger.Debug().
  483. Str("fingerprint", finding.Fingerprint).
  484. Msgf("skipping finding: fingerprint")
  485. return
  486. }
  487. }
  488. if d.baseline != nil && !IsNew(finding, d.Redact, d.baseline) {
  489. logger.Debug().
  490. Str("fingerprint", finding.Fingerprint).
  491. Msgf("skipping finding: baseline")
  492. return
  493. }
  494. d.findingMutex.Lock()
  495. d.findings = append(d.findings, finding)
  496. if d.Verbose {
  497. printFinding(finding, d.NoColor)
  498. }
  499. d.findingMutex.Unlock()
  500. }
  501. // Findings returns the findings added to the detector
  502. func (d *Detector) Findings() []report.Finding {
  503. return d.findings
  504. }
  505. // AddCommit synchronously adds a commit to the commit slice
  506. func (d *Detector) addCommit(commit string) {
  507. d.commitMutex.Lock()
  508. d.commitMap[commit] = true
  509. d.commitMutex.Unlock()
  510. }
  511. // checkCommitOrPathAllowed evaluates |fragment| against all provided |allowlists|.
  512. //
  513. // If the match condition is "OR", only commit and path are checked.
  514. // Otherwise, if regexes or stopwords are defined this will fail.
  515. func checkCommitOrPathAllowed(
  516. logger zerolog.Logger,
  517. fragment Fragment,
  518. allowlists []*config.Allowlist,
  519. ) (bool, *zerolog.Event) {
  520. if fragment.FilePath == "" && fragment.CommitSHA == "" {
  521. return false, nil
  522. }
  523. for _, a := range allowlists {
  524. var (
  525. isAllowed bool
  526. allowlistChecks []bool
  527. commitAllowed, _ = a.CommitAllowed(fragment.CommitSHA)
  528. pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
  529. )
  530. // If the condition is "AND" we need to check all conditions.
  531. if a.MatchCondition == config.AllowlistMatchAnd {
  532. if len(a.Commits) > 0 {
  533. allowlistChecks = append(allowlistChecks, commitAllowed)
  534. }
  535. if len(a.Paths) > 0 {
  536. allowlistChecks = append(allowlistChecks, pathAllowed)
  537. }
  538. // These will be checked later.
  539. if len(a.Regexes) > 0 {
  540. continue
  541. }
  542. if len(a.StopWords) > 0 {
  543. continue
  544. }
  545. isAllowed = allTrue(allowlistChecks)
  546. } else {
  547. isAllowed = commitAllowed || pathAllowed
  548. }
  549. if isAllowed {
  550. event := logger.Trace().Str("condition", a.MatchCondition.String())
  551. if commitAllowed {
  552. event.Bool("allowed-commit", commitAllowed)
  553. }
  554. if pathAllowed {
  555. event.Bool("allowed-path", pathAllowed)
  556. }
  557. return true, event
  558. }
  559. }
  560. return false, nil
  561. }
  562. // checkFindingAllowed evaluates |finding| against all provided |allowlists|.
  563. //
  564. // If the match condition is "OR", only regex and stopwords are run. (Commit and path should be handled separately).
  565. // Otherwise, all conditions are checked.
  566. //
  567. // TODO: The method signature is awkward. I can't think of a better way to log helpful info.
  568. func checkFindingAllowed(
  569. logger zerolog.Logger,
  570. finding report.Finding,
  571. fragment Fragment,
  572. currentLine string,
  573. allowlists []*config.Allowlist,
  574. ) (bool, *zerolog.Event) {
  575. for _, a := range allowlists {
  576. allowlistTarget := finding.Secret
  577. switch a.RegexTarget {
  578. case "match":
  579. allowlistTarget = finding.Match
  580. case "line":
  581. allowlistTarget = currentLine
  582. }
  583. var (
  584. checks []bool
  585. isAllowed bool
  586. commitAllowed bool
  587. commit string
  588. pathAllowed bool
  589. regexAllowed = a.RegexAllowed(allowlistTarget)
  590. containsStopword, word = a.ContainsStopWord(finding.Secret)
  591. )
  592. // If the condition is "AND" we need to check all conditions.
  593. if a.MatchCondition == config.AllowlistMatchAnd {
  594. // Determine applicable checks.
  595. if len(a.Commits) > 0 {
  596. commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
  597. checks = append(checks, commitAllowed)
  598. }
  599. if len(a.Paths) > 0 {
  600. pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
  601. checks = append(checks, pathAllowed)
  602. }
  603. if len(a.Regexes) > 0 {
  604. checks = append(checks, regexAllowed)
  605. }
  606. if len(a.StopWords) > 0 {
  607. checks = append(checks, containsStopword)
  608. }
  609. isAllowed = allTrue(checks)
  610. } else {
  611. isAllowed = regexAllowed || containsStopword
  612. }
  613. if isAllowed {
  614. event := logger.Trace().
  615. Str("finding", finding.Secret).
  616. Str("condition", a.MatchCondition.String())
  617. if commitAllowed {
  618. event.Str("allowed-commit", commit)
  619. }
  620. if pathAllowed {
  621. event.Bool("allowed-path", pathAllowed)
  622. }
  623. if regexAllowed {
  624. event.Bool("allowed-regex", regexAllowed)
  625. }
  626. if containsStopword {
  627. event.Str("allowed-stopword", word)
  628. }
  629. return true, event
  630. }
  631. }
  632. return false, nil
  633. }
  634. func allTrue(bools []bool) bool {
  635. for _, check := range bools {
  636. if !check {
  637. return false
  638. }
  639. }
  640. return true
  641. }