main.go 26 KB

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