util.go 9.5 KB

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