main.go 22 KB

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