detect.go 17 KB

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