main.go 26 KB

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