main.go 29 KB

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