detect.go 16 KB

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