main.go 27 KB

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