main.go 20 KB

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