detect.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. package detect
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "io"
  7. "io/fs"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "sync"
  13. "github.com/h2non/filetype"
  14. "github.com/zricethezav/gitleaks/v8/config"
  15. "github.com/zricethezav/gitleaks/v8/detect/git"
  16. "github.com/zricethezav/gitleaks/v8/report"
  17. ahocorasick "github.com/BobuSumisu/aho-corasick"
  18. "github.com/fatih/semgroup"
  19. "github.com/gitleaks/go-gitdiff/gitdiff"
  20. "github.com/rs/zerolog/log"
  21. "github.com/spf13/viper"
  22. )
  23. // Type used to differentiate between git scan types:
  24. // $ gitleaks detect
  25. // $ gitleaks protect
  26. // $ gitleaks protect staged
  27. type GitScanType int
  28. const (
  29. DetectType GitScanType = iota
  30. ProtectType
  31. ProtectStagedType
  32. gitleaksAllowSignature = "gitleaks:allow"
  33. )
  34. // Detector is the main detector struct
  35. type Detector struct {
  36. // Config is the configuration for the detector
  37. Config config.Config
  38. // Redact is a flag to redact findings. This is exported
  39. // so users using gitleaks as a library can set this flag
  40. // without calling `detector.Start(cmd *cobra.Command)`
  41. Redact uint
  42. // verbose is a flag to print findings
  43. Verbose bool
  44. // files larger than this will be skipped
  45. MaxTargetMegaBytes int
  46. // followSymlinks is a flag to enable scanning symlink files
  47. FollowSymlinks bool
  48. // NoColor is a flag to disable color output
  49. NoColor bool
  50. // commitMap is used to keep track of commits that have been scanned.
  51. // This is only used for logging purposes and git scans.
  52. commitMap map[string]bool
  53. // findingMutex is to prevent concurrent access to the
  54. // findings slice when adding findings.
  55. findingMutex *sync.Mutex
  56. // findings is a slice of report.Findings. This is the result
  57. // of the detector's scan which can then be used to generate a
  58. // report.
  59. findings []report.Finding
  60. // prefilter is a ahocorasick struct used for doing efficient string
  61. // matching given a set of words (keywords from the rules in the config)
  62. prefilter ahocorasick.Trie
  63. // a list of known findings that should be ignored
  64. baseline []report.Finding
  65. // path to baseline
  66. baselinePath string
  67. // gitleaksIgnore
  68. gitleaksIgnore map[string]bool
  69. }
  70. // Fragment contains the data to be scanned
  71. type Fragment struct {
  72. // Raw is the raw content of the fragment
  73. Raw string
  74. // FilePath is the path to the file if applicable
  75. FilePath string
  76. SymlinkFile string
  77. // CommitSHA is the SHA of the commit if applicable
  78. CommitSHA string
  79. // newlineIndices is a list of indices of newlines in the raw content.
  80. // This is used to calculate the line location of a finding
  81. newlineIndices [][]int
  82. // keywords is a map of all the keywords contain within the contents
  83. // of this fragment
  84. keywords map[string]bool
  85. }
  86. // NewDetector creates a new detector with the given config
  87. func NewDetector(cfg config.Config) *Detector {
  88. return &Detector{
  89. commitMap: make(map[string]bool),
  90. gitleaksIgnore: make(map[string]bool),
  91. findingMutex: &sync.Mutex{},
  92. findings: make([]report.Finding, 0),
  93. Config: cfg,
  94. prefilter: *ahocorasick.NewTrieBuilder().AddStrings(cfg.Keywords).Build(),
  95. }
  96. }
  97. // NewDetectorDefaultConfig creates a new detector with the default config
  98. func NewDetectorDefaultConfig() (*Detector, error) {
  99. viper.SetConfigType("toml")
  100. err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
  101. if err != nil {
  102. return nil, err
  103. }
  104. var vc config.ViperConfig
  105. err = viper.Unmarshal(&vc)
  106. if err != nil {
  107. return nil, err
  108. }
  109. cfg, err := vc.Translate()
  110. if err != nil {
  111. return nil, err
  112. }
  113. return NewDetector(cfg), nil
  114. }
  115. func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
  116. log.Debug().Msgf("found .gitleaksignore file: %s", gitleaksIgnorePath)
  117. file, err := os.Open(gitleaksIgnorePath)
  118. if err != nil {
  119. return err
  120. }
  121. // https://github.com/securego/gosec/issues/512
  122. defer func() {
  123. if err := file.Close(); err != nil {
  124. log.Warn().Msgf("Error closing .gitleaksignore file: %s\n", err)
  125. }
  126. }()
  127. scanner := bufio.NewScanner(file)
  128. for scanner.Scan() {
  129. d.gitleaksIgnore[scanner.Text()] = true
  130. }
  131. return nil
  132. }
  133. func (d *Detector) AddBaseline(baselinePath string, source string) error {
  134. if baselinePath != "" {
  135. absoluteSource, err := filepath.Abs(source)
  136. if err != nil {
  137. return err
  138. }
  139. absoluteBaseline, err := filepath.Abs(baselinePath)
  140. if err != nil {
  141. return err
  142. }
  143. relativeBaseline, err := filepath.Rel(absoluteSource, absoluteBaseline)
  144. if err != nil {
  145. return err
  146. }
  147. baseline, err := LoadBaseline(baselinePath)
  148. if err != nil {
  149. return err
  150. }
  151. d.baseline = baseline
  152. baselinePath = relativeBaseline
  153. }
  154. d.baselinePath = baselinePath
  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. // detectRule scans the given fragment for the given rule and returns a list of findings
  168. func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Finding {
  169. var findings []report.Finding
  170. // check if filepath or commit is allowed for this rule
  171. if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
  172. rule.Allowlist.PathAllowed(fragment.FilePath) {
  173. return findings
  174. }
  175. if rule.Path != nil && rule.Regex == nil {
  176. // Path _only_ rule
  177. if rule.Path.Match([]byte(fragment.FilePath)) {
  178. finding := report.Finding{
  179. Description: rule.Description,
  180. File: fragment.FilePath,
  181. SymlinkFile: fragment.SymlinkFile,
  182. RuleID: rule.RuleID,
  183. Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
  184. Tags: rule.Tags,
  185. }
  186. return append(findings, finding)
  187. }
  188. } else if rule.Path != nil {
  189. // if path is set _and_ a regex is set, then we need to check both
  190. // so if the path does not match, then we should return early and not
  191. // consider the regex
  192. if !rule.Path.Match([]byte(fragment.FilePath)) {
  193. return findings
  194. }
  195. }
  196. // if path only rule, skip content checks
  197. if rule.Regex == nil {
  198. return findings
  199. }
  200. // If flag configure and raw data size bigger then the flag
  201. if d.MaxTargetMegaBytes > 0 {
  202. rawLength := len(fragment.Raw) / 1000000
  203. if rawLength > d.MaxTargetMegaBytes {
  204. log.Debug().Msgf("skipping file: %s scan due to size: %d", fragment.FilePath, rawLength)
  205. return findings
  206. }
  207. }
  208. matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
  209. for _, matchIndex := range matchIndices {
  210. // extract secret from match
  211. secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
  212. // determine location of match. Note that the location
  213. // in the finding will be the line/column numbers of the _match_
  214. // not the _secret_, which will be different if the secretGroup
  215. // value is set for this rule
  216. loc := location(fragment, matchIndex)
  217. if matchIndex[1] > loc.endLineIndex {
  218. loc.endLineIndex = matchIndex[1]
  219. }
  220. finding := report.Finding{
  221. Description: rule.Description,
  222. File: fragment.FilePath,
  223. SymlinkFile: fragment.SymlinkFile,
  224. RuleID: rule.RuleID,
  225. StartLine: loc.startLine,
  226. EndLine: loc.endLine,
  227. StartColumn: loc.startColumn,
  228. EndColumn: loc.endColumn,
  229. Secret: secret,
  230. Match: secret,
  231. Tags: rule.Tags,
  232. Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
  233. }
  234. if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
  235. gitleaksAllowSignature) {
  236. continue
  237. }
  238. // extract secret from secret group if set
  239. if rule.SecretGroup != 0 {
  240. groups := rule.Regex.FindStringSubmatch(secret)
  241. if len(groups) <= rule.SecretGroup || len(groups) == 0 {
  242. // Config validation should prevent this
  243. continue
  244. }
  245. secret = groups[rule.SecretGroup]
  246. finding.Secret = secret
  247. }
  248. // check if the regexTarget is defined in the allowlist "regexes" entry
  249. allowlistTarget := finding.Secret
  250. switch rule.Allowlist.RegexTarget {
  251. case "match":
  252. allowlistTarget = finding.Match
  253. case "line":
  254. allowlistTarget = finding.Line
  255. }
  256. globalAllowlistTarget := finding.Secret
  257. switch d.Config.Allowlist.RegexTarget {
  258. case "match":
  259. globalAllowlistTarget = finding.Match
  260. case "line":
  261. globalAllowlistTarget = finding.Line
  262. }
  263. if rule.Allowlist.RegexAllowed(allowlistTarget) ||
  264. d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
  265. continue
  266. }
  267. // check if the secret is in the list of stopwords
  268. if rule.Allowlist.ContainsStopWord(finding.Secret) ||
  269. d.Config.Allowlist.ContainsStopWord(finding.Secret) {
  270. continue
  271. }
  272. // check entropy
  273. entropy := shannonEntropy(finding.Secret)
  274. finding.Entropy = float32(entropy)
  275. if rule.Entropy != 0.0 {
  276. if entropy <= rule.Entropy {
  277. // entropy is too low, skip this finding
  278. continue
  279. }
  280. // NOTE: this is a goofy hack to get around the fact there golang's regex engine
  281. // does not support positive lookaheads. Ideally we would want to add a
  282. // restriction on generic rules regex that requires the secret match group
  283. // contains both numbers and alphabetical characters, not just alphabetical characters.
  284. // What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
  285. // secret contains both digits and alphabetical characters.
  286. // TODO: this should be replaced with stop words
  287. if strings.HasPrefix(rule.RuleID, "generic") {
  288. if !containsDigit(secret) {
  289. continue
  290. }
  291. }
  292. }
  293. findings = append(findings, finding)
  294. }
  295. return findings
  296. }
  297. // DetectGit accepts source directory, log opts and GitScanType and returns a slice of report.Finding.
  298. func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
  299. var (
  300. diffFilesCmd *git.DiffFilesCmd
  301. err error
  302. )
  303. switch gitScanType {
  304. case DetectType:
  305. diffFilesCmd, err = git.NewGitLogCmd(source, logOpts)
  306. if err != nil {
  307. return d.findings, err
  308. }
  309. case ProtectType:
  310. diffFilesCmd, err = git.NewGitDiffCmd(source, false)
  311. if err != nil {
  312. return d.findings, err
  313. }
  314. case ProtectStagedType:
  315. diffFilesCmd, err = git.NewGitDiffCmd(source, true)
  316. if err != nil {
  317. return d.findings, err
  318. }
  319. }
  320. defer diffFilesCmd.Wait()
  321. diffFilesCh := diffFilesCmd.DiffFilesCh()
  322. errCh := diffFilesCmd.ErrCh()
  323. s := semgroup.NewGroup(context.Background(), 4)
  324. // loop to range over both DiffFiles (stdout) and ErrCh (stderr)
  325. for diffFilesCh != nil || errCh != nil {
  326. select {
  327. case gitdiffFile, open := <-diffFilesCh:
  328. if !open {
  329. diffFilesCh = nil
  330. break
  331. }
  332. // skip binary files
  333. if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
  334. continue
  335. }
  336. // Check if commit is allowed
  337. commitSHA := ""
  338. if gitdiffFile.PatchHeader != nil {
  339. commitSHA = gitdiffFile.PatchHeader.SHA
  340. if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
  341. continue
  342. }
  343. }
  344. d.addCommit(commitSHA)
  345. s.Go(func() error {
  346. for _, textFragment := range gitdiffFile.TextFragments {
  347. if textFragment == nil {
  348. return nil
  349. }
  350. fragment := Fragment{
  351. Raw: textFragment.Raw(gitdiff.OpAdd),
  352. CommitSHA: commitSHA,
  353. FilePath: gitdiffFile.NewName,
  354. }
  355. for _, finding := range d.Detect(fragment) {
  356. d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
  357. }
  358. }
  359. return nil
  360. })
  361. case err, open := <-errCh:
  362. if !open {
  363. errCh = nil
  364. break
  365. }
  366. return d.findings, err
  367. }
  368. }
  369. if err := s.Wait(); err != nil {
  370. return d.findings, err
  371. }
  372. log.Info().Msgf("%d commits scanned.", len(d.commitMap))
  373. log.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
  374. return d.findings, nil
  375. }
  376. type scanTarget struct {
  377. Path string
  378. Symlink string
  379. }
  380. // DetectFiles accepts a path to a source directory or file and begins a scan of the
  381. // file or directory.
  382. func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
  383. s := semgroup.NewGroup(context.Background(), 4)
  384. paths := make(chan scanTarget)
  385. s.Go(func() error {
  386. defer close(paths)
  387. return filepath.Walk(source,
  388. func(path string, fInfo os.FileInfo, err error) error {
  389. if err != nil {
  390. return err
  391. }
  392. if fInfo.Name() == ".git" && fInfo.IsDir() {
  393. return filepath.SkipDir
  394. }
  395. if fInfo.Size() == 0 {
  396. return nil
  397. }
  398. if fInfo.Mode().IsRegular() {
  399. paths <- scanTarget{
  400. Path: path,
  401. Symlink: "",
  402. }
  403. }
  404. if fInfo.Mode().Type() == fs.ModeSymlink && d.FollowSymlinks {
  405. realPath, err := filepath.EvalSymlinks(path)
  406. if err != nil {
  407. return err
  408. }
  409. realPathFileInfo, _ := os.Stat(realPath)
  410. if realPathFileInfo.IsDir() {
  411. log.Debug().Msgf("found symlinked directory: %s -> %s [skipping]", path, realPath)
  412. return nil
  413. }
  414. paths <- scanTarget{
  415. Path: realPath,
  416. Symlink: path,
  417. }
  418. }
  419. return nil
  420. })
  421. })
  422. for pa := range paths {
  423. p := pa
  424. s.Go(func() error {
  425. b, err := os.ReadFile(p.Path)
  426. if err != nil {
  427. return err
  428. }
  429. mimetype, err := filetype.Match(b)
  430. if err != nil {
  431. return err
  432. }
  433. if mimetype.MIME.Type == "application" {
  434. return nil // skip binary files
  435. }
  436. fragment := Fragment{
  437. Raw: string(b),
  438. FilePath: p.Path,
  439. }
  440. if p.Symlink != "" {
  441. fragment.SymlinkFile = p.Symlink
  442. }
  443. for _, finding := range d.Detect(fragment) {
  444. // need to add 1 since line counting starts at 1
  445. finding.EndLine++
  446. finding.StartLine++
  447. d.addFinding(finding)
  448. }
  449. return nil
  450. })
  451. }
  452. if err := s.Wait(); err != nil {
  453. return d.findings, err
  454. }
  455. return d.findings, nil
  456. }
  457. // DetectReader accepts an io.Reader and a buffer size for the reader in KB
  458. func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, error) {
  459. reader := bufio.NewReader(r)
  460. buf := make([]byte, 0, 1000*bufSize)
  461. findings := []report.Finding{}
  462. for {
  463. n, err := reader.Read(buf[:cap(buf)])
  464. buf = buf[:n]
  465. if err != nil {
  466. if err != io.EOF {
  467. return findings, err
  468. }
  469. break
  470. }
  471. fragment := Fragment{
  472. Raw: string(buf),
  473. }
  474. for _, finding := range d.Detect(fragment) {
  475. findings = append(findings, finding)
  476. if d.Verbose {
  477. printFinding(finding, d.NoColor)
  478. }
  479. }
  480. }
  481. return findings, nil
  482. }
  483. // Detect scans the given fragment and returns a list of findings
  484. func (d *Detector) Detect(fragment Fragment) []report.Finding {
  485. var findings []report.Finding
  486. // initiate fragment keywords
  487. fragment.keywords = make(map[string]bool)
  488. // check if filepath is allowed
  489. if fragment.FilePath != "" && (d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
  490. fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath)) {
  491. return findings
  492. }
  493. // add newline indices for location calculation in detectRule
  494. fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
  495. // build keyword map for prefiltering rules
  496. normalizedRaw := strings.ToLower(fragment.Raw)
  497. matches := d.prefilter.MatchString(normalizedRaw)
  498. for _, m := range matches {
  499. fragment.keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
  500. }
  501. for _, rule := range d.Config.Rules {
  502. if len(rule.Keywords) == 0 {
  503. // if not keywords are associated with the rule always scan the
  504. // fragment using the rule
  505. findings = append(findings, d.detectRule(fragment, rule)...)
  506. continue
  507. }
  508. fragmentContainsKeyword := false
  509. // check if keywords are in the fragment
  510. for _, k := range rule.Keywords {
  511. if _, ok := fragment.keywords[strings.ToLower(k)]; ok {
  512. fragmentContainsKeyword = true
  513. }
  514. }
  515. if fragmentContainsKeyword {
  516. findings = append(findings, d.detectRule(fragment, rule)...)
  517. }
  518. }
  519. return filter(findings, d.Redact)
  520. }
  521. // addFinding synchronously adds a finding to the findings slice
  522. func (d *Detector) addFinding(finding report.Finding) {
  523. globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine)
  524. if finding.Commit != "" {
  525. finding.Fingerprint = fmt.Sprintf("%s:%s:%s:%d", finding.Commit, finding.File, finding.RuleID, finding.StartLine)
  526. } else {
  527. finding.Fingerprint = globalFingerprint
  528. }
  529. // check if we should ignore this finding
  530. if _, ok := d.gitleaksIgnore[globalFingerprint]; ok {
  531. log.Debug().Msgf("ignoring finding with global Fingerprint %s",
  532. finding.Fingerprint)
  533. return
  534. } else if finding.Commit != "" {
  535. // Awkward nested if because I'm not sure how to chain these two conditions.
  536. if _, ok := d.gitleaksIgnore[finding.Fingerprint]; ok {
  537. log.Debug().Msgf("ignoring finding with Fingerprint %s",
  538. finding.Fingerprint)
  539. return
  540. }
  541. }
  542. if d.baseline != nil && !IsNew(finding, d.baseline) {
  543. log.Debug().Msgf("baseline duplicate -- ignoring finding with Fingerprint %s", finding.Fingerprint)
  544. return
  545. }
  546. d.findingMutex.Lock()
  547. d.findings = append(d.findings, finding)
  548. if d.Verbose {
  549. printFinding(finding, d.NoColor)
  550. }
  551. d.findingMutex.Unlock()
  552. }
  553. // addCommit synchronously adds a commit to the commit slice
  554. func (d *Detector) addCommit(commit string) {
  555. d.commitMap[commit] = true
  556. }