util.go 10 KB

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