main.go 26 KB

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