detect.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package detect
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. "strings"
  9. "sync"
  10. "github.com/zricethezav/gitleaks/v8/config"
  11. "github.com/zricethezav/gitleaks/v8/detect/git"
  12. "github.com/zricethezav/gitleaks/v8/report"
  13. "github.com/fatih/semgroup"
  14. "github.com/gitleaks/go-gitdiff/gitdiff"
  15. "github.com/h2non/filetype"
  16. "github.com/rs/zerolog/log"
  17. "github.com/spf13/viper"
  18. )
  19. // Type used to differentiate between git scan types:
  20. // $ gitleaks detect
  21. // $ gitleaks protect
  22. // $ gitleaks protect staged
  23. type GitScanType int
  24. const (
  25. DetectType GitScanType = iota
  26. ProtectType
  27. ProtectStagedType
  28. gitleaksAllowSignature = "gitleaks:allow"
  29. )
  30. // Detector is the main detector struct
  31. type Detector struct {
  32. // Config is the configuration for the detector
  33. Config config.Config
  34. // Redact is a flag to redact findings. This is exported
  35. // so users using gitleaks as a library can set this flag
  36. // without calling `detector.Start(cmd *cobra.Command)`
  37. Redact bool
  38. // verbose is a flag to print findings
  39. Verbose bool
  40. // commitMap is used to keep track of commits that have been scanned.
  41. // This is only used for logging purposes and git scans.
  42. commitMap map[string]bool
  43. // findingMutex is to prevent concurrent access to the
  44. // findings slice when adding findings.
  45. findingMutex *sync.Mutex
  46. // findings is a slice of report.Findings. This is the result
  47. // of the detector's scan which can then be used to generate a
  48. // report.
  49. findings []report.Finding
  50. }
  51. // Fragment contains the data to be scanned
  52. type Fragment struct {
  53. // Raw is the raw content of the fragment
  54. Raw string
  55. // FilePath is the path to the file if applicable
  56. FilePath string
  57. // CommitSHA is the SHA of the commit if applicable
  58. CommitSHA string
  59. // newlineIndices is a list of indices of newlines in the raw content.
  60. // This is used to calculate the line location of a finding
  61. newlineIndices [][]int
  62. }
  63. // NewDetector creates a new detector with the given config
  64. func NewDetector(cfg config.Config) *Detector {
  65. return &Detector{
  66. commitMap: make(map[string]bool),
  67. findingMutex: &sync.Mutex{},
  68. findings: make([]report.Finding, 0),
  69. Config: cfg,
  70. }
  71. }
  72. // NewDetectorDefaultConfig creates a new detector with the default config
  73. func NewDetectorDefaultConfig() (*Detector, error) {
  74. viper.SetConfigType("toml")
  75. err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
  76. if err != nil {
  77. return nil, err
  78. }
  79. var vc config.ViperConfig
  80. err = viper.Unmarshal(&vc)
  81. if err != nil {
  82. return nil, err
  83. }
  84. cfg, err := vc.Translate()
  85. if err != nil {
  86. return nil, err
  87. }
  88. return NewDetector(cfg), nil
  89. }
  90. // DetectBytes scans the given bytes and returns a list of findings
  91. func (d *Detector) DetectBytes(content []byte) []report.Finding {
  92. return d.DetectString(string(content))
  93. }
  94. // DetectString scans the given string and returns a list of findings
  95. func (d *Detector) DetectString(content string) []report.Finding {
  96. return d.Detect(Fragment{
  97. Raw: content,
  98. })
  99. }
  100. // detectRule scans the given fragment for the given rule and returns a list of findings
  101. func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding {
  102. var findings []report.Finding
  103. // check if filepath or commit is allowed for this rule
  104. if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
  105. rule.Allowlist.PathAllowed(fragment.FilePath) {
  106. return findings
  107. }
  108. if rule.Path != nil && rule.Regex == nil {
  109. // Path _only_ rule
  110. if rule.Path.Match([]byte(fragment.FilePath)) {
  111. finding := report.Finding{
  112. Description: rule.Description,
  113. File: fragment.FilePath,
  114. RuleID: rule.RuleID,
  115. Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
  116. Tags: rule.Tags,
  117. }
  118. return append(findings, finding)
  119. }
  120. } else if rule.Path != nil {
  121. // if path is set _and_ a regex is set, then we need to check both
  122. // so if the path does not match, then we should return early and not
  123. // consider the regex
  124. if !rule.Path.Match([]byte(fragment.FilePath)) {
  125. return findings
  126. }
  127. }
  128. matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
  129. for _, matchIndex := range matchIndices {
  130. // extract secret from match
  131. secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
  132. // determine location of match. Note that the location
  133. // in the finding will be the line/column numbers of the _match_
  134. // not the _secret_, which will be different if the secretGroup
  135. // value is set for this rule
  136. loc := location(fragment, matchIndex)
  137. finding := report.Finding{
  138. Description: rule.Description,
  139. File: fragment.FilePath,
  140. RuleID: rule.RuleID,
  141. StartLine: loc.startLine,
  142. EndLine: loc.endLine,
  143. StartColumn: loc.startColumn,
  144. EndColumn: loc.endColumn,
  145. Secret: secret,
  146. Match: secret,
  147. Tags: rule.Tags,
  148. }
  149. if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
  150. gitleaksAllowSignature) {
  151. continue
  152. }
  153. // extract secret from secret group if set
  154. if rule.SecretGroup != 0 {
  155. groups := rule.Regex.FindStringSubmatch(secret)
  156. if len(groups) <= rule.SecretGroup || len(groups) == 0 {
  157. // Config validation should prevent this
  158. continue
  159. }
  160. secret = groups[rule.SecretGroup]
  161. finding.Secret = secret
  162. }
  163. // check if the secret is in the allowlist
  164. if rule.Allowlist.RegexAllowed(finding.Secret) ||
  165. d.Config.Allowlist.RegexAllowed(finding.Secret) {
  166. continue
  167. }
  168. // check entropy
  169. entropy := shannonEntropy(finding.Secret)
  170. finding.Entropy = float32(entropy)
  171. if rule.Entropy != 0.0 {
  172. if entropy <= rule.Entropy {
  173. // entropy is too low, skip this finding
  174. continue
  175. }
  176. // NOTE: this is a goofy hack to get around the fact there golang's regex engine
  177. // does not support positive lookaheads. Ideally we would want to add a
  178. // restriction on generic rules regex that requires the secret match group
  179. // contains both numbers and alphabetical characters, not just alphabetical characters.
  180. // What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
  181. // secret contains both digits and alphabetical characters.
  182. // TODO: this should be replaced with stop words
  183. if strings.HasPrefix(rule.RuleID, "generic") {
  184. if !containsDigit(secret) {
  185. continue
  186. }
  187. }
  188. }
  189. findings = append(findings, finding)
  190. }
  191. return findings
  192. }
  193. // GitScan accepts a *gitdiff.File channel which contents a git history generated from
  194. // the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
  195. // and determine if the patch contains any findings.
  196. func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
  197. var (
  198. gitdiffFiles <-chan *gitdiff.File
  199. err error
  200. )
  201. switch gitScanType {
  202. case DetectType:
  203. gitdiffFiles, err = git.GitLog(source, logOpts)
  204. if err != nil {
  205. return d.findings, err
  206. }
  207. case ProtectType:
  208. gitdiffFiles, err = git.GitDiff(source, false)
  209. if err != nil {
  210. return d.findings, err
  211. }
  212. case ProtectStagedType:
  213. gitdiffFiles, err = git.GitDiff(source, true)
  214. if err != nil {
  215. return d.findings, err
  216. }
  217. }
  218. s := semgroup.NewGroup(context.Background(), 4)
  219. for gitdiffFile := range gitdiffFiles {
  220. gitdiffFile := gitdiffFile
  221. // skip binary files
  222. if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
  223. continue
  224. }
  225. // Check if commit is allowed
  226. commitSHA := ""
  227. if gitdiffFile.PatchHeader != nil {
  228. commitSHA = gitdiffFile.PatchHeader.SHA
  229. if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
  230. continue
  231. }
  232. }
  233. d.addCommit(commitSHA)
  234. s.Go(func() error {
  235. for _, textFragment := range gitdiffFile.TextFragments {
  236. if textFragment == nil {
  237. return nil
  238. }
  239. fragment := Fragment{
  240. Raw: textFragment.Raw(gitdiff.OpAdd),
  241. CommitSHA: commitSHA,
  242. FilePath: gitdiffFile.NewName,
  243. }
  244. for _, finding := range d.Detect(fragment) {
  245. d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
  246. }
  247. }
  248. return nil
  249. })
  250. }
  251. if err := s.Wait(); err != nil {
  252. return d.findings, err
  253. }
  254. log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(d.commitMap))
  255. return d.findings, nil
  256. }
  257. // DetectFiles accepts a path to a source directory or file and begins a scan of the
  258. // file or directory.
  259. func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
  260. s := semgroup.NewGroup(context.Background(), 4)
  261. paths := make(chan string)
  262. s.Go(func() error {
  263. defer close(paths)
  264. return filepath.Walk(source,
  265. func(path string, fInfo os.FileInfo, err error) error {
  266. if err != nil {
  267. return err
  268. }
  269. if fInfo.Name() == ".git" {
  270. return filepath.SkipDir
  271. }
  272. if fInfo.Mode().IsRegular() {
  273. paths <- path
  274. }
  275. return nil
  276. })
  277. })
  278. for pa := range paths {
  279. p := pa
  280. s.Go(func() error {
  281. b, err := os.ReadFile(p)
  282. if err != nil {
  283. return err
  284. }
  285. mimetype, err := filetype.Match(b)
  286. if err != nil {
  287. return err
  288. }
  289. if mimetype.MIME.Type == "application" {
  290. return nil // skip binary files
  291. }
  292. fragment := Fragment{
  293. Raw: string(b),
  294. FilePath: p,
  295. }
  296. for _, finding := range d.Detect(fragment) {
  297. // need to add 1 since line counting starts at 1
  298. finding.EndLine++
  299. finding.StartLine++
  300. d.addFinding(finding)
  301. }
  302. return nil
  303. })
  304. }
  305. if err := s.Wait(); err != nil {
  306. return d.findings, err
  307. }
  308. return d.findings, nil
  309. }
  310. // Detect scans the given fragment and returns a list of findings
  311. func (d *Detector) Detect(fragment Fragment) []report.Finding {
  312. var findings []report.Finding
  313. // check if filepath is allowed
  314. if d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
  315. fragment.FilePath == d.Config.Path {
  316. return findings
  317. }
  318. // add newline indices for location calculation in detectRule
  319. fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
  320. for _, rule := range d.Config.Rules {
  321. findings = append(findings, d.detectRule(fragment, rule)...)
  322. }
  323. return filter(findings, d.Redact)
  324. }
  325. // addFinding synchronously adds a finding to the findings slice
  326. func (d *Detector) addFinding(finding report.Finding) {
  327. d.findingMutex.Lock()
  328. d.findings = append(d.findings, finding)
  329. if d.Verbose {
  330. printFinding(finding)
  331. }
  332. d.findingMutex.Unlock()
  333. }
  334. // addCommit synchronously adds a commit to the commit slice
  335. func (d *Detector) addCommit(commit string) {
  336. d.commitMap[commit] = true
  337. }