main.go 25 KB

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