main.go 27 KB

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