main.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. package main
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/csv"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "math"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "os/user"
  16. "path"
  17. "path/filepath"
  18. "regexp"
  19. "runtime"
  20. "strings"
  21. "sync"
  22. "time"
  23. "gopkg.in/src-d/go-git.v4/plumbing"
  24. "golang.org/x/oauth2"
  25. "gopkg.in/src-d/go-git.v4/plumbing/object"
  26. "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
  27. "gopkg.in/src-d/go-git.v4/storage/memory"
  28. "github.com/BurntSushi/toml"
  29. "github.com/google/go-github/github"
  30. "github.com/hako/durafmt"
  31. flags "github.com/jessevdk/go-flags"
  32. log "github.com/sirupsen/logrus"
  33. git "gopkg.in/src-d/go-git.v4"
  34. )
  35. // Leak represents a leaked secret or regex match.
  36. type Leak struct {
  37. Line string `json:"line"`
  38. Commit string `json:"commit"`
  39. Offender string `json:"offender"`
  40. Type string `json:"reason"`
  41. Message string `json:"commitMsg"`
  42. Author string `json:"author"`
  43. File string `json:"file"`
  44. Branch string `json:"branch"`
  45. Repo string `json:"repo"`
  46. }
  47. // RepoDescriptor contains a src-d git repository and other data about the repo
  48. type RepoDescriptor struct {
  49. path string
  50. url string
  51. name string
  52. repository *git.Repository
  53. err error
  54. }
  55. // Options for gitleaks
  56. type Options struct {
  57. // remote target options
  58. Repo string `short:"r" long:"repo" description:"Repo url to audit"`
  59. GithubUser string `long:"github-user" description:"Github user to audit"`
  60. GithubOrg string `long:"github-org" description:"Github organization to audit"`
  61. 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/"`
  62. IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"`
  63. /*
  64. TODO:
  65. GitLabUser string `long:"gitlab-user" description:"User url to audit"`
  66. GitLabOrg string `long:"gitlab-org" description:"Organization url to audit"`
  67. */
  68. Branch string `short:"b" long:"branch" description:"branch name to audit (defaults to HEAD)"`
  69. Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
  70. Depth int `long:"depth" description:"maximum commit depth"`
  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. ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
  82. Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
  83. // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
  84. // Output options
  85. Log string `short:"l" long:"log" description:"log level"`
  86. Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
  87. Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
  88. Redact bool `long:"redact" description:"redact secrets from log messages and report"`
  89. Version bool `long:"version" description:"version number"`
  90. SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
  91. }
  92. // Config struct for regexes matching and whitelisting
  93. type Config struct {
  94. Regexes []struct {
  95. Description string
  96. Regex string
  97. }
  98. Whitelist struct {
  99. Files []string
  100. Regexes []string
  101. Commits []string
  102. Branches []string
  103. Repos []string
  104. }
  105. }
  106. type gitDiff struct {
  107. content string
  108. commit *object.Commit
  109. filePath string
  110. branchName string
  111. repoName string
  112. }
  113. const defaultGithubURL = "https://api.github.com/"
  114. const version = "1.12.1"
  115. const errExit = 2
  116. const leakExit = 1
  117. const defaultConfig = `
  118. # This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
  119. # The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
  120. # is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
  121. # configurations from that path. Gitleaks does not whitelist anything by default.
  122. title = "gitleaks config"
  123. # add regexes to the regex table
  124. [[regexes]]
  125. description = "AWS"
  126. regex = '''AKIA[0-9A-Z]{16}'''
  127. [[regexes]]
  128. description = "RKCS8"
  129. regex = '''-----BEGIN PRIVATE KEY-----'''
  130. [[regexes]]
  131. description = "RSA"
  132. regex = '''-----BEGIN RSA PRIVATE KEY-----'''
  133. [[regexes]]
  134. description = "Github"
  135. regex = '''(?i)github.*['\"][0-9a-zA-Z]{35,40}['\"]'''
  136. [[regexes]]
  137. description = "SSH"
  138. regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
  139. [[regexes]]
  140. description = "Facebook"
  141. regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]'''
  142. [[regexes]]
  143. description = "Twitter"
  144. regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
  145. [whitelist]
  146. #regexes = [
  147. # "AKAIMYFAKEAWKKEY",
  148. #]
  149. #files = [
  150. # "(.*?)(jpg|gif|doc|pdf|bin)$"
  151. #]
  152. #commits = [
  153. # "BADHA5H1",
  154. # "BADHA5H2",
  155. #]
  156. #branches = [
  157. # "dev/STUPDIFKNFEATURE"
  158. #]
  159. #repos = [
  160. # "someYugeRepoWeKnowIsCLEAR"
  161. #]
  162. `
  163. var (
  164. opts Options
  165. regexes map[string]*regexp.Regexp
  166. singleSearchRegex *regexp.Regexp
  167. whiteListRegexes []*regexp.Regexp
  168. whiteListFiles []*regexp.Regexp
  169. whiteListCommits map[string]bool
  170. whiteListBranches []string
  171. whiteListRepos []string
  172. fileDiffRegex *regexp.Regexp
  173. sshAuth *ssh.PublicKeys
  174. dir string
  175. maxGo int
  176. totalCommits int64
  177. )
  178. func init() {
  179. log.SetOutput(os.Stdout)
  180. maxGo = runtime.GOMAXPROCS(0) / 2
  181. regexes = make(map[string]*regexp.Regexp)
  182. whiteListCommits = make(map[string]bool)
  183. }
  184. func main() {
  185. parser := flags.NewParser(&opts, flags.Default)
  186. _, err := parser.Parse()
  187. if err != nil {
  188. if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
  189. os.Exit(0)
  190. }
  191. }
  192. if len(os.Args) == 1 {
  193. parser.WriteHelp(os.Stdout)
  194. os.Exit(0)
  195. }
  196. if opts.Version {
  197. fmt.Println(version)
  198. os.Exit(0)
  199. }
  200. if opts.SampleConfig {
  201. fmt.Println(defaultConfig)
  202. os.Exit(0)
  203. }
  204. now := time.Now()
  205. leaks, err := run()
  206. if err != nil {
  207. log.Error(err)
  208. os.Exit(errExit)
  209. }
  210. if opts.Report != "" {
  211. writeReport(leaks)
  212. }
  213. log.Infof("%d commits inspected in %s", totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
  214. if len(leaks) != 0 {
  215. log.Warnf("%d leaks detected", len(leaks))
  216. os.Exit(leakExit)
  217. }
  218. }
  219. // run parses options and kicks off the audit
  220. func run() ([]Leak, error) {
  221. var leaks []Leak
  222. setLogs()
  223. err := optsGuard()
  224. if err != nil {
  225. return nil, err
  226. }
  227. err = loadToml()
  228. if err != nil {
  229. return nil, err
  230. }
  231. if opts.IncludePrivate {
  232. // if including private repos use ssh as authentication
  233. sshAuth, err = getSSHAuth()
  234. if err != nil {
  235. return nil, err
  236. }
  237. }
  238. if opts.Disk {
  239. // temporary directory where all the gitleaks plain clones will reside
  240. dir, err = ioutil.TempDir("", "gitleaks")
  241. defer os.RemoveAll(dir)
  242. if err != nil {
  243. return nil, err
  244. }
  245. }
  246. // start audits
  247. if opts.Repo != "" || opts.RepoPath != "" {
  248. // Audit a single remote repo or a local repo.
  249. repo, err := cloneRepo()
  250. if err != nil {
  251. return leaks, err
  252. }
  253. return auditGitRepo(repo)
  254. } else if opts.OwnerPath != "" {
  255. // Audit local repos. Gitleaks will look for all child directories of OwnerPath for
  256. // git repos and perform an audit on said repos.
  257. repos, err := discoverRepos(opts.OwnerPath)
  258. if err != nil {
  259. return leaks, err
  260. }
  261. for _, repo := range repos {
  262. leaksFromRepo, err := auditGitRepo(repo)
  263. if err != nil {
  264. return leaks, err
  265. }
  266. leaks = append(leaksFromRepo, leaks...)
  267. }
  268. } else if opts.GithubOrg != "" || opts.GithubUser != "" {
  269. // Audit a github owner -- a user or organization. If you want to include
  270. // private repos you must pass a --private/-p option and have your ssh keys set
  271. leaks, err = auditGithubRepos()
  272. if err != nil {
  273. return leaks, err
  274. }
  275. }
  276. return leaks, nil
  277. }
  278. // writeReport writes a report to a file specified in the --report= option.
  279. // Default format for report is JSON. You can use the --csv option to write the report as a csv
  280. func writeReport(leaks []Leak) error {
  281. var err error
  282. log.Infof("writing report to %s", opts.Report)
  283. if strings.HasSuffix(opts.Report, ".csv") {
  284. f, err := os.Create(opts.Report)
  285. if err != nil {
  286. return err
  287. }
  288. defer f.Close()
  289. w := csv.NewWriter(f)
  290. w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "branch"})
  291. for _, leak := range leaks {
  292. w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Branch})
  293. }
  294. w.Flush()
  295. } else {
  296. reportJSON, _ := json.MarshalIndent(leaks, "", "\t")
  297. err = ioutil.WriteFile(opts.Report, reportJSON, 0644)
  298. }
  299. return err
  300. }
  301. // cloneRepo clones a repo to memory(default) or to disk if the --disk option is set. If you want to
  302. // clone a private repo you must set the --private/-p option, use a ssh target, and have your ssh keys
  303. // configured. If you want to audit a local repo, getRepo will load up a repo located at --repo-path
  304. func cloneRepo() (*RepoDescriptor, error) {
  305. var (
  306. err error
  307. repo *git.Repository
  308. )
  309. if opts.Disk {
  310. log.Infof("cloning %s", opts.Repo)
  311. cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
  312. if opts.IncludePrivate {
  313. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  314. URL: opts.Repo,
  315. Progress: os.Stdout,
  316. Auth: sshAuth,
  317. })
  318. } else {
  319. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  320. URL: opts.Repo,
  321. Progress: os.Stdout,
  322. })
  323. }
  324. } else if opts.RepoPath != "" {
  325. log.Infof("opening %s", opts.Repo)
  326. repo, err = git.PlainOpen(opts.RepoPath)
  327. } else {
  328. log.Infof("cloning %s", opts.Repo)
  329. if opts.IncludePrivate {
  330. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  331. URL: opts.Repo,
  332. Progress: os.Stdout,
  333. Auth: sshAuth,
  334. })
  335. } else {
  336. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  337. URL: opts.Repo,
  338. Progress: os.Stdout,
  339. })
  340. }
  341. }
  342. return &RepoDescriptor{
  343. repository: repo,
  344. path: opts.RepoPath,
  345. url: opts.Repo,
  346. name: filepath.Base(opts.Repo),
  347. err: err,
  348. }, nil
  349. }
  350. // auditGitRepo beings an audit on a git repository by checking the default HEAD branch, all branches, or
  351. // a single branch depending on what gitleaks is configured to do. Note when I say branch I really
  352. // mean reference as these branches are read only.
  353. func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
  354. var (
  355. err error
  356. leaks []Leak
  357. )
  358. for _, repoName := range whiteListRepos {
  359. if repoName == repo.name {
  360. return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
  361. }
  362. }
  363. ref, err := repo.repository.Head()
  364. if err != nil {
  365. return leaks, err
  366. }
  367. if opts.AuditAllRefs {
  368. skipBranch := false
  369. refs, err := repo.repository.Storer.IterReferences()
  370. if err != nil {
  371. return leaks, err
  372. }
  373. err = refs.ForEach(func(ref *plumbing.Reference) error {
  374. for _, b := range whiteListBranches {
  375. if strings.HasSuffix(string(ref.Name()), b) {
  376. skipBranch = true
  377. }
  378. }
  379. if skipBranch {
  380. skipBranch = false
  381. return nil
  382. }
  383. branchLeaks := auditGitReference(repo, ref)
  384. for _, leak := range branchLeaks {
  385. leaks = append(leaks, leak)
  386. }
  387. return nil
  388. })
  389. } else {
  390. if opts.Branch != "" {
  391. foundBranch := false
  392. refs, _ := repo.repository.Storer.IterReferences()
  393. branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1]
  394. err = refs.ForEach(func(refBranch *plumbing.Reference) error {
  395. if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch {
  396. foundBranch = true
  397. ref = refBranch
  398. }
  399. return nil
  400. })
  401. if foundBranch == false {
  402. return nil, nil
  403. }
  404. }
  405. leaks = auditGitReference(repo, ref)
  406. }
  407. return leaks, err
  408. }
  409. // auditGitReference beings the audit for a git reference. This function will
  410. // traverse the git reference and audit each line of each diff. Set maximum concurrency with
  411. // the --max-go option (default is set to the number of cores on your cpu).
  412. func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
  413. var (
  414. err error
  415. prevCommit *object.Commit
  416. semaphore chan bool
  417. repoName string
  418. leaks []Leak
  419. commitWg sync.WaitGroup
  420. mutex = &sync.Mutex{}
  421. commitCount int
  422. )
  423. repoName = repo.name
  424. if opts.MaxGoRoutines != 0 {
  425. maxGo = opts.MaxGoRoutines
  426. }
  427. semaphore = make(chan bool, maxGo)
  428. cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
  429. if err != nil {
  430. return nil
  431. }
  432. err = cIter.ForEach(func(c *object.Commit) error {
  433. if c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
  434. cIter.Close()
  435. return errors.New("ErrStop")
  436. }
  437. commitCount = commitCount + 1
  438. totalCommits = totalCommits + 1
  439. if whiteListCommits[c.Hash.String()] {
  440. prevCommit = c
  441. log.Infof("skipping commit: %s\n", c.Hash.String())
  442. return nil
  443. }
  444. if prevCommit != nil {
  445. if whiteListCommits[prevCommit.Hash.String()] {
  446. prevCommit = c
  447. log.Infof("skipping commit: %s\n", c.Hash.String())
  448. return nil
  449. }
  450. }
  451. commitWg.Add(1)
  452. semaphore <- true
  453. go func(c *object.Commit, prevCommit *object.Commit) {
  454. var (
  455. filePath string
  456. skipFile bool
  457. )
  458. defer func() {
  459. commitWg.Done()
  460. <-semaphore
  461. if r := recover(); r != nil {
  462. log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
  463. }
  464. }()
  465. diff := gitDiff{
  466. commit: prevCommit,
  467. branchName: string(ref.Name()),
  468. repoName: repoName,
  469. }
  470. if prevCommit == nil {
  471. t, _ := c.Tree()
  472. files := t.Files()
  473. err := files.ForEach(func(file *object.File) error {
  474. content, err := file.Contents()
  475. if err != nil {
  476. return err
  477. }
  478. diff.filePath = file.Name
  479. diff.content = content
  480. diff.commit = c
  481. chunkLeaks := inspect(diff)
  482. for _, leak := range chunkLeaks {
  483. mutex.Lock()
  484. leaks = append(leaks, leak)
  485. mutex.Unlock()
  486. }
  487. return nil
  488. })
  489. if err != nil {
  490. log.Warnf("problem generating diff for commit: %s\n", c.Hash.String())
  491. return
  492. }
  493. } else {
  494. patch, err := c.Patch(prevCommit)
  495. if err != nil {
  496. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  497. return
  498. }
  499. for _, f := range patch.FilePatches() {
  500. skipFile = false
  501. from, to := f.Files()
  502. filePath = "???"
  503. if from != nil {
  504. filePath = from.Path()
  505. } else if to != nil {
  506. filePath = to.Path()
  507. }
  508. diff.filePath = filePath
  509. for _, re := range whiteListFiles {
  510. if re.FindString(filePath) != "" {
  511. skipFile = true
  512. break
  513. }
  514. }
  515. if skipFile {
  516. continue
  517. }
  518. chunks := f.Chunks()
  519. for _, chunk := range chunks {
  520. if chunk.Type() == 1 || chunk.Type() == 2 {
  521. diff.content = chunk.Content()
  522. chunkLeaks := inspect(diff)
  523. for _, leak := range chunkLeaks {
  524. mutex.Lock()
  525. leaks = append(leaks, leak)
  526. mutex.Unlock()
  527. }
  528. }
  529. }
  530. }
  531. }
  532. }(c, prevCommit)
  533. prevCommit = c
  534. return nil
  535. })
  536. commitWg.Wait()
  537. return leaks
  538. }
  539. // inspect will parse each line of the git diff's content against a set of regexes or
  540. // a set of regexes set by the config (see gitleaks.toml for example). This function
  541. // will skip lines that include a whitelisted regex. A list of leaks is returned.
  542. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
  543. func inspect(diff gitDiff) []Leak {
  544. lines := strings.Split(diff.content, "\n")
  545. var (
  546. leaks []Leak
  547. skipLine bool
  548. )
  549. for _, line := range lines {
  550. skipLine = false
  551. for leakType, re := range regexes {
  552. match := re.FindString(line)
  553. if match == "" {
  554. continue
  555. }
  556. // if offender matches whitelist regex, ignore it
  557. for _, wRe := range whiteListRegexes {
  558. whitelistMatch := wRe.FindString(line)
  559. if whitelistMatch != "" {
  560. skipLine = true
  561. break
  562. }
  563. }
  564. if skipLine {
  565. break
  566. }
  567. leaks = addLeak(leaks, line, match, leakType, diff)
  568. }
  569. if opts.Entropy > 0 {
  570. words := strings.Fields(line)
  571. for _, word := range words {
  572. if getShannonEntropy(word) >= opts.Entropy {
  573. leaks = addLeak(leaks, line, word, "High Entropy", diff)
  574. }
  575. }
  576. }
  577. }
  578. return leaks
  579. }
  580. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  581. func getShannonEntropy(data string) (entropy float64) {
  582. if data == "" {
  583. return 0
  584. }
  585. charCounts := make(map[rune]int)
  586. for _, char := range data {
  587. charCounts[char]++
  588. }
  589. invLength := 1.0 / float64(len(data))
  590. for _, count := range charCounts {
  591. freq := float64(count) * invLength
  592. entropy -= freq * math.Log2(freq)
  593. }
  594. return entropy
  595. }
  596. // addLeak is helper for func inspect() to append leaks if found during a diff check.
  597. func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
  598. leak := Leak{
  599. Line: line,
  600. Commit: diff.commit.Hash.String(),
  601. Offender: offender,
  602. Type: leakType,
  603. Message: diff.commit.Message,
  604. Author: diff.commit.Author.String(),
  605. File: diff.filePath,
  606. Branch: diff.branchName,
  607. Repo: diff.repoName,
  608. }
  609. if opts.Redact {
  610. leak.Offender = "REDACTED"
  611. leak.Line = "REDACTED"
  612. }
  613. if opts.Verbose {
  614. leak.log()
  615. }
  616. leaks = append(leaks, leak)
  617. return leaks
  618. }
  619. // auditGithubRepos kicks off audits if --github-user or --github-org options are set.
  620. // First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
  621. // After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
  622. // If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
  623. func auditGithubRepos() ([]Leak, error) {
  624. var (
  625. err error
  626. githubRepos []*github.Repository
  627. pagedGithubRepos []*github.Repository
  628. resp *github.Response
  629. githubClient *github.Client
  630. githubOrgOptions *github.RepositoryListByOrgOptions
  631. githubOptions *github.RepositoryListOptions
  632. done bool
  633. leaks []Leak
  634. ownerDir string
  635. )
  636. ctx := context.Background()
  637. if opts.GithubOrg != "" {
  638. githubClient = github.NewClient(githubToken())
  639. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  640. ghURL, _ := url.Parse(opts.GithubURL)
  641. githubClient.BaseURL = ghURL
  642. }
  643. githubOrgOptions = &github.RepositoryListByOrgOptions{
  644. ListOptions: github.ListOptions{PerPage: 100},
  645. }
  646. } else if opts.GithubUser != "" {
  647. githubClient = github.NewClient(githubToken())
  648. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  649. ghURL, _ := url.Parse(opts.GithubURL)
  650. githubClient.BaseURL = ghURL
  651. }
  652. githubOptions = &github.RepositoryListOptions{
  653. Affiliation: "owner",
  654. ListOptions: github.ListOptions{
  655. PerPage: 100,
  656. },
  657. }
  658. }
  659. for {
  660. if done {
  661. break
  662. }
  663. if opts.GithubUser != "" {
  664. if opts.IncludePrivate {
  665. pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
  666. } else {
  667. pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
  668. }
  669. if err != nil {
  670. done = true
  671. }
  672. githubOptions.Page = resp.NextPage
  673. githubRepos = append(githubRepos, pagedGithubRepos...)
  674. if resp.NextPage == 0 {
  675. done = true
  676. }
  677. } else if opts.GithubOrg != "" {
  678. pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
  679. if err != nil {
  680. done = true
  681. }
  682. githubOrgOptions.Page = resp.NextPage
  683. githubRepos = append(githubRepos, pagedGithubRepos...)
  684. if resp.NextPage == 0 {
  685. done = true
  686. }
  687. }
  688. if opts.Log == "Debug" || opts.Log == "debug" {
  689. for _, githubRepo := range pagedGithubRepos {
  690. log.Debugf("staging repos %s", *githubRepo.Name)
  691. }
  692. }
  693. }
  694. if err != nil {
  695. return nil, err
  696. }
  697. if opts.Disk {
  698. ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
  699. os.RemoveAll(ownerDir)
  700. }
  701. for _, githubRepo := range githubRepos {
  702. repo, err := cloneGithubRepo(githubRepo)
  703. if err != nil {
  704. log.Warn(err)
  705. continue
  706. }
  707. leaksFromRepo, err := auditGitRepo(repo)
  708. if opts.Disk {
  709. os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
  710. }
  711. if len(leaksFromRepo) == 0 {
  712. log.Infof("no leaks found for repo %s", *githubRepo.Name)
  713. } else {
  714. log.Warnf("leaks found for repo %s", *githubRepo.Name)
  715. }
  716. if err != nil {
  717. log.Warn(err)
  718. }
  719. leaks = append(leaks, leaksFromRepo...)
  720. }
  721. return leaks, nil
  722. }
  723. // cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
  724. // will be cloned to disk if --disk is set. If the repo is private, you must include the
  725. // --private/-p option. After the repo is clone, an audit will begin.
  726. func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
  727. var (
  728. repo *git.Repository
  729. err error
  730. )
  731. if opts.ExcludeForks && githubRepo.GetFork() {
  732. return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
  733. }
  734. for _, repoName := range whiteListRepos {
  735. if repoName == *githubRepo.Name {
  736. return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
  737. }
  738. }
  739. log.Infof("cloning: %s", *githubRepo.Name)
  740. if opts.Disk {
  741. ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
  742. if err != nil {
  743. return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
  744. }
  745. if opts.IncludePrivate {
  746. if sshAuth == nil {
  747. return nil, fmt.Errorf("no ssh auth available")
  748. }
  749. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  750. URL: *githubRepo.SSHURL,
  751. Auth: sshAuth,
  752. })
  753. } else {
  754. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  755. URL: *githubRepo.CloneURL,
  756. })
  757. }
  758. } else {
  759. if opts.IncludePrivate {
  760. if sshAuth == nil {
  761. return nil, fmt.Errorf("no ssh auth available")
  762. }
  763. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  764. URL: *githubRepo.SSHURL,
  765. Auth: sshAuth,
  766. })
  767. } else {
  768. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  769. URL: *githubRepo.CloneURL,
  770. })
  771. }
  772. }
  773. if err != nil {
  774. return nil, err
  775. }
  776. return &RepoDescriptor{
  777. repository: repo,
  778. name: *githubRepo.Name,
  779. }, nil
  780. }
  781. // githubToken returns an oauth2 client for the github api to consume. This token is necessary
  782. // if you are running audits with --github-user or --github-org
  783. func githubToken() *http.Client {
  784. githubToken := os.Getenv("GITHUB_TOKEN")
  785. if githubToken == "" {
  786. return nil
  787. }
  788. ts := oauth2.StaticTokenSource(
  789. &oauth2.Token{AccessToken: githubToken},
  790. )
  791. return oauth2.NewClient(context.Background(), ts)
  792. }
  793. // discoverRepos walks all the children of `path`. If a child directory
  794. // contain a .git file then that repo will be added to the list of repos returned
  795. func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
  796. var (
  797. err error
  798. repos []*RepoDescriptor
  799. )
  800. files, err := ioutil.ReadDir(ownerPath)
  801. if err != nil {
  802. return repos, err
  803. }
  804. for _, f := range files {
  805. if f.IsDir() {
  806. repoPath := path.Join(ownerPath, f.Name())
  807. r, err := git.PlainOpen(repoPath)
  808. if err != nil {
  809. continue
  810. }
  811. repos = append(repos, &RepoDescriptor{
  812. repository: r,
  813. name: f.Name(),
  814. path: repoPath,
  815. })
  816. }
  817. }
  818. return repos, err
  819. }
  820. // setLogLevel sets log level for gitleaks. Default is Warning
  821. func setLogs() {
  822. switch opts.Log {
  823. case "info":
  824. log.SetLevel(log.InfoLevel)
  825. case "debug":
  826. log.SetLevel(log.DebugLevel)
  827. case "warn":
  828. log.SetLevel(log.WarnLevel)
  829. default:
  830. log.SetLevel(log.InfoLevel)
  831. }
  832. log.SetFormatter(&log.TextFormatter{
  833. FullTimestamp: true,
  834. })
  835. }
  836. // optsGuard prevents invalid options
  837. func optsGuard() error {
  838. var err error
  839. if opts.GithubOrg != "" && opts.GithubUser != "" {
  840. return fmt.Errorf("github user and organization set")
  841. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  842. return fmt.Errorf("github organization set and local owner path")
  843. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  844. return fmt.Errorf("github user set and local owner path")
  845. } else if opts.IncludePrivate && os.Getenv("GITHUB_TOKEN") == "" && (opts.GithubOrg != "" || opts.GithubUser != "") {
  846. return fmt.Errorf("user/organization private repos require env var GITHUB_TOKEN to be set")
  847. }
  848. // do the URL Parse and error checking here, so we can skip it later
  849. // empty string is OK, it will default to the public github URL.
  850. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  851. if !strings.HasSuffix(opts.GithubURL, "/") {
  852. opts.GithubURL += "/"
  853. }
  854. ghURL, err := url.Parse(opts.GithubURL)
  855. if err != nil {
  856. return err
  857. }
  858. tcpPort := "443"
  859. if ghURL.Scheme == "http" {
  860. tcpPort = "80"
  861. }
  862. timeout := time.Duration(1 * time.Second)
  863. _, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
  864. if err != nil {
  865. return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
  866. }
  867. }
  868. if opts.SingleSearch != "" {
  869. singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
  870. if err != nil {
  871. return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
  872. }
  873. }
  874. if opts.Entropy > 8 {
  875. return fmt.Errorf("The maximum level of entropy is 8")
  876. }
  877. if opts.Report != "" {
  878. if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
  879. return fmt.Errorf("Report should be a .json or .csv file")
  880. }
  881. dirPath := filepath.Dir(opts.Report)
  882. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  883. return fmt.Errorf("%s does not exist", dirPath)
  884. }
  885. }
  886. return nil
  887. }
  888. // loadToml loads of the toml config containing regexes and whitelists.
  889. // This function will first look if the configPath is set and load the config
  890. // from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
  891. // env var. If that is not set, then gitleaks will continue with the default configs
  892. // specified by the const var at the top `defaultConfig`
  893. func loadToml() error {
  894. var (
  895. config Config
  896. configPath string
  897. )
  898. if opts.ConfigPath != "" {
  899. configPath = opts.ConfigPath
  900. _, err := os.Stat(configPath)
  901. if err != nil {
  902. return fmt.Errorf("no gitleaks config at %s", configPath)
  903. }
  904. } else {
  905. configPath = os.Getenv("GITLEAKS_CONFIG")
  906. }
  907. if configPath != "" {
  908. if _, err := toml.DecodeFile(configPath, &config); err != nil {
  909. return fmt.Errorf("problem loading config: %v", err)
  910. }
  911. } else {
  912. _, err := toml.Decode(defaultConfig, &config)
  913. if err != nil {
  914. return fmt.Errorf("problem loading default config: %v", err)
  915. }
  916. }
  917. if singleSearchRegex != nil {
  918. regexes["singleSearch"] = singleSearchRegex
  919. } else {
  920. for _, regex := range config.Regexes {
  921. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  922. }
  923. }
  924. whiteListBranches = config.Whitelist.Branches
  925. whiteListRepos = config.Whitelist.Repos
  926. whiteListCommits = make(map[string]bool)
  927. for _, commit := range config.Whitelist.Commits {
  928. whiteListCommits[commit] = true
  929. }
  930. for _, regex := range config.Whitelist.Files {
  931. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  932. }
  933. for _, regex := range config.Whitelist.Regexes {
  934. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  935. }
  936. return nil
  937. }
  938. // getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
  939. // If --ssh-key is set then it will attempt to load the key from that path. If not,
  940. // gitleaks will use the default $HOME/.ssh/id_rsa key
  941. func getSSHAuth() (*ssh.PublicKeys, error) {
  942. var (
  943. sshKeyPath string
  944. )
  945. if opts.SSHKey != "" {
  946. sshKeyPath = opts.SSHKey
  947. } else {
  948. c, _ := user.Current()
  949. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  950. }
  951. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  952. if err != nil {
  953. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  954. }
  955. return sshAuth, err
  956. }
  957. func (leak Leak) log() {
  958. b, _ := json.MarshalIndent(leak, "", " ")
  959. fmt.Println(string(b))
  960. }