main.go 25 KB

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