detect.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. // if path only rule, skip content checks
  129. if rule.Regex == nil {
  130. return findings
  131. }
  132. matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
  133. for _, matchIndex := range matchIndices {
  134. // extract secret from match
  135. secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
  136. // determine location of match. Note that the location
  137. // in the finding will be the line/column numbers of the _match_
  138. // not the _secret_, which will be different if the secretGroup
  139. // value is set for this rule
  140. loc := location(fragment, matchIndex)
  141. finding := report.Finding{
  142. Description: rule.Description,
  143. File: fragment.FilePath,
  144. RuleID: rule.RuleID,
  145. StartLine: loc.startLine,
  146. EndLine: loc.endLine,
  147. StartColumn: loc.startColumn,
  148. EndColumn: loc.endColumn,
  149. Secret: secret,
  150. Match: secret,
  151. Tags: rule.Tags,
  152. }
  153. if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
  154. gitleaksAllowSignature) {
  155. continue
  156. }
  157. // extract secret from secret group if set
  158. if rule.SecretGroup != 0 {
  159. groups := rule.Regex.FindStringSubmatch(secret)
  160. if len(groups) <= rule.SecretGroup || len(groups) == 0 {
  161. // Config validation should prevent this
  162. continue
  163. }
  164. secret = groups[rule.SecretGroup]
  165. finding.Secret = secret
  166. }
  167. // check if the secret is in the allowlist
  168. if rule.Allowlist.RegexAllowed(finding.Secret) ||
  169. d.Config.Allowlist.RegexAllowed(finding.Secret) {
  170. continue
  171. }
  172. // check entropy
  173. entropy := shannonEntropy(finding.Secret)
  174. finding.Entropy = float32(entropy)
  175. if rule.Entropy != 0.0 {
  176. if entropy <= rule.Entropy {
  177. // entropy is too low, skip this finding
  178. continue
  179. }
  180. // NOTE: this is a goofy hack to get around the fact there golang's regex engine
  181. // does not support positive lookaheads. Ideally we would want to add a
  182. // restriction on generic rules regex that requires the secret match group
  183. // contains both numbers and alphabetical characters, not just alphabetical characters.
  184. // What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
  185. // secret contains both digits and alphabetical characters.
  186. // TODO: this should be replaced with stop words
  187. if strings.HasPrefix(rule.RuleID, "generic") {
  188. if !containsDigit(secret) {
  189. continue
  190. }
  191. }
  192. }
  193. findings = append(findings, finding)
  194. }
  195. return findings
  196. }
  197. // GitScan accepts a *gitdiff.File channel which contents a git history generated from
  198. // the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
  199. // and determine if the patch contains any findings.
  200. func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
  201. var (
  202. gitdiffFiles <-chan *gitdiff.File
  203. err error
  204. )
  205. switch gitScanType {
  206. case DetectType:
  207. gitdiffFiles, err = git.GitLog(source, logOpts)
  208. if err != nil {
  209. return d.findings, err
  210. }
  211. case ProtectType:
  212. gitdiffFiles, err = git.GitDiff(source, false)
  213. if err != nil {
  214. return d.findings, err
  215. }
  216. case ProtectStagedType:
  217. gitdiffFiles, err = git.GitDiff(source, true)
  218. if err != nil {
  219. return d.findings, err
  220. }
  221. }
  222. s := semgroup.NewGroup(context.Background(), 4)
  223. for gitdiffFile := range gitdiffFiles {
  224. gitdiffFile := gitdiffFile
  225. // skip binary files
  226. if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
  227. continue
  228. }
  229. // Check if commit is allowed
  230. commitSHA := ""
  231. if gitdiffFile.PatchHeader != nil {
  232. commitSHA = gitdiffFile.PatchHeader.SHA
  233. if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
  234. continue
  235. }
  236. }
  237. d.addCommit(commitSHA)
  238. s.Go(func() error {
  239. for _, textFragment := range gitdiffFile.TextFragments {
  240. if textFragment == nil {
  241. return nil
  242. }
  243. fragment := Fragment{
  244. Raw: textFragment.Raw(gitdiff.OpAdd),
  245. CommitSHA: commitSHA,
  246. FilePath: gitdiffFile.NewName,
  247. }
  248. for _, finding := range d.Detect(fragment) {
  249. d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
  250. }
  251. }
  252. return nil
  253. })
  254. }
  255. if err := s.Wait(); err != nil {
  256. return d.findings, err
  257. }
  258. log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(d.commitMap))
  259. return d.findings, nil
  260. }
  261. // DetectFiles accepts a path to a source directory or file and begins a scan of the
  262. // file or directory.
  263. func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
  264. s := semgroup.NewGroup(context.Background(), 4)
  265. paths := make(chan string)
  266. s.Go(func() error {
  267. defer close(paths)
  268. return filepath.Walk(source,
  269. func(path string, fInfo os.FileInfo, err error) error {
  270. if err != nil {
  271. return err
  272. }
  273. if fInfo.Name() == ".git" {
  274. return filepath.SkipDir
  275. }
  276. if fInfo.Mode().IsRegular() {
  277. paths <- path
  278. }
  279. return nil
  280. })
  281. })
  282. for pa := range paths {
  283. p := pa
  284. s.Go(func() error {
  285. b, err := os.ReadFile(p)
  286. if err != nil {
  287. return err
  288. }
  289. mimetype, err := filetype.Match(b)
  290. if err != nil {
  291. return err
  292. }
  293. if mimetype.MIME.Type == "application" {
  294. return nil // skip binary files
  295. }
  296. fragment := Fragment{
  297. Raw: string(b),
  298. FilePath: p,
  299. }
  300. for _, finding := range d.Detect(fragment) {
  301. // need to add 1 since line counting starts at 1
  302. finding.EndLine++
  303. finding.StartLine++
  304. d.addFinding(finding)
  305. }
  306. return nil
  307. })
  308. }
  309. if err := s.Wait(); err != nil {
  310. return d.findings, err
  311. }
  312. return d.findings, nil
  313. }
  314. // Detect scans the given fragment and returns a list of findings
  315. func (d *Detector) Detect(fragment Fragment) []report.Finding {
  316. var findings []report.Finding
  317. // check if filepath is allowed
  318. if d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
  319. fragment.FilePath == d.Config.Path {
  320. return findings
  321. }
  322. // add newline indices for location calculation in detectRule
  323. fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
  324. for _, rule := range d.Config.Rules {
  325. findings = append(findings, d.detectRule(fragment, rule)...)
  326. }
  327. return filter(findings, d.Redact)
  328. }
  329. // addFinding synchronously adds a finding to the findings slice
  330. func (d *Detector) addFinding(finding report.Finding) {
  331. d.findingMutex.Lock()
  332. d.findings = append(d.findings, finding)
  333. if d.Verbose {
  334. printFinding(finding)
  335. }
  336. d.findingMutex.Unlock()
  337. }
  338. // addCommit synchronously adds a commit to the commit slice
  339. func (d *Detector) addCommit(commit string) {
  340. d.commitMap[commit] = true
  341. }