main.go 24 KB

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