detect.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package detect
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "os"
  7. "regexp"
  8. "strings"
  9. "sync"
  10. "github.com/zricethezav/gitleaks/v8/config"
  11. "github.com/zricethezav/gitleaks/v8/report"
  12. ahocorasick "github.com/BobuSumisu/aho-corasick"
  13. "github.com/fatih/semgroup"
  14. "github.com/rs/zerolog/log"
  15. "github.com/spf13/viper"
  16. "golang.org/x/exp/maps"
  17. )
  18. const (
  19. gitleaksAllowSignature = "gitleaks:allow"
  20. chunkSize = 10 * 1_000 // 10kb
  21. )
  22. // Detector is the main detector struct
  23. type Detector struct {
  24. // Config is the configuration for the detector
  25. Config config.Config
  26. // Redact is a flag to redact findings. This is exported
  27. // so users using gitleaks as a library can set this flag
  28. // without calling `detector.Start(cmd *cobra.Command)`
  29. Redact uint
  30. // verbose is a flag to print findings
  31. Verbose bool
  32. // files larger than this will be skipped
  33. MaxTargetMegaBytes int
  34. // followSymlinks is a flag to enable scanning symlink files
  35. FollowSymlinks bool
  36. // NoColor is a flag to disable color output
  37. NoColor bool
  38. // IgnoreGitleaksAllow is a flag to ignore gitleaks:allow comments.
  39. IgnoreGitleaksAllow 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. // prefilter is a ahocorasick struct used for doing efficient string
  51. // matching given a set of words (keywords from the rules in the config)
  52. prefilter ahocorasick.Trie
  53. // a list of known findings that should be ignored
  54. baseline []report.Finding
  55. // path to baseline
  56. baselinePath string
  57. // gitleaksIgnore
  58. gitleaksIgnore map[string]bool
  59. // Sema (https://github.com/fatih/semgroup) controls the concurrency
  60. Sema *semgroup.Group
  61. }
  62. // Fragment contains the data to be scanned
  63. type Fragment struct {
  64. // Raw is the raw content of the fragment
  65. Raw string
  66. // FilePath is the path to the file if applicable
  67. FilePath string
  68. SymlinkFile string
  69. // CommitSHA is the SHA of the commit if applicable
  70. CommitSHA string
  71. // newlineIndices is a list of indices of newlines in the raw content.
  72. // This is used to calculate the line location of a finding
  73. newlineIndices [][]int
  74. // keywords is a map of all the keywords contain within the contents
  75. // of this fragment
  76. keywords map[string]bool
  77. }
  78. // NewDetector creates a new detector with the given config
  79. func NewDetector(cfg config.Config) *Detector {
  80. return &Detector{
  81. commitMap: make(map[string]bool),
  82. gitleaksIgnore: make(map[string]bool),
  83. findingMutex: &sync.Mutex{},
  84. findings: make([]report.Finding, 0),
  85. Config: cfg,
  86. prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
  87. Sema: semgroup.NewGroup(context.Background(), 40),
  88. }
  89. }
  90. // NewDetectorDefaultConfig creates a new detector with the default config
  91. func NewDetectorDefaultConfig() (*Detector, error) {
  92. viper.SetConfigType("toml")
  93. err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
  94. if err != nil {
  95. return nil, err
  96. }
  97. var vc config.ViperConfig
  98. err = viper.Unmarshal(&vc)
  99. if err != nil {
  100. return nil, err
  101. }
  102. cfg, err := vc.Translate()
  103. if err != nil {
  104. return nil, err
  105. }
  106. return NewDetector(cfg), nil
  107. }
  108. func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
  109. log.Debug().Msgf("found .gitleaksignore file: %s", gitleaksIgnorePath)
  110. file, err := os.Open(gitleaksIgnorePath)
  111. if err != nil {
  112. return err
  113. }
  114. // https://github.com/securego/gosec/issues/512
  115. defer func() {
  116. if err := file.Close(); err != nil {
  117. log.Warn().Msgf("Error closing .gitleaksignore file: %s\n", err)
  118. }
  119. }()
  120. scanner := bufio.NewScanner(file)
  121. for scanner.Scan() {
  122. line := strings.TrimSpace(scanner.Text())
  123. // Skip lines that start with a comment
  124. if line != "" && !strings.HasPrefix(line, "#") {
  125. d.gitleaksIgnore[line] = true
  126. }
  127. }
  128. return nil
  129. }
  130. // DetectBytes scans the given bytes and returns a list of findings
  131. func (d *Detector) DetectBytes(content []byte) []report.Finding {
  132. return d.DetectString(string(content))
  133. }
  134. // DetectString scans the given string and returns a list of findings
  135. func (d *Detector) DetectString(content string) []report.Finding {
  136. return d.Detect(Fragment{
  137. Raw: content,
  138. })
  139. }
  140. // Detect scans the given fragment and returns a list of findings
  141. func (d *Detector) Detect(fragment Fragment) []report.Finding {
  142. var findings []report.Finding
  143. // initiate fragment keywords
  144. fragment.keywords = make(map[string]bool)
  145. // check if filepath is allowed
  146. if fragment.FilePath != "" && (d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
  147. fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath)) {
  148. return findings
  149. }
  150. // add newline indices for location calculation in detectRule
  151. fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
  152. // build keyword map for prefiltering rules
  153. normalizedRaw := strings.ToLower(fragment.Raw)
  154. matches := d.prefilter.MatchString(normalizedRaw)
  155. for _, m := range matches {
  156. fragment.keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
  157. }
  158. for _, rule := range d.Config.Rules {
  159. if len(rule.Keywords) == 0 {
  160. // if not keywords are associated with the rule always scan the
  161. // fragment using the rule
  162. findings = append(findings, d.detectRule(fragment, rule)...)
  163. continue
  164. }
  165. fragmentContainsKeyword := false
  166. // check if keywords are in the fragment
  167. for _, k := range rule.Keywords {
  168. if _, ok := fragment.keywords[strings.ToLower(k)]; ok {
  169. fragmentContainsKeyword = true
  170. }
  171. }
  172. if fragmentContainsKeyword {
  173. findings = append(findings, d.detectRule(fragment, rule)...)
  174. }
  175. }
  176. return filter(findings, d.Redact)
  177. }
  178. // detectRule scans the given fragment for the given rule and returns a list of findings
  179. func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Finding {
  180. var findings []report.Finding
  181. // check if filepath or commit is allowed for this rule
  182. if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
  183. rule.Allowlist.PathAllowed(fragment.FilePath) {
  184. return findings
  185. }
  186. if rule.Path != nil && rule.Regex == nil {
  187. // Path _only_ rule
  188. if rule.Path.MatchString(fragment.FilePath) {
  189. finding := report.Finding{
  190. Description: rule.Description,
  191. File: fragment.FilePath,
  192. SymlinkFile: fragment.SymlinkFile,
  193. RuleID: rule.RuleID,
  194. Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
  195. Tags: rule.Tags,
  196. }
  197. return append(findings, finding)
  198. }
  199. } else if rule.Path != nil {
  200. // if path is set _and_ a regex is set, then we need to check both
  201. // so if the path does not match, then we should return early and not
  202. // consider the regex
  203. if !rule.Path.MatchString(fragment.FilePath) {
  204. return findings
  205. }
  206. }
  207. // if path only rule, skip content checks
  208. if rule.Regex == nil {
  209. return findings
  210. }
  211. // If flag configure and raw data size bigger then the flag
  212. if d.MaxTargetMegaBytes > 0 {
  213. rawLength := len(fragment.Raw) / 1000000
  214. if rawLength > d.MaxTargetMegaBytes {
  215. log.Debug().Msgf("skipping file: %s scan due to size: %d", fragment.FilePath, rawLength)
  216. return findings
  217. }
  218. }
  219. matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
  220. for _, matchIndex := range matchIndices {
  221. // extract secret from match
  222. secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
  223. // Fixes: https://github.com/gitleaks/gitleaks/issues/1352
  224. // removes the incorrectly following line that was detected by regex expression '\n'
  225. matchIndex[1] = matchIndex[0] + len(secret)
  226. // determine location of match. Note that the location
  227. // in the finding will be the line/column numbers of the _match_
  228. // not the _secret_, which will be different if the secretGroup
  229. // value is set for this rule
  230. loc := location(fragment, matchIndex)
  231. if matchIndex[1] > loc.endLineIndex {
  232. loc.endLineIndex = matchIndex[1]
  233. }
  234. finding := report.Finding{
  235. Description: rule.Description,
  236. File: fragment.FilePath,
  237. SymlinkFile: fragment.SymlinkFile,
  238. RuleID: rule.RuleID,
  239. StartLine: loc.startLine,
  240. EndLine: loc.endLine,
  241. StartColumn: loc.startColumn,
  242. EndColumn: loc.endColumn,
  243. Secret: secret,
  244. Match: secret,
  245. Tags: rule.Tags,
  246. Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
  247. }
  248. if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
  249. gitleaksAllowSignature) && !d.IgnoreGitleaksAllow {
  250. continue
  251. }
  252. // Set the value of |secret|, if the pattern contains at least one capture group.
  253. // (The first element is the full match, hence we check >= 2.)
  254. groups := rule.Regex.FindStringSubmatch(finding.Secret)
  255. if len(groups) >= 2 {
  256. if rule.SecretGroup > 0 {
  257. if len(groups) <= rule.SecretGroup {
  258. // Config validation should prevent this
  259. continue
  260. }
  261. finding.Secret = groups[rule.SecretGroup]
  262. } else {
  263. // If |secretGroup| is not set, we will use the first suitable capture group.
  264. if len(groups) == 2 {
  265. // Use the only group.
  266. finding.Secret = groups[1]
  267. } else {
  268. // Use the first non-empty group.
  269. for _, s := range groups[1:] {
  270. if len(s) > 0 {
  271. finding.Secret = s
  272. break
  273. }
  274. }
  275. }
  276. }
  277. }
  278. // check if the regexTarget is defined in the allowlist "regexes" entry
  279. allowlistTarget := finding.Secret
  280. switch rule.Allowlist.RegexTarget {
  281. case "match":
  282. allowlistTarget = finding.Match
  283. case "line":
  284. allowlistTarget = finding.Line
  285. }
  286. globalAllowlistTarget := finding.Secret
  287. switch d.Config.Allowlist.RegexTarget {
  288. case "match":
  289. globalAllowlistTarget = finding.Match
  290. case "line":
  291. globalAllowlistTarget = finding.Line
  292. }
  293. if rule.Allowlist.RegexAllowed(allowlistTarget) ||
  294. d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
  295. continue
  296. }
  297. // check if the secret is in the list of stopwords
  298. if rule.Allowlist.ContainsStopWord(finding.Secret) ||
  299. d.Config.Allowlist.ContainsStopWord(finding.Secret) {
  300. continue
  301. }
  302. // check entropy
  303. entropy := shannonEntropy(finding.Secret)
  304. finding.Entropy = float32(entropy)
  305. if rule.Entropy != 0.0 {
  306. if entropy <= rule.Entropy {
  307. // entropy is too low, skip this finding
  308. continue
  309. }
  310. // NOTE: this is a goofy hack to get around the fact there golang's regex engine
  311. // does not support positive lookaheads. Ideally we would want to add a
  312. // restriction on generic rules regex that requires the secret match group
  313. // contains both numbers and alphabetical characters, not just alphabetical characters.
  314. // What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
  315. // secret contains both digits and alphabetical characters.
  316. // TODO: this should be replaced with stop words
  317. if strings.HasPrefix(rule.RuleID, "generic") {
  318. if !containsDigit(finding.Secret) {
  319. continue
  320. }
  321. }
  322. }
  323. findings = append(findings, finding)
  324. }
  325. return findings
  326. }
  327. // addFinding synchronously adds a finding to the findings slice
  328. func (d *Detector) addFinding(finding report.Finding) {
  329. globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine)
  330. if finding.Commit != "" {
  331. finding.Fingerprint = fmt.Sprintf("%s:%s:%s:%d", finding.Commit, finding.File, finding.RuleID, finding.StartLine)
  332. } else {
  333. finding.Fingerprint = globalFingerprint
  334. }
  335. // check if we should ignore this finding
  336. if _, ok := d.gitleaksIgnore[globalFingerprint]; ok {
  337. log.Debug().Msgf("ignoring finding with global Fingerprint %s",
  338. finding.Fingerprint)
  339. return
  340. } else if finding.Commit != "" {
  341. // Awkward nested if because I'm not sure how to chain these two conditions.
  342. if _, ok := d.gitleaksIgnore[finding.Fingerprint]; ok {
  343. log.Debug().Msgf("ignoring finding with Fingerprint %s",
  344. finding.Fingerprint)
  345. return
  346. }
  347. }
  348. if d.baseline != nil && !IsNew(finding, d.baseline) {
  349. log.Debug().Msgf("baseline duplicate -- ignoring finding with Fingerprint %s", finding.Fingerprint)
  350. return
  351. }
  352. d.findingMutex.Lock()
  353. d.findings = append(d.findings, finding)
  354. if d.Verbose {
  355. printFinding(finding, d.NoColor)
  356. }
  357. d.findingMutex.Unlock()
  358. }
  359. // addCommit synchronously adds a commit to the commit slice
  360. func (d *Detector) addCommit(commit string) {
  361. d.commitMap[commit] = true
  362. }