main.go 27 KB

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