detect.go 16 KB

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