main.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/csv"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "math"
  9. "net"
  10. "net/url"
  11. "os"
  12. "os/user"
  13. "path"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "gopkg.in/src-d/go-git.v4/plumbing"
  22. diffType "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
  23. "gopkg.in/src-d/go-git.v4/plumbing/object"
  24. "gopkg.in/src-d/go-git.v4/plumbing/storer"
  25. "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
  26. "gopkg.in/src-d/go-git.v4/storage/memory"
  27. "github.com/BurntSushi/toml"
  28. "github.com/google/go-github/github"
  29. "github.com/hako/durafmt"
  30. "github.com/jessevdk/go-flags"
  31. log "github.com/sirupsen/logrus"
  32. "gopkg.in/src-d/go-git.v4"
  33. )
  34. // Leak represents a leaked secret or regex match.
  35. type Leak struct {
  36. Line string `json:"line"`
  37. Commit string `json:"commit"`
  38. Offender string `json:"offender"`
  39. Type string `json:"reason"`
  40. Message string `json:"commitMsg"`
  41. Author string `json:"author"`
  42. File string `json:"file"`
  43. Repo string `json:"repo"`
  44. Date time.Time `json:"date"`
  45. }
  46. // RepoDescriptor contains a src-d git repository and other data about the repo
  47. type RepoDescriptor struct {
  48. path string
  49. url string
  50. name string
  51. repository *git.Repository
  52. err error
  53. }
  54. // Options for gitleaks
  55. type Options struct {
  56. // remote target options
  57. Repo string `short:"r" long:"repo" description:"Repo url to audit"`
  58. GithubUser string `long:"github-user" description:"Github user to audit"`
  59. GithubOrg string `long:"github-org" description:"Github organization to audit"`
  60. GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"`
  61. GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
  62. GitLabUser string `long:"gitlab-user" description:"GitLab user ID to audit"`
  63. GitLabOrg string `long:"gitlab-org" description:"GitLab group ID to audit"`
  64. CommitStop string `long:"commit-stop" description:"sha of commit to stop at"`
  65. Commit string `long:"commit" description:"sha of commit to investigate"`
  66. Depth int64 `long:"depth" description:"maximum commit depth"`
  67. // local target option
  68. RepoPath string `long:"repo-path" description:"Path to repo"`
  69. OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
  70. // Process options
  71. Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
  72. Disk bool `long:"disk" description:"Clones repo(s) to disk"`
  73. SingleSearch string `long:"single-search" description:"single regular expression to search for"`
  74. ConfigPath string `long:"config" description:"path to gitleaks config"`
  75. SSHKey string `long:"ssh-key" description:"path to ssh key"`
  76. ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
  77. Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
  78. NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"`
  79. RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""`
  80. // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
  81. // Output options
  82. Log string `short:"l" long:"log" description:"log level"`
  83. Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
  84. Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
  85. Redact bool `long:"redact" description:"redact secrets from log messages and report"`
  86. Version bool `long:"version" description:"version number"`
  87. SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
  88. }
  89. // Config struct for regexes matching and whitelisting
  90. type Config struct {
  91. Regexes []struct {
  92. Description string
  93. Regex string
  94. }
  95. Entropy struct {
  96. LineRegexes []string
  97. }
  98. Whitelist struct {
  99. Files []string
  100. Regexes []string
  101. Commits []string
  102. Repos []string
  103. }
  104. Misc struct {
  105. Entropy []string
  106. }
  107. }
  108. type gitDiff struct {
  109. content string
  110. commit *object.Commit
  111. filePath string
  112. repoName string
  113. githubCommit *github.RepositoryCommit
  114. sha string
  115. message string
  116. author string
  117. date time.Time
  118. }
  119. type entropyRange struct {
  120. v1 float64
  121. v2 float64
  122. }
  123. const defaultGithubURL = "https://api.github.com/"
  124. const version = "1.24.0"
  125. const errExit = 2
  126. const leakExit = 1
  127. const defaultConfig = `
  128. # This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
  129. # The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
  130. # is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
  131. # configurations from that path. Gitleaks does not whitelist anything by default.
  132. title = "gitleaks config"
  133. # add regexes to the regex table
  134. [[regexes]]
  135. description = "AWS"
  136. regex = '''AKIA[0-9A-Z]{16}'''
  137. [[regexes]]
  138. description = "PKCS8"
  139. regex = '''-----BEGIN PRIVATE KEY-----'''
  140. [[regexes]]
  141. description = "RSA"
  142. regex = '''-----BEGIN RSA PRIVATE KEY-----'''
  143. [[regexes]]
  144. description = "SSH"
  145. regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
  146. [[regexes]]
  147. description = "PGP"
  148. regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
  149. [[regexes]]
  150. description = "Facebook"
  151. regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]'''
  152. [[regexes]]
  153. description = "Twitter"
  154. regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]'''
  155. [[regexes]]
  156. description = "Github"
  157. regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
  158. [[regexes]]
  159. description = "Slack"
  160. regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
  161. [entropy]
  162. lineregexes = [
  163. "api",
  164. "key",
  165. "signature",
  166. "secret",
  167. "password",
  168. "pass",
  169. "pwd",
  170. "token",
  171. "curl",
  172. "wget",
  173. "https?",
  174. ]
  175. [whitelist]
  176. files = [
  177. "(.*?)(jpg|gif|doc|pdf|bin)$"
  178. ]
  179. #commits = [
  180. # "BADHA5H1",
  181. # "BADHA5H2",
  182. #]
  183. #repos = [
  184. # "mygoodrepo"
  185. #]
  186. [misc]
  187. #entropy = [
  188. # "3.3-4.30"
  189. # "6.0-8.0
  190. #]
  191. `
  192. var (
  193. opts Options
  194. regexes map[string]*regexp.Regexp
  195. singleSearchRegex *regexp.Regexp
  196. whiteListRegexes []*regexp.Regexp
  197. whiteListFiles []*regexp.Regexp
  198. whiteListCommits map[string]bool
  199. whiteListRepos []*regexp.Regexp
  200. entropyRanges []entropyRange
  201. entropyRegexes []*regexp.Regexp
  202. fileDiffRegex *regexp.Regexp
  203. sshAuth *ssh.PublicKeys
  204. dir string
  205. threads int
  206. totalCommits int64
  207. commitMap = make(map[string]bool)
  208. cMutex = &sync.Mutex{}
  209. auditDone bool
  210. )
  211. func init() {
  212. log.SetOutput(os.Stdout)
  213. // threads = runtime.GOMAXPROCS(0) / 2
  214. threads = 1
  215. regexes = make(map[string]*regexp.Regexp)
  216. whiteListCommits = make(map[string]bool)
  217. }
  218. func main() {
  219. parser := flags.NewParser(&opts, flags.Default)
  220. _, err := parser.Parse()
  221. if err != nil {
  222. if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
  223. os.Exit(0)
  224. }
  225. }
  226. if len(os.Args) == 1 {
  227. parser.WriteHelp(os.Stdout)
  228. os.Exit(0)
  229. }
  230. if opts.Version {
  231. fmt.Println(version)
  232. os.Exit(0)
  233. }
  234. if opts.SampleConfig {
  235. fmt.Println(defaultConfig)
  236. os.Exit(0)
  237. }
  238. now := time.Now()
  239. leaks, err := run()
  240. if err != nil {
  241. if strings.Contains(err.Error(), "whitelisted") {
  242. log.Info(err.Error())
  243. os.Exit(0)
  244. }
  245. log.Error(err)
  246. os.Exit(errExit)
  247. }
  248. if opts.Report != "" {
  249. writeReport(leaks)
  250. }
  251. if len(leaks) != 0 {
  252. log.Warnf("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
  253. os.Exit(leakExit)
  254. } else {
  255. log.Infof("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
  256. }
  257. }
  258. // run parses options and kicks off the audit
  259. func run() ([]Leak, error) {
  260. var leaks []Leak
  261. setLogs()
  262. err := optsGuard()
  263. if err != nil {
  264. return nil, err
  265. }
  266. err = loadToml()
  267. if err != nil {
  268. return nil, err
  269. }
  270. sshAuth, err = getSSHAuth()
  271. if err != nil {
  272. return leaks, err
  273. }
  274. if opts.Disk {
  275. // temporary directory where all the gitleaks plain clones will reside
  276. dir, err = ioutil.TempDir("", "gitleaks")
  277. defer os.RemoveAll(dir)
  278. if err != nil {
  279. return nil, err
  280. }
  281. }
  282. // start audits
  283. if opts.Repo != "" || opts.RepoPath != "" {
  284. // Audit a single remote repo or a local repo.
  285. repo, err := cloneRepo()
  286. if err != nil {
  287. return leaks, err
  288. }
  289. return auditGitRepo(repo)
  290. } else if opts.OwnerPath != "" {
  291. // Audit local repos. Gitleaks will look for all child directories of OwnerPath for
  292. // git repos and perform an audit on said repos.
  293. repos, err := discoverRepos(opts.OwnerPath)
  294. if err != nil {
  295. return leaks, err
  296. }
  297. for _, repo := range repos {
  298. leaksFromRepo, err := auditGitRepo(repo)
  299. if err != nil {
  300. return leaks, err
  301. }
  302. leaks = append(leaksFromRepo, leaks...)
  303. }
  304. } else if opts.GithubOrg != "" || opts.GithubUser != "" {
  305. // Audit a github owner -- a user or organization.
  306. leaks, err = auditGithubRepos()
  307. if err != nil {
  308. return leaks, err
  309. }
  310. } else if opts.GitLabOrg != "" || opts.GitLabUser != "" {
  311. leaks, err = auditGitlabRepos()
  312. if err != nil {
  313. return leaks, err
  314. }
  315. } else if opts.GithubPR != "" {
  316. return auditGithubPR()
  317. }
  318. return leaks, nil
  319. }
  320. // writeReport writes a report to a file specified in the --report= option.
  321. // Default format for report is JSON. You can use the --csv option to write the report as a csv
  322. func writeReport(leaks []Leak) error {
  323. if len(leaks) == 0 {
  324. return nil
  325. }
  326. var err error
  327. log.Infof("writing report to %s", opts.Report)
  328. if strings.HasSuffix(opts.Report, ".csv") {
  329. f, err := os.Create(opts.Report)
  330. if err != nil {
  331. return err
  332. }
  333. defer f.Close()
  334. w := csv.NewWriter(f)
  335. w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "date"})
  336. for _, leak := range leaks {
  337. w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Date.Format(time.RFC3339)})
  338. }
  339. w.Flush()
  340. } else {
  341. var (
  342. f *os.File
  343. encoder *json.Encoder
  344. )
  345. f, err := os.Create(opts.Report)
  346. if err != nil {
  347. return err
  348. }
  349. defer f.Close()
  350. encoder = json.NewEncoder(f)
  351. encoder.SetIndent("", "\t")
  352. if _, err := f.WriteString("[\n"); err != nil {
  353. return err
  354. }
  355. for i := 0; i < len(leaks); i++ {
  356. if err := encoder.Encode(leaks[i]); err != nil {
  357. return err
  358. }
  359. // for all but the last leak, seek back and overwrite the newline appended by Encode() with comma & newline
  360. if i+1 < len(leaks) {
  361. if _, err := f.Seek(-1, 1); err != nil {
  362. return err
  363. }
  364. if _, err := f.WriteString(",\n"); err != nil {
  365. return err
  366. }
  367. }
  368. }
  369. if _, err := f.WriteString("]"); err != nil {
  370. return err
  371. }
  372. if err := f.Sync(); err != nil {
  373. log.Error(err)
  374. return err
  375. }
  376. }
  377. return err
  378. }
  379. // cloneRepo clones a repo to memory(default) or to disk if the --disk option is set.
  380. func cloneRepo() (*RepoDescriptor, error) {
  381. var (
  382. err error
  383. repo *git.Repository
  384. )
  385. // check if whitelist
  386. for _, re := range whiteListRepos {
  387. if re.FindString(opts.Repo) != "" {
  388. return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
  389. }
  390. }
  391. if opts.Disk {
  392. log.Infof("cloning %s", opts.Repo)
  393. cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
  394. if strings.HasPrefix(opts.Repo, "git") {
  395. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  396. URL: opts.Repo,
  397. Progress: os.Stdout,
  398. Auth: sshAuth,
  399. })
  400. } else {
  401. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  402. URL: opts.Repo,
  403. Progress: os.Stdout,
  404. })
  405. }
  406. } else if opts.RepoPath != "" {
  407. log.Infof("opening %s", opts.RepoPath)
  408. repo, err = git.PlainOpen(opts.RepoPath)
  409. } else {
  410. log.Infof("cloning %s", opts.Repo)
  411. if strings.HasPrefix(opts.Repo, "git") {
  412. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  413. URL: opts.Repo,
  414. Progress: os.Stdout,
  415. Auth: sshAuth,
  416. })
  417. } else {
  418. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  419. URL: opts.Repo,
  420. Progress: os.Stdout,
  421. })
  422. }
  423. }
  424. return &RepoDescriptor{
  425. repository: repo,
  426. path: opts.RepoPath,
  427. url: opts.Repo,
  428. name: filepath.Base(opts.Repo),
  429. err: err,
  430. }, nil
  431. }
  432. // auditGitRepo beings an audit on a git repository
  433. func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
  434. var (
  435. err error
  436. leaks []Leak
  437. )
  438. for _, re := range whiteListRepos {
  439. if re.FindString(repo.name) != "" {
  440. return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
  441. }
  442. }
  443. // check if target contains an external gitleaks toml
  444. if opts.RepoConfig {
  445. err := externalConfig(repo)
  446. if err != nil {
  447. return leaks, nil
  448. }
  449. }
  450. // clear commit cache
  451. commitMap = make(map[string]bool)
  452. refs, err := repo.repository.Storer.IterReferences()
  453. if err != nil {
  454. return leaks, err
  455. }
  456. err = refs.ForEach(func(ref *plumbing.Reference) error {
  457. fmt.Println(ref.Name())
  458. if ref.Name().IsTag() {
  459. return nil
  460. }
  461. branchLeaks := auditGitReference(repo, ref)
  462. for _, leak := range branchLeaks {
  463. leaks = append(leaks, leak)
  464. }
  465. return nil
  466. })
  467. return leaks, err
  468. }
  469. // auditGitReference beings the audit for a git reference. This function will
  470. // traverse the git reference and audit each line of each diff.
  471. func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
  472. var (
  473. err error
  474. repoName string
  475. leaks []Leak
  476. commitCount int64
  477. commitWg sync.WaitGroup
  478. mutex = &sync.Mutex{}
  479. semaphore chan bool
  480. )
  481. if auditDone {
  482. return nil
  483. }
  484. repoName = repo.name
  485. if opts.Threads != 0 {
  486. threads = opts.Threads
  487. }
  488. if opts.RepoPath != "" {
  489. threads = 1
  490. }
  491. semaphore = make(chan bool, threads)
  492. cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
  493. if err != nil {
  494. return nil
  495. }
  496. err = cIter.ForEach(func(c *object.Commit) error {
  497. if c == nil || (opts.Depth != 0 && commitCount == opts.Depth) || auditDone {
  498. if commitCount == opts.Depth {
  499. auditDone = true
  500. }
  501. return storer.ErrStop
  502. }
  503. commitCount = commitCount + 1
  504. if whiteListCommits[c.Hash.String()] {
  505. log.Infof("skipping commit: %s\n", c.Hash.String())
  506. return nil
  507. }
  508. // commits w/o parent (root of git the git ref) or option for single commit is not empty str
  509. if len(c.ParentHashes) == 0 || opts.Commit == c.Hash.String() {
  510. if commitMap[c.Hash.String()] {
  511. return nil
  512. }
  513. if opts.Commit == c.Hash.String() {
  514. auditDone = true
  515. }
  516. cMutex.Lock()
  517. commitMap[c.Hash.String()] = true
  518. cMutex.Unlock()
  519. fmt.Println(c.Hash.String())
  520. totalCommits = totalCommits + 1
  521. fIter, err := c.Files()
  522. if err != nil {
  523. return nil
  524. }
  525. err = fIter.ForEach(func(f *object.File) error {
  526. bin, err := f.IsBinary()
  527. if bin || err != nil {
  528. return nil
  529. }
  530. for _, re := range whiteListFiles {
  531. if re.FindString(f.Name) != "" {
  532. log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.Name)
  533. return nil
  534. }
  535. }
  536. content, err := f.Contents()
  537. if err != nil {
  538. return nil
  539. }
  540. diff := gitDiff{
  541. repoName: repoName,
  542. filePath: f.Name,
  543. content: content,
  544. sha: c.Hash.String(),
  545. author: c.Author.String(),
  546. message: strings.Replace(c.Message, "\n", " ", -1),
  547. date: c.Author.When,
  548. }
  549. fileLeaks := inspect(diff)
  550. mutex.Lock()
  551. leaks = append(leaks, fileLeaks...)
  552. mutex.Unlock()
  553. return nil
  554. })
  555. return nil
  556. }
  557. // single commit
  558. if opts.Commit != "" {
  559. return nil
  560. }
  561. skipCount := false
  562. err = c.Parents().ForEach(func(parent *object.Commit) error {
  563. // check if we've seen this diff before
  564. if commitMap[c.Hash.String()+parent.Hash.String()] {
  565. return nil
  566. }
  567. cMutex.Lock()
  568. commitMap[c.Hash.String()+parent.Hash.String()] = true
  569. cMutex.Unlock()
  570. if !skipCount {
  571. totalCommits = totalCommits + 1
  572. skipCount = true
  573. }
  574. commitWg.Add(1)
  575. semaphore <- true
  576. go func(c *object.Commit, parent *object.Commit) {
  577. var (
  578. filePath string
  579. skipFile bool
  580. )
  581. defer func() {
  582. commitWg.Done()
  583. <-semaphore
  584. if r := recover(); r != nil {
  585. log.Warnf("recovering from panic on commit %s, likely large diff causing panic", c.Hash.String())
  586. }
  587. }()
  588. patch, err := c.Patch(parent)
  589. if err != nil {
  590. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  591. return
  592. }
  593. for _, f := range patch.FilePatches() {
  594. if f.IsBinary() {
  595. continue
  596. }
  597. skipFile = false
  598. from, to := f.Files()
  599. filePath = "???"
  600. if from != nil {
  601. filePath = from.Path()
  602. } else if to != nil {
  603. filePath = to.Path()
  604. }
  605. for _, re := range whiteListFiles {
  606. if re.FindString(filePath) != "" {
  607. log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath)
  608. skipFile = true
  609. break
  610. }
  611. }
  612. if skipFile {
  613. continue
  614. }
  615. chunks := f.Chunks()
  616. for _, chunk := range chunks {
  617. if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete {
  618. diff := gitDiff{
  619. repoName: repoName,
  620. filePath: filePath,
  621. content: chunk.Content(),
  622. sha: c.Hash.String(),
  623. author: c.Author.String(),
  624. message: strings.Replace(c.Message, "\n", " ", -1),
  625. date: c.Author.When,
  626. }
  627. chunkLeaks := inspect(diff)
  628. for _, leak := range chunkLeaks {
  629. mutex.Lock()
  630. leaks = append(leaks, leak)
  631. mutex.Unlock()
  632. }
  633. }
  634. }
  635. }
  636. }(c, parent)
  637. return nil
  638. })
  639. // stop audit if we are at commitStop
  640. if c.Hash.String() == opts.CommitStop {
  641. auditDone = true
  642. return storer.ErrStop
  643. }
  644. return nil
  645. })
  646. commitWg.Wait()
  647. return leaks
  648. }
  649. // inspect will parse each line of the git diff's content against a set of regexes or
  650. // a set of regexes set by the config (see gitleaks.toml for example). This function
  651. // will skip lines that include a whitelisted regex. A list of leaks is returned.
  652. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
  653. func inspect(diff gitDiff) []Leak {
  654. var (
  655. leaks []Leak
  656. skipLine bool
  657. )
  658. lines := strings.Split(diff.content, "\n")
  659. for _, line := range lines {
  660. skipLine = false
  661. for leakType, re := range regexes {
  662. match := re.FindString(line)
  663. if match == "" {
  664. continue
  665. }
  666. if skipLine = isLineWhitelisted(line); skipLine {
  667. break
  668. }
  669. leaks = addLeak(leaks, line, match, leakType, diff)
  670. }
  671. if !skipLine && (opts.Entropy > 0 || len(entropyRanges) != 0) {
  672. words := strings.Fields(line)
  673. for _, word := range words {
  674. entropy := getShannonEntropy(word)
  675. // Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type
  676. // was found above, since regex checks are expensive.
  677. if !entropyIsHighEnough(entropy) {
  678. continue
  679. }
  680. // If either the line is whitelisted or the line fails the noiseReduction check (when enabled),
  681. // then we can skip checking the rest of the line for high entropy words.
  682. if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine {
  683. break
  684. }
  685. leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
  686. }
  687. }
  688. }
  689. return leaks
  690. }
  691. // isLineWhitelisted returns true iff the line is matched by at least one of the whiteListRegexes.
  692. func isLineWhitelisted(line string) bool {
  693. for _, wRe := range whiteListRegexes {
  694. whitelistMatch := wRe.FindString(line)
  695. if whitelistMatch != "" {
  696. return true
  697. }
  698. }
  699. return false
  700. }
  701. // addLeak is helper for func inspect() to append leaks if found during a diff check.
  702. func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
  703. leak := Leak{
  704. Line: line,
  705. Commit: diff.sha,
  706. Offender: offender,
  707. Type: leakType,
  708. Author: diff.author,
  709. File: diff.filePath,
  710. Repo: diff.repoName,
  711. Message: diff.message,
  712. Date: diff.date,
  713. }
  714. if opts.Redact {
  715. leak.Offender = "REDACTED"
  716. leak.Line = strings.Replace(line, offender, "REDACTED", -1)
  717. }
  718. if opts.Verbose {
  719. leak.log()
  720. }
  721. leaks = append(leaks, leak)
  722. return leaks
  723. }
  724. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  725. func getShannonEntropy(data string) (entropy float64) {
  726. if data == "" {
  727. return 0
  728. }
  729. charCounts := make(map[rune]int)
  730. for _, char := range data {
  731. charCounts[char]++
  732. }
  733. invLength := 1.0 / float64(len(data))
  734. for _, count := range charCounts {
  735. freq := float64(count) * invLength
  736. entropy -= freq * math.Log2(freq)
  737. }
  738. return entropy
  739. }
  740. func entropyIsHighEnough(entropy float64) bool {
  741. if entropy >= opts.Entropy && len(entropyRanges) == 0 {
  742. return true
  743. }
  744. if len(entropyRanges) != 0 {
  745. for _, eR := range entropyRanges {
  746. if entropy > eR.v1 && entropy < eR.v2 {
  747. return true
  748. }
  749. }
  750. }
  751. return false
  752. }
  753. func highEntropyLineIsALeak(line string) bool {
  754. if !opts.NoiseReduction {
  755. return true
  756. }
  757. for _, re := range entropyRegexes {
  758. if re.FindString(line) != "" {
  759. return true
  760. }
  761. }
  762. return false
  763. }
  764. // discoverRepos walks all the children of `path`. If a child directory
  765. // contain a .git file then that repo will be added to the list of repos returned
  766. func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
  767. var (
  768. err error
  769. repos []*RepoDescriptor
  770. )
  771. files, err := ioutil.ReadDir(ownerPath)
  772. if err != nil {
  773. return repos, err
  774. }
  775. for _, f := range files {
  776. if f.IsDir() {
  777. repoPath := path.Join(ownerPath, f.Name())
  778. r, err := git.PlainOpen(repoPath)
  779. if err != nil {
  780. continue
  781. }
  782. repos = append(repos, &RepoDescriptor{
  783. repository: r,
  784. name: f.Name(),
  785. path: repoPath,
  786. })
  787. }
  788. }
  789. return repos, err
  790. }
  791. // externalConfig will attempt to load a pinned ".gitleaks.toml" configuration file
  792. // from a remote or local repo. Use the --repo-config option to trigger this.
  793. func externalConfig(repo *RepoDescriptor) error {
  794. var config Config
  795. wt, err := repo.repository.Worktree()
  796. if err != nil {
  797. return err
  798. }
  799. f, err := wt.Filesystem.Open(".gitleaks.toml")
  800. if err != nil {
  801. return err
  802. }
  803. if _, err := toml.DecodeReader(f, &config); err != nil {
  804. return fmt.Errorf("problem loading config: %v", err)
  805. }
  806. f.Close()
  807. if err != nil {
  808. return err
  809. }
  810. updateConfig(config)
  811. return nil
  812. }
  813. // setLogLevel sets log level for gitleaks. Default is Warning
  814. func setLogs() {
  815. switch opts.Log {
  816. case "info":
  817. log.SetLevel(log.InfoLevel)
  818. case "debug":
  819. log.SetLevel(log.DebugLevel)
  820. case "warn":
  821. log.SetLevel(log.WarnLevel)
  822. default:
  823. log.SetLevel(log.InfoLevel)
  824. }
  825. log.SetFormatter(&log.TextFormatter{
  826. FullTimestamp: true,
  827. })
  828. }
  829. // optsGuard prevents invalid options
  830. func optsGuard() error {
  831. var err error
  832. if opts.GithubOrg != "" && opts.GithubUser != "" {
  833. return fmt.Errorf("github user and organization set")
  834. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  835. return fmt.Errorf("github organization set and local owner path")
  836. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  837. return fmt.Errorf("github user set and local owner path")
  838. }
  839. if opts.Threads > runtime.GOMAXPROCS(0) {
  840. return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
  841. }
  842. // do the URL Parse and error checking here, so we can skip it later
  843. // empty string is OK, it will default to the public github URL.
  844. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  845. if !strings.HasSuffix(opts.GithubURL, "/") {
  846. opts.GithubURL += "/"
  847. }
  848. ghURL, err := url.Parse(opts.GithubURL)
  849. if err != nil {
  850. return err
  851. }
  852. tcpPort := "443"
  853. if ghURL.Scheme == "http" {
  854. tcpPort = "80"
  855. }
  856. timeout := time.Duration(1 * time.Second)
  857. _, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
  858. if err != nil {
  859. return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
  860. }
  861. }
  862. if opts.SingleSearch != "" {
  863. singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
  864. if err != nil {
  865. return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
  866. }
  867. }
  868. if opts.Entropy > 8 {
  869. return fmt.Errorf("The maximum level of entropy is 8")
  870. }
  871. if opts.Report != "" {
  872. if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
  873. return fmt.Errorf("Report should be a .json or .csv file")
  874. }
  875. dirPath := filepath.Dir(opts.Report)
  876. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  877. return fmt.Errorf("%s does not exist", dirPath)
  878. }
  879. }
  880. return nil
  881. }
  882. // loadToml loads of the toml config containing regexes and whitelists.
  883. // This function will first look if the configPath is set and load the config
  884. // from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
  885. // env var. If that is not set, then gitleaks will continue with the default configs
  886. // specified by the const var at the top `defaultConfig`
  887. func loadToml() error {
  888. var (
  889. config Config
  890. configPath string
  891. )
  892. if opts.ConfigPath != "" {
  893. configPath = opts.ConfigPath
  894. _, err := os.Stat(configPath)
  895. if err != nil {
  896. return fmt.Errorf("no gitleaks config at %s", configPath)
  897. }
  898. } else {
  899. configPath = os.Getenv("GITLEAKS_CONFIG")
  900. }
  901. if configPath != "" {
  902. if _, err := toml.DecodeFile(configPath, &config); err != nil {
  903. return fmt.Errorf("problem loading config: %v", err)
  904. }
  905. } else {
  906. _, err := toml.Decode(defaultConfig, &config)
  907. if err != nil {
  908. return fmt.Errorf("problem loading default config: %v", err)
  909. }
  910. }
  911. return updateConfig(config)
  912. }
  913. // updateConfig will update a the global config values
  914. func updateConfig(config Config) error {
  915. if len(config.Misc.Entropy) != 0 {
  916. err := entropyLimits(config.Misc.Entropy)
  917. if err != nil {
  918. return err
  919. }
  920. }
  921. for _, regex := range config.Entropy.LineRegexes {
  922. entropyRegexes = append(entropyRegexes, regexp.MustCompile(regex))
  923. }
  924. if singleSearchRegex != nil {
  925. regexes["singleSearch"] = singleSearchRegex
  926. } else {
  927. for _, regex := range config.Regexes {
  928. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  929. }
  930. }
  931. whiteListCommits = make(map[string]bool)
  932. for _, commit := range config.Whitelist.Commits {
  933. whiteListCommits[commit] = true
  934. }
  935. for _, regex := range config.Whitelist.Files {
  936. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  937. }
  938. for _, regex := range config.Whitelist.Regexes {
  939. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  940. }
  941. for _, regex := range config.Whitelist.Repos {
  942. whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
  943. }
  944. return nil
  945. }
  946. // entropyLimits hydrates entropyRanges which allows for fine tuning entropy checking
  947. func entropyLimits(entropyLimitStr []string) error {
  948. for _, span := range entropyLimitStr {
  949. split := strings.Split(span, "-")
  950. v1, err := strconv.ParseFloat(split[0], 64)
  951. if err != nil {
  952. return err
  953. }
  954. v2, err := strconv.ParseFloat(split[1], 64)
  955. if err != nil {
  956. return err
  957. }
  958. if v1 > v2 {
  959. return fmt.Errorf("entropy range must be ascending")
  960. }
  961. r := entropyRange{
  962. v1: v1,
  963. v2: v2,
  964. }
  965. if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
  966. return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
  967. }
  968. entropyRanges = append(entropyRanges, r)
  969. }
  970. return nil
  971. }
  972. // getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
  973. // If --ssh-key is set then it will attempt to load the key from that path. If not,
  974. // gitleaks will use the default $HOME/.ssh/id_rsa key
  975. func getSSHAuth() (*ssh.PublicKeys, error) {
  976. var (
  977. sshKeyPath string
  978. )
  979. if opts.SSHKey != "" {
  980. sshKeyPath = opts.SSHKey
  981. } else {
  982. // try grabbing default
  983. c, err := user.Current()
  984. if err != nil {
  985. return nil, nil
  986. }
  987. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  988. }
  989. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  990. if err != nil {
  991. if strings.HasPrefix(opts.Repo, "git") {
  992. // if you are attempting to clone a git repo via ssh and supply a bad ssh key,
  993. // the clone will fail.
  994. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  995. }
  996. }
  997. return sshAuth, nil
  998. }
  999. func (leak Leak) log() {
  1000. b, _ := json.MarshalIndent(leak, "", " ")
  1001. fmt.Println(string(b))
  1002. }