detect.go 10 KB

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