main.go 25 KB

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