main.go 21 KB

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