main.go 19 KB

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