util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. package audit
  2. import (
  3. "fmt"
  4. "math"
  5. "regexp"
  6. "runtime"
  7. "strings"
  8. "time"
  9. "github.com/zricethezav/gitleaks/v3/config"
  10. "github.com/zricethezav/gitleaks/v3/manager"
  11. log "github.com/sirupsen/logrus"
  12. "gopkg.in/src-d/go-git.v4"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. fdiff "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
  15. "gopkg.in/src-d/go-git.v4/plumbing/object"
  16. )
  17. // Inspect patch accepts a patch, commit, and repo. If the patches contains files that are
  18. // binary, then gitleaks will skip auditing that file OR if a file is matched on
  19. // whitelisted files set in the configuration. If a global rule for files is defined and a filename
  20. // matches said global rule, then a leak is sent to the manager.
  21. // After that, file chunks are created which are then inspected by InspectString()
  22. func inspectPatch(patch *object.Patch, c *object.Commit, repo *Repo) {
  23. for _, f := range patch.FilePatches() {
  24. if repo.timeoutReached() {
  25. return
  26. }
  27. if f.IsBinary() {
  28. continue
  29. }
  30. if fileMatched(getFileName(f), repo.config.Whitelist.File) {
  31. log.Debugf("whitelisted file found, skipping audit of file: %s", getFileName(f))
  32. continue
  33. }
  34. if fileMatched(getFileName(f), repo.config.FileRegex) {
  35. repo.Manager.SendLeaks(manager.Leak{
  36. Line: "N/A",
  37. Offender: getFileName(f),
  38. Commit: c.Hash.String(),
  39. Repo: repo.Name,
  40. Rule: "file regex matched" + repo.config.FileRegex.String(),
  41. Author: c.Author.Name,
  42. Email: c.Author.Email,
  43. Date: c.Author.When,
  44. File: getFileName(f),
  45. })
  46. }
  47. for _, chunk := range f.Chunks() {
  48. if chunk.Type() == fdiff.Delete || chunk.Type() == fdiff.Add {
  49. InspectString(chunk.Content(), c, repo, getFileName(f))
  50. }
  51. }
  52. }
  53. }
  54. // getFileName accepts a file patch and returns the filename
  55. func getFileName(f fdiff.FilePatch) string {
  56. fn := "???"
  57. from, to := f.Files()
  58. if from != nil {
  59. return from.Path()
  60. } else if to != nil {
  61. return to.Path()
  62. }
  63. return fn
  64. }
  65. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  66. func shannonEntropy(data string) (entropy float64) {
  67. if data == "" {
  68. return 0
  69. }
  70. charCounts := make(map[rune]int)
  71. for _, char := range data {
  72. charCounts[char]++
  73. }
  74. invLength := 1.0 / float64(len(data))
  75. for _, count := range charCounts {
  76. freq := float64(count) * invLength
  77. entropy -= freq * math.Log2(freq)
  78. }
  79. return entropy
  80. }
  81. // aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
  82. // trippedEntropy checks if a given line falls in between entropy ranges supplied
  83. // by a custom gitleaks configuration. Gitleaks do not check entropy by default.
  84. func trippedEntropy(line string, rule config.Rule) bool {
  85. for _, e := range rule.Entropy {
  86. entropy := shannonEntropy(line)
  87. if entropy > e.P1 && entropy < e.P2 {
  88. return true
  89. }
  90. }
  91. return false
  92. }
  93. func ruleContainRegex(rule config.Rule) bool {
  94. if rule.Regex == nil {
  95. return false
  96. }
  97. if rule.Regex.String() == "" {
  98. return false
  99. }
  100. return true
  101. }
  102. // InspectString accepts a string, commit object, repo, and filename. This function iterates over
  103. // all the rules set by the gitleaks config. If the rule contains entropy checks then entropy will be checked first.
  104. // Next, if the rule contains a regular expression then that will be checked.
  105. func InspectString(content string, c *object.Commit, repo *Repo, filename string) {
  106. for _, rule := range repo.config.Rules {
  107. // check entropy
  108. if len(rule.Entropy) != 0 {
  109. // an optimization would be to switch the regex from FindAllIndex to FindString
  110. // since we are iterating on the lines if entropy rules exist...
  111. for _, line := range strings.Split(content, "\n") {
  112. if repo.timeoutReached() {
  113. return
  114. }
  115. entropyTripped := trippedEntropy(line, rule)
  116. if entropyTripped && !ruleContainRegex(rule) {
  117. repo.Manager.SendLeaks(manager.Leak{
  118. Line: line,
  119. Offender: fmt.Sprintf("Entropy range %+v", rule.Entropy),
  120. Commit: c.Hash.String(),
  121. Repo: repo.Name,
  122. Message: c.Message,
  123. Rule: rule.Description,
  124. Author: c.Author.Name,
  125. Email: c.Author.Email,
  126. Date: c.Author.When,
  127. Tags: strings.Join(rule.Tags, ", "),
  128. File: filename,
  129. })
  130. } else if entropyTripped {
  131. if repo.timeoutReached() {
  132. return
  133. }
  134. // entropy has been tripped which means if there is a regex specified in the same
  135. // rule, we need to inspect the line for a regex match. In otherwords, the current rule has
  136. // both entropy and regex set which work in combination. This helps narrow down false positives
  137. // on searches for generic passwords in code.
  138. match := rule.Regex.FindString(line)
  139. // check if any rules are whitelisting this leak
  140. if len(rule.Whitelist) != 0 {
  141. for _, wl := range rule.Whitelist {
  142. if fileMatched(filename, wl.File) {
  143. // if matched, go to next rule
  144. goto NEXTLINE
  145. }
  146. if wl.Regex.FindString(line) != "" {
  147. goto NEXTLINE
  148. }
  149. }
  150. }
  151. if match != "" {
  152. // both the regex and entropy in this rule have been tripped which means this line
  153. // contains a leak
  154. repo.Manager.SendLeaks(manager.Leak{
  155. Line: line,
  156. Offender: match,
  157. Commit: c.Hash.String(),
  158. Message: c.Message,
  159. Repo: repo.Name,
  160. Rule: rule.Description,
  161. Author: c.Author.Name,
  162. Email: c.Author.Email,
  163. Date: c.Author.When,
  164. Tags: strings.Join(rule.Tags, ", "),
  165. File: filename,
  166. })
  167. }
  168. }
  169. NEXTLINE:
  170. }
  171. return
  172. }
  173. if rule.Regex.String() == "" {
  174. continue
  175. }
  176. if repo.timeoutReached() {
  177. return
  178. }
  179. start := time.Now()
  180. locs := rule.Regex.FindAllIndex([]byte(content), -1)
  181. if len(locs) != 0 {
  182. // check if any rules are whitelisting this leak
  183. if len(rule.Whitelist) != 0 {
  184. for _, wl := range rule.Whitelist {
  185. if fileMatched(filename, wl.File) {
  186. // if matched, go to next rule
  187. goto NEXT
  188. }
  189. }
  190. }
  191. for _, loc := range locs {
  192. start := loc[0]
  193. end := loc[1]
  194. for start != 0 && content[start] != '\n' {
  195. start = start - 1
  196. }
  197. if start != 0 {
  198. // skip newline
  199. start = start + 1
  200. }
  201. for end < len(content)-1 && content[end] != '\n' {
  202. end = end + 1
  203. }
  204. offender := content[loc[0]:loc[1]]
  205. line := content[start:end]
  206. if len(rule.Whitelist) != 0 {
  207. for _, wl := range rule.Whitelist {
  208. if wl.Regex.FindString(line) != "" {
  209. goto NEXT
  210. }
  211. }
  212. }
  213. if repo.Manager.Opts.Redact {
  214. line = strings.ReplaceAll(line, offender, "REDACTED")
  215. offender = "REDACTED"
  216. }
  217. repo.Manager.SendLeaks(manager.Leak{
  218. Line: line,
  219. Offender: offender,
  220. Commit: c.Hash.String(),
  221. Message: c.Message,
  222. Repo: repo.Name,
  223. Rule: rule.Description,
  224. Author: c.Author.Name,
  225. Email: c.Author.Email,
  226. Date: c.Author.When,
  227. Tags: strings.Join(rule.Tags, ", "),
  228. File: filename,
  229. })
  230. }
  231. }
  232. repo.Manager.RecordTime(manager.RegexTime{
  233. Time: time.Now().Sub(start).Nanoseconds(),
  234. Regex: rule.Regex.String(),
  235. })
  236. NEXT:
  237. }
  238. }
  239. // inspectCommit accepts a commit object and a repo. This function is only called when the --commit=
  240. // option has been set. That option tells gitleaks to look only at a single commit and check the contents
  241. // of said commit. Similar to inspectPatch(), if the files contained in the commit are a binaries or if they are
  242. // whitelisted then those files will be skipped.
  243. func inspectCommit(c *object.Commit, repo *Repo) error {
  244. fIter, err := c.Files()
  245. if err != nil {
  246. return err
  247. }
  248. err = fIter.ForEach(func(f *object.File) error {
  249. bin, err := f.IsBinary()
  250. if bin || repo.timeoutReached() {
  251. return nil
  252. } else if err != nil {
  253. return err
  254. }
  255. if fileMatched(f, repo.config.Whitelist.File) {
  256. log.Debugf("whitelisted file found, skipping audit of file: %s", f.Name)
  257. return nil
  258. }
  259. if fileMatched(f.Name, repo.config.FileRegex) {
  260. repo.Manager.SendLeaks(manager.Leak{
  261. Line: "N/A",
  262. Offender: f.Name,
  263. Commit: c.Hash.String(),
  264. Repo: repo.Name,
  265. Rule: "file regex matched" + repo.config.FileRegex.String(),
  266. Author: c.Author.Name,
  267. Email: c.Author.Email,
  268. Date: c.Author.When,
  269. File: f.Name,
  270. })
  271. }
  272. content, err := f.Contents()
  273. if err != nil {
  274. return err
  275. }
  276. InspectString(content, c, repo, f.Name)
  277. return nil
  278. })
  279. return err
  280. }
  281. // howManyThreads will return a number 1-GOMAXPROCS which is the number
  282. // of goroutines that will spawn during gitleaks execution
  283. func howManyThreads(threads int) int {
  284. maxThreads := runtime.GOMAXPROCS(0)
  285. if threads == 0 {
  286. return 1
  287. } else if threads > maxThreads {
  288. log.Warnf("%d threads set too high, setting to system max, %d", threads, maxThreads)
  289. return maxThreads
  290. }
  291. return threads
  292. }
  293. func isCommitWhiteListed(commitHash string, whitelistedCommits []string) bool {
  294. for _, hash := range whitelistedCommits {
  295. if commitHash == hash {
  296. return true
  297. }
  298. }
  299. return false
  300. }
  301. func fileMatched(f interface{}, re *regexp.Regexp) bool {
  302. if re == nil {
  303. return false
  304. }
  305. switch f.(type) {
  306. case nil:
  307. return false
  308. case string:
  309. if re.FindString(f.(string)) != "" {
  310. return true
  311. }
  312. return false
  313. case *object.File:
  314. if re.FindString(f.(*object.File).Name) != "" {
  315. return true
  316. }
  317. return false
  318. }
  319. return false
  320. }
  321. // getLogOptions determines what log options are used when iterating through commits.
  322. // It is similar to `git log {branch}`. Default behavior is to log ALL branches so
  323. // gitleaks gets the full git history.
  324. func getLogOptions(repo *Repo) (*git.LogOptions, error) {
  325. var logOpts git.LogOptions
  326. if repo.Manager.Opts.CommitFrom != "" {
  327. logOpts.From = plumbing.NewHash(repo.Manager.Opts.CommitFrom)
  328. }
  329. if repo.Manager.Opts.Branch != "" {
  330. refs, err := repo.Storer.IterReferences()
  331. if err != nil {
  332. return nil, err
  333. }
  334. err = refs.ForEach(func(ref *plumbing.Reference) error {
  335. if ref.Name().IsTag() {
  336. return nil
  337. }
  338. // check heads first
  339. if ref.Name().String() == "refs/heads/"+repo.Manager.Opts.Branch {
  340. logOpts = git.LogOptions{
  341. From: ref.Hash(),
  342. }
  343. return nil
  344. } else if ref.Name().String() == "refs/remotes/origin/"+repo.Manager.Opts.Branch {
  345. logOpts = git.LogOptions{
  346. From: ref.Hash(),
  347. }
  348. return nil
  349. }
  350. return nil
  351. })
  352. if logOpts.From.IsZero() {
  353. return nil, fmt.Errorf("could not find branch %s", repo.Manager.Opts.Branch)
  354. }
  355. return &logOpts, nil
  356. }
  357. if !logOpts.From.IsZero() {
  358. return &logOpts, nil
  359. }
  360. return &git.LogOptions{All: true}, nil
  361. }
  362. // howLong accepts a time.Time object which is subtracted from time.Now() and
  363. // converted to nanoseconds which is returned
  364. func howLong(t time.Time) int64 {
  365. return time.Now().Sub(t).Nanoseconds()
  366. }