detect.go 11 KB

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