main.go 23 KB

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