4
0

main.go 21 KB

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