util.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package audit
  2. import (
  3. "fmt"
  4. log "github.com/sirupsen/logrus"
  5. "github.com/zricethezav/gitleaks-ng/config"
  6. "github.com/zricethezav/gitleaks-ng/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. // InspectString accepts a string, commit object, repo, and filename. This function iterates over
  92. // all the rules set by the gitleaks config. If the rule contains entropy checks then entropy will be checked first.
  93. // Next, if the rule contains a regular expression then that will be checked.
  94. func InspectString(content string, c *object.Commit, repo *Repo, filename string) {
  95. for _, rule := range repo.config.Rules {
  96. // check entropy
  97. if len(rule.Entropy) != 0 {
  98. // TODO
  99. // an optimization would be to switch the regex from FindAllIndex to FindString
  100. // since we are iterating on the lines if entropy rules exist...
  101. for _, line := range strings.Split(content, "\n") {
  102. if trippedEntropy(line, rule) {
  103. _line := line
  104. if len(_line) > maxLineLen {
  105. _line = line[0 : maxLineLen-1]
  106. }
  107. repo.Manager.SendLeaks(manager.Leak{
  108. Line: _line,
  109. Offender: fmt.Sprintf("Entropy range %+v", rule.Entropy),
  110. Commit: c.Hash.String(),
  111. Repo: repo.Name,
  112. Message: c.Message,
  113. Rule: rule.Description,
  114. Author: c.Author.Name,
  115. Email: c.Author.Email,
  116. Date: c.Author.When,
  117. Tags: strings.Join(rule.Tags, ", "),
  118. File: filename,
  119. })
  120. }
  121. }
  122. }
  123. if rule.Regex.String() == "" {
  124. continue
  125. }
  126. start := time.Now()
  127. locs := rule.Regex.FindAllIndex([]byte(content), -1)
  128. if len(locs) != 0 {
  129. // check if any rules are whitelisting this leak
  130. if len(rule.Whitelist) != 0 {
  131. for _, wl := range rule.Whitelist {
  132. if fileMatched(filename, wl.File) {
  133. // if matched, go to next rule
  134. goto NEXT
  135. }
  136. }
  137. }
  138. for _, loc := range locs {
  139. start := loc[0]
  140. end := loc[1]
  141. for start != 0 && content[start] != '\n' {
  142. start = start - 1
  143. }
  144. if start != 0 {
  145. // skip newline
  146. start = start + 1
  147. }
  148. for end < len(content)-1 && content[end] != '\n' {
  149. end = end + 1
  150. }
  151. offender := content[loc[0]:loc[1]]
  152. line := content[start:end]
  153. if repo.Manager.Opts.Redact {
  154. line = strings.ReplaceAll(line, offender, "REDACTED")
  155. offender = "REDACTED"
  156. }
  157. repo.Manager.SendLeaks(manager.Leak{
  158. Line: line,
  159. Offender: offender,
  160. Commit: c.Hash.String(),
  161. Message: c.Message,
  162. Repo: repo.Name,
  163. Rule: rule.Description,
  164. Author: c.Author.Name,
  165. Email: c.Author.Email,
  166. Date: c.Author.When,
  167. Tags: strings.Join(rule.Tags, ", "),
  168. File: filename,
  169. })
  170. }
  171. }
  172. repo.Manager.RecordTime(manager.RegexTime{
  173. Time: time.Now().Sub(start).Nanoseconds(),
  174. Regex: rule.Regex.String(),
  175. })
  176. NEXT:
  177. }
  178. }
  179. // inspectCommit accepts a commit object and a repo. This function is only called when the --commit=
  180. // option has been set. That option tells gitleaks to look only at a single commit and check the contents
  181. // of said commit. Similar to inspectPatch(), if the files contained in the commit are a binaries or if they are
  182. // whitelisted then those files will be skipped.
  183. func inspectCommit(c *object.Commit, repo *Repo) error {
  184. fIter, err := c.Files()
  185. if err != nil {
  186. return err
  187. }
  188. err = fIter.ForEach(func(f *object.File) error {
  189. bin, err := f.IsBinary()
  190. if bin {
  191. return nil
  192. } else if err != nil {
  193. return err
  194. }
  195. if fileMatched(f, repo.config.Whitelist.File) {
  196. log.Debugf("whitelisted file found, skipping audit of file: %s", f.Name)
  197. return nil
  198. }
  199. content, err := f.Contents()
  200. if err != nil {
  201. return err
  202. }
  203. InspectString(content, c, repo, f.Name)
  204. return nil
  205. })
  206. return err
  207. }
  208. // howManyThreads will return a number 1-GOMAXPROCS which is the number
  209. // of goroutines that will spawn during gitleaks execution
  210. func howManyThreads(threads int) int {
  211. maxThreads := runtime.GOMAXPROCS(0)
  212. if threads == 0 {
  213. return 1
  214. } else if threads > maxThreads {
  215. log.Warnf("%d threads set too high, setting to system max, %d", threads, maxThreads)
  216. return maxThreads
  217. }
  218. return threads
  219. }
  220. func isCommitWhiteListed(commitHash string, whitelistedCommits []string) bool {
  221. for _, hash := range whitelistedCommits {
  222. if commitHash == hash {
  223. return true
  224. }
  225. }
  226. return false
  227. }
  228. func fileMatched(f interface{}, re *regexp.Regexp) bool {
  229. if re == nil {
  230. return false
  231. }
  232. switch f.(type) {
  233. case nil:
  234. return false
  235. case string:
  236. if re.FindString(f.(string)) != "" {
  237. return true
  238. }
  239. return false
  240. case *object.File:
  241. if re.FindString(f.(*object.File).Name) != "" {
  242. return true
  243. }
  244. return false
  245. }
  246. return false
  247. }
  248. // getLogOptions determines what log options are used when iterating through commits.
  249. // It is similar to `git log {branch}`. Default behavior is to log ALL branches so
  250. // gitleaks gets the full git history.
  251. func getLogOptions(repo *Repo) (*git.LogOptions, error) {
  252. if repo.Manager.Opts.Branch != "" {
  253. var logOpts git.LogOptions
  254. refs, err := repo.Storer.IterReferences()
  255. if err != nil {
  256. return nil, err
  257. }
  258. err = refs.ForEach(func(ref *plumbing.Reference) error {
  259. if ref.Name().IsTag() {
  260. return nil
  261. }
  262. // check heads first
  263. if ref.Name().String() == "refs/heads/"+repo.Manager.Opts.Branch {
  264. logOpts = git.LogOptions{
  265. From: ref.Hash(),
  266. }
  267. return nil
  268. } else if ref.Name().String() == "refs/remotes/origin/"+repo.Manager.Opts.Branch {
  269. logOpts = git.LogOptions{
  270. From: ref.Hash(),
  271. }
  272. return nil
  273. }
  274. return nil
  275. })
  276. if logOpts.From.IsZero() {
  277. return nil, fmt.Errorf("could not find branch %s", repo.Manager.Opts.Branch)
  278. }
  279. return &logOpts, nil
  280. }
  281. return &git.LogOptions{All: true}, nil
  282. }
  283. // howLong accepts a time.Time object which is subtracted from time.Now() and
  284. // converted to nanoseconds which is returned
  285. func howLong(t time.Time) int64 {
  286. return time.Now().Sub(t).Nanoseconds()
  287. }