main.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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.3.0"
  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. if opts.Disk {
  247. log.Infof("cloning %s", opts.Repo)
  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. log.Infof("opening %s", opts.Repo)
  264. r, err = git.PlainOpen(opts.RepoPath)
  265. } else {
  266. log.Infof("cloning %s", opts.Repo)
  267. if opts.IncludePrivate {
  268. r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  269. URL: opts.Repo,
  270. Progress: os.Stdout,
  271. Auth: sshAuth,
  272. })
  273. } else {
  274. r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  275. URL: opts.Repo,
  276. Progress: os.Stdout,
  277. })
  278. }
  279. }
  280. return Repo{
  281. repository: r,
  282. path: opts.RepoPath,
  283. url: opts.Repo,
  284. name: filepath.Base(opts.Repo),
  285. err: err,
  286. }, nil
  287. }
  288. // auditRef audits a git reference
  289. // TODO: need to add a layer of parallelism here and a cache for parent+child commits so we don't
  290. // double dip
  291. func auditRef(r *git.Repository, ref *plumbing.Reference, commitWg *sync.WaitGroup, commitChan chan []Leak) error {
  292. var (
  293. err error
  294. prevCommit *object.Commit
  295. limitGoRoutines bool
  296. semaphore chan bool
  297. )
  298. // goroutine limiting
  299. if opts.MaxGoRoutines != 0 {
  300. semaphore = make(chan bool, opts.MaxGoRoutines)
  301. limitGoRoutines = true
  302. }
  303. cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
  304. if err != nil {
  305. return err
  306. }
  307. err = cIter.ForEach(func(c *object.Commit) error {
  308. if c.Hash.String() == opts.Commit {
  309. cIter.Close()
  310. }
  311. if whiteListCommits[c.Hash.String()] {
  312. log.Infof("skipping commit: %s\n", c.Hash.String())
  313. return nil
  314. }
  315. if limitGoRoutines {
  316. semaphore <- true
  317. }
  318. commitWg.Add(1)
  319. go func(c *object.Commit, prevCommit *object.Commit) {
  320. var (
  321. leaks []Leak
  322. filePath string
  323. skipFile bool
  324. )
  325. if prevCommit == nil {
  326. t, _ := c.Tree()
  327. files := t.Files()
  328. err := files.ForEach(func(file *object.File) error {
  329. content, err := file.Contents()
  330. if err != nil {
  331. return err
  332. }
  333. leaks = append(leaks, checkDiff(content, c, file.Name, string(ref.Name()))...)
  334. return nil
  335. })
  336. if err != nil {
  337. log.Warnf("problem generating diff for commit: %s\n", c.Hash.String())
  338. if limitGoRoutines {
  339. <-semaphore
  340. }
  341. commitChan <- leaks
  342. return
  343. }
  344. } else {
  345. patch, err := c.Patch(prevCommit)
  346. if err != nil {
  347. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  348. if limitGoRoutines {
  349. <-semaphore
  350. }
  351. commitChan <- leaks
  352. return
  353. }
  354. for _, f := range patch.FilePatches() {
  355. skipFile = false
  356. from, to := f.Files()
  357. filePath = "???"
  358. if from != nil {
  359. filePath = from.Path()
  360. } else if to != nil {
  361. filePath = to.Path()
  362. }
  363. for _, re := range whiteListFiles {
  364. if re.FindString(filePath) != "" {
  365. skipFile = true
  366. break
  367. }
  368. }
  369. if skipFile {
  370. continue
  371. }
  372. chunks := f.Chunks()
  373. for _, chunk := range chunks {
  374. if chunk.Type() == 1 || chunk.Type() == 2 {
  375. // only check if adding or removing
  376. leaks = append(leaks, checkDiff(chunk.Content(), prevCommit, filePath, string(ref.Name()))...)
  377. }
  378. }
  379. }
  380. }
  381. if limitGoRoutines {
  382. <-semaphore
  383. }
  384. commitChan <- leaks
  385. }(c, prevCommit)
  386. prevCommit = c
  387. return nil
  388. })
  389. return nil
  390. }
  391. // auditRepo performs an audit on a repository checking for regex matching and ignoring
  392. // files and regexes that are whitelisted
  393. func auditRepo(r *git.Repository) ([]Leak, error) {
  394. var (
  395. err error
  396. leaks []Leak
  397. commitWg sync.WaitGroup
  398. )
  399. ref, err := r.Head()
  400. if err != nil {
  401. return leaks, err
  402. }
  403. // leak messaging
  404. commitChan := make(chan []Leak, 1)
  405. if opts.AuditAllRefs {
  406. skipBranch := false
  407. refs, err := r.Storer.IterReferences()
  408. if err != nil {
  409. return leaks, err
  410. }
  411. err = refs.ForEach(func(ref *plumbing.Reference) error {
  412. for _, b := range whiteListBranches {
  413. if strings.HasSuffix(string(ref.Name()), b) {
  414. skipBranch = true
  415. }
  416. }
  417. if skipBranch {
  418. skipBranch = false
  419. return nil
  420. }
  421. auditRef(r, ref, &commitWg, commitChan)
  422. return nil
  423. })
  424. } else {
  425. if opts.Branch != "" {
  426. foundBranch := false
  427. refs, _ := r.Storer.IterReferences()
  428. branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1]
  429. err = refs.ForEach(func(refBranch *plumbing.Reference) error {
  430. if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch {
  431. foundBranch = true
  432. ref = refBranch
  433. }
  434. return nil
  435. })
  436. if foundBranch == false {
  437. log.Fatalf("No branch with name", opts.Branch)
  438. return nil, nil
  439. }
  440. }
  441. auditRef(r, ref, &commitWg, commitChan)
  442. }
  443. go func() {
  444. for commitLeaks := range commitChan {
  445. if commitLeaks != nil {
  446. for _, leak := range commitLeaks {
  447. leaks = append(leaks, leak)
  448. }
  449. }
  450. commitWg.Done()
  451. }
  452. }()
  453. commitWg.Wait()
  454. return leaks, err
  455. }
  456. // checkDiff accepts a string diff and commit object then performs a
  457. // regex check
  458. func checkDiff(diff string, commit *object.Commit, filePath string, branch string) []Leak {
  459. lines := strings.Split(diff, "\n")
  460. var (
  461. leaks []Leak
  462. skipLine bool
  463. )
  464. for _, line := range lines {
  465. skipLine = false
  466. for leakType, re := range regexes {
  467. match := re.FindString(line)
  468. if match == "" {
  469. continue
  470. }
  471. // if offender matches whitelist regex, ignore it
  472. for _, wRe := range whiteListRegexes {
  473. whitelistMatch := wRe.FindString(line)
  474. if whitelistMatch != "" {
  475. skipLine = true
  476. break
  477. }
  478. }
  479. if skipLine {
  480. break
  481. }
  482. leak := Leak{
  483. Line: line,
  484. Commit: commit.Hash.String(),
  485. Offender: match,
  486. Type: leakType,
  487. Message: commit.Message,
  488. Author: commit.Author.String(),
  489. File: filePath,
  490. Branch: branch,
  491. }
  492. if opts.Redact {
  493. leak.Offender = "REDACTED"
  494. leak.Line = "REDACTED"
  495. }
  496. if opts.Verbose {
  497. leak.log()
  498. }
  499. leaks = append(leaks, leak)
  500. }
  501. }
  502. return leaks
  503. }
  504. // auditOwner audits all of the owner's(user or org) repos
  505. func getOwnerRepos() ([]Repo, error) {
  506. var (
  507. err error
  508. repos []Repo
  509. )
  510. ctx := context.Background()
  511. if opts.OwnerPath != "" {
  512. repos, err = discoverRepos(opts.OwnerPath)
  513. } else if opts.GithubOrg != "" {
  514. githubClient := github.NewClient(githubToken())
  515. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  516. ghURL, _ := url.Parse(opts.GithubURL)
  517. githubClient.BaseURL = ghURL
  518. }
  519. githubOptions := github.RepositoryListByOrgOptions{
  520. ListOptions: github.ListOptions{PerPage: 10},
  521. }
  522. repos, err = getOrgGithubRepos(ctx, &githubOptions, githubClient)
  523. } else if opts.GithubUser != "" {
  524. githubClient := github.NewClient(githubToken())
  525. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  526. ghURL, _ := url.Parse(opts.GithubURL)
  527. githubClient.BaseURL = ghURL
  528. }
  529. githubOptions := github.RepositoryListOptions{
  530. Affiliation: "owner",
  531. ListOptions: github.ListOptions{
  532. PerPage: 10,
  533. },
  534. }
  535. repos, err = getUserGithubRepos(ctx, &githubOptions, githubClient)
  536. }
  537. return repos, err
  538. }
  539. // getUserGithubRepos grabs all github user's public and/or private repos
  540. func getUserGithubRepos(ctx context.Context, listOpts *github.RepositoryListOptions, client *github.Client) ([]Repo, error) {
  541. var (
  542. err error
  543. repos []Repo
  544. r *git.Repository
  545. rs []*github.Repository
  546. resp *github.Response
  547. )
  548. for {
  549. if opts.IncludePrivate {
  550. rs, resp, err = client.Repositories.List(ctx, "", listOpts)
  551. } else {
  552. rs, resp, err = client.Repositories.List(ctx, opts.GithubUser, listOpts)
  553. }
  554. for _, rDesc := range rs {
  555. log.Infof("cloning: %s", *rDesc.Name)
  556. if opts.Disk {
  557. ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
  558. if err != nil {
  559. return repos, fmt.Errorf("unable to generater owner temp dir: %v", err)
  560. }
  561. if opts.IncludePrivate {
  562. r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
  563. URL: *rDesc.SSHURL,
  564. Auth: sshAuth,
  565. })
  566. } else {
  567. r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
  568. URL: *rDesc.CloneURL,
  569. })
  570. }
  571. } else {
  572. if opts.IncludePrivate {
  573. r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  574. URL: *rDesc.SSHURL,
  575. Auth: sshAuth,
  576. })
  577. } else {
  578. r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  579. URL: *rDesc.CloneURL,
  580. })
  581. }
  582. }
  583. repos = append(repos, Repo{
  584. name: *rDesc.Name,
  585. url: *rDesc.SSHURL,
  586. repository: r,
  587. err: err,
  588. })
  589. }
  590. if resp.NextPage == 0 {
  591. break
  592. }
  593. listOpts.Page = resp.NextPage
  594. }
  595. return repos, err
  596. }
  597. // getOrgGithubRepos grabs all of org's public and/or private repos
  598. func getOrgGithubRepos(ctx context.Context, listOpts *github.RepositoryListByOrgOptions, client *github.Client) ([]Repo, error) {
  599. var (
  600. err error
  601. repos []Repo
  602. r *git.Repository
  603. ownerDir string
  604. )
  605. for {
  606. rs, resp, err := client.Repositories.ListByOrg(ctx, opts.GithubOrg, listOpts)
  607. for _, rDesc := range rs {
  608. log.Infof("cloning: %s", *rDesc.Name)
  609. if opts.Disk {
  610. ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
  611. if err != nil {
  612. return repos, fmt.Errorf("unable to generater owner temp dir: %v", err)
  613. }
  614. if opts.IncludePrivate {
  615. if sshAuth == nil {
  616. return nil, fmt.Errorf("no ssh auth available")
  617. }
  618. r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
  619. URL: *rDesc.SSHURL,
  620. Auth: sshAuth,
  621. })
  622. } else {
  623. r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
  624. URL: *rDesc.CloneURL,
  625. })
  626. }
  627. } else {
  628. if opts.IncludePrivate {
  629. if sshAuth == nil {
  630. return nil, fmt.Errorf("no ssh auth available")
  631. }
  632. r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  633. URL: *rDesc.SSHURL,
  634. Auth: sshAuth,
  635. })
  636. } else {
  637. r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  638. URL: *rDesc.CloneURL,
  639. })
  640. }
  641. }
  642. repos = append(repos, Repo{
  643. url: *rDesc.SSHURL,
  644. name: *rDesc.Name,
  645. repository: r,
  646. err: err,
  647. })
  648. }
  649. if resp.NextPage == 0 {
  650. break
  651. }
  652. listOpts.Page = resp.NextPage
  653. }
  654. return repos, err
  655. }
  656. // githubToken returns a oauth2 client for the github api to consume
  657. func githubToken() *http.Client {
  658. githubToken := os.Getenv("GITHUB_TOKEN")
  659. if githubToken == "" {
  660. return nil
  661. }
  662. ts := oauth2.StaticTokenSource(
  663. &oauth2.Token{AccessToken: githubToken},
  664. )
  665. return oauth2.NewClient(context.Background(), ts)
  666. }
  667. // discoverRepos walks all the children of `path`. If a child directory
  668. // contain a .git file then that repo will be added
  669. func discoverRepos(ownerPath string) ([]Repo, error) {
  670. var (
  671. err error
  672. repos []Repo
  673. )
  674. files, err := ioutil.ReadDir(ownerPath)
  675. if err != nil {
  676. return repos, err
  677. }
  678. for _, f := range files {
  679. if f.IsDir() {
  680. repoPath := path.Join(ownerPath, f.Name())
  681. r, err := git.PlainOpen(repoPath)
  682. if err != nil {
  683. continue
  684. }
  685. repos = append(repos, Repo{
  686. repository: r,
  687. name: f.Name(),
  688. path: repoPath,
  689. })
  690. }
  691. }
  692. return repos, err
  693. }
  694. // setLogLevel sets log level for gitleaks. Default is Warning
  695. func setLogs() {
  696. switch opts.Log {
  697. case "info":
  698. log.SetLevel(log.InfoLevel)
  699. case "debug":
  700. log.SetLevel(log.DebugLevel)
  701. case "warn":
  702. log.SetLevel(log.WarnLevel)
  703. default:
  704. log.SetLevel(log.InfoLevel)
  705. }
  706. log.SetFormatter(&log.TextFormatter{
  707. FullTimestamp: true,
  708. })
  709. }
  710. // optsGuard prevents invalid options
  711. func optsGuard() error {
  712. var err error
  713. if opts.GithubOrg != "" && opts.GithubUser != "" {
  714. return fmt.Errorf("github user and organization set")
  715. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  716. return fmt.Errorf("github organization set and local owner path")
  717. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  718. return fmt.Errorf("github user set and local owner path")
  719. } else if opts.IncludePrivate && os.Getenv("GITHUB_TOKEN") == "" && (opts.GithubOrg != "" || opts.GithubUser != "") {
  720. return fmt.Errorf("user/organization private repos require env var GITHUB_TOKEN to be set")
  721. }
  722. // do the URL Parse and error checking here, so we can skip it later
  723. // empty string is OK, it will default to the public github URL.
  724. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  725. if !strings.HasSuffix(opts.GithubURL, "/") {
  726. opts.GithubURL += "/"
  727. }
  728. ghURL, err := url.Parse(opts.GithubURL)
  729. if err != nil {
  730. return err
  731. }
  732. tcpPort := "443"
  733. if ghURL.Scheme == "http" {
  734. tcpPort = "80"
  735. }
  736. timeout := time.Duration(1 * time.Second)
  737. _, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
  738. if err != nil {
  739. return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
  740. }
  741. }
  742. if opts.SingleSearch != "" {
  743. singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
  744. if err != nil {
  745. return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
  746. }
  747. }
  748. return nil
  749. }
  750. // loadToml loads of the toml config containing regexes and whitelists
  751. // 1. look for config path
  752. // 2. two, look for gitleaks config env var
  753. func loadToml() error {
  754. var (
  755. config Config
  756. configPath string
  757. )
  758. if opts.ConfigPath != "" {
  759. configPath = opts.ConfigPath
  760. _, err := os.Stat(configPath)
  761. if err != nil {
  762. return fmt.Errorf("no gitleaks config at %s", configPath)
  763. }
  764. } else {
  765. configPath = os.Getenv("GITLEAKS_CONFIG")
  766. }
  767. if configPath != "" {
  768. if _, err := toml.DecodeFile(configPath, &config); err != nil {
  769. return fmt.Errorf("problem loading config: %v", err)
  770. }
  771. } else {
  772. _, err := toml.Decode(defaultConfig, &config)
  773. if err != nil {
  774. return fmt.Errorf("problem loading default config: %v", err)
  775. }
  776. }
  777. // load up regexes
  778. if singleSearchRegex != nil {
  779. // single search takes precedence over default regex
  780. regexes["singleSearch"] = singleSearchRegex
  781. } else {
  782. for _, regex := range config.Regexes {
  783. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  784. }
  785. }
  786. whiteListBranches = config.Whitelist.Branches
  787. whiteListCommits = make(map[string]bool)
  788. for _, commit := range config.Whitelist.Commits {
  789. whiteListCommits[commit] = true
  790. }
  791. for _, regex := range config.Whitelist.Files {
  792. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  793. }
  794. for _, regex := range config.Whitelist.Regexes {
  795. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  796. }
  797. return nil
  798. }
  799. // ownerTarget checks if we are dealing with a remote owner
  800. func ownerTarget() bool {
  801. if opts.GithubOrg != "" ||
  802. opts.GithubUser != "" ||
  803. opts.OwnerPath != "" {
  804. return true
  805. }
  806. return false
  807. }
  808. // getSSHAuth generates ssh auth
  809. func getSSHAuth() (*ssh.PublicKeys, error) {
  810. var (
  811. sshKeyPath string
  812. )
  813. if opts.SSHKey != "" {
  814. sshKeyPath = opts.SSHKey
  815. } else {
  816. c, _ := user.Current()
  817. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  818. }
  819. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  820. if err != nil {
  821. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  822. }
  823. return sshAuth, err
  824. }
  825. func (leak *Leak) log() {
  826. b, _ := json.MarshalIndent(leak, "", " ")
  827. fmt.Println(string(b))
  828. }