main.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/csv"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "math"
  10. "net"
  11. "net/url"
  12. "os"
  13. "os/user"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. "gopkg.in/src-d/go-git.v4/plumbing"
  23. "gopkg.in/src-d/go-git.v4/plumbing/object"
  24. "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
  25. "gopkg.in/src-d/go-git.v4/storage/memory"
  26. "github.com/BurntSushi/toml"
  27. "github.com/google/go-github/github"
  28. "github.com/hako/durafmt"
  29. flags "github.com/jessevdk/go-flags"
  30. log "github.com/sirupsen/logrus"
  31. git "gopkg.in/src-d/go-git.v4"
  32. )
  33. // Leak represents a leaked secret or regex match.
  34. type Leak struct {
  35. Line string `json:"line"`
  36. Commit string `json:"commit"`
  37. Offender string `json:"offender"`
  38. Type string `json:"reason"`
  39. Message string `json:"commitMsg"`
  40. Author string `json:"author"`
  41. File string `json:"file"`
  42. Repo string `json:"repo"`
  43. Date time.Time `json:"date"`
  44. }
  45. // RepoDescriptor contains a src-d git repository and other data about the repo
  46. type RepoDescriptor struct {
  47. path string
  48. url string
  49. name string
  50. repository *git.Repository
  51. err error
  52. }
  53. // Options for gitleaks
  54. type Options struct {
  55. // remote target options
  56. Repo string `short:"r" long:"repo" description:"Repo url to audit"`
  57. GithubUser string `long:"github-user" description:"Github user to audit"`
  58. GithubOrg string `long:"github-org" description:"Github organization to audit"`
  59. GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"`
  60. GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
  61. /*
  62. TODO:
  63. GitLabUser string `long:"gitlab-user" description:"User url to audit"`
  64. GitLabOrg string `long:"gitlab-org" description:"Organization url to audit"`
  65. */
  66. Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
  67. Depth int `long:"depth" description:"maximum commit depth"`
  68. // local target option
  69. RepoPath string `long:"repo-path" description:"Path to repo"`
  70. OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
  71. // Process options
  72. Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
  73. Disk bool `long:"disk" description:"Clones repo(s) to disk"`
  74. SingleSearch string `long:"single-search" description:"single regular expression to search for"`
  75. ConfigPath string `long:"config" description:"path to gitleaks config"`
  76. SSHKey string `long:"ssh-key" description:"path to ssh key"`
  77. ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
  78. Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
  79. // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
  80. // Output options
  81. Log string `short:"l" long:"log" description:"log level"`
  82. Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
  83. Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
  84. Redact bool `long:"redact" description:"redact secrets from log messages and report"`
  85. Version bool `long:"version" description:"version number"`
  86. SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
  87. }
  88. // Config struct for regexes matching and whitelisting
  89. type Config struct {
  90. Regexes []struct {
  91. Description string
  92. Regex string
  93. }
  94. Whitelist struct {
  95. Files []string
  96. Regexes []string
  97. Commits []string
  98. Repos []string
  99. }
  100. Misc struct {
  101. Entropy []string
  102. }
  103. }
  104. type gitDiff struct {
  105. content string
  106. commit *object.Commit
  107. filePath string
  108. repoName string
  109. githubCommit *github.RepositoryCommit
  110. sha string
  111. message string
  112. author string
  113. date time.Time
  114. }
  115. type entropyRange struct {
  116. v1 float64
  117. v2 float64
  118. }
  119. const defaultGithubURL = "https://api.github.com/"
  120. const version = "1.19.1"
  121. const errExit = 2
  122. const leakExit = 1
  123. const defaultConfig = `
  124. # This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
  125. # The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
  126. # is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
  127. # configurations from that path. Gitleaks does not whitelist anything by default.
  128. title = "gitleaks config"
  129. # add regexes to the regex table
  130. [[regexes]]
  131. description = "AWS"
  132. regex = '''AKIA[0-9A-Z]{16}'''
  133. [[regexes]]
  134. description = "PKCS8"
  135. regex = '''-----BEGIN PRIVATE KEY-----'''
  136. [[regexes]]
  137. description = "RSA"
  138. regex = '''-----BEGIN RSA PRIVATE KEY-----'''
  139. [[regexes]]
  140. description = "SSH"
  141. regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
  142. [[regexes]]
  143. description = "PGP"
  144. regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
  145. [[regexes]]
  146. description = "Facebook"
  147. regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]'''
  148. [[regexes]]
  149. description = "Twitter"
  150. regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]'''
  151. [[regexes]]
  152. description = "Github"
  153. regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
  154. [[regexes]]
  155. description = "Slack"
  156. regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
  157. [whitelist]
  158. files = [
  159. "(.*?)(jpg|gif|doc|pdf|bin)$"
  160. ]
  161. #commits = [
  162. # "BADHA5H1",
  163. # "BADHA5H2",
  164. #]
  165. #repos = [
  166. # "mygoodrepo"
  167. #]
  168. [misc]
  169. #entropy = [
  170. # "3.3-4.30"
  171. # "6.0-8.0
  172. #]
  173. `
  174. var (
  175. opts Options
  176. regexes map[string]*regexp.Regexp
  177. singleSearchRegex *regexp.Regexp
  178. whiteListRegexes []*regexp.Regexp
  179. whiteListFiles []*regexp.Regexp
  180. whiteListCommits map[string]bool
  181. whiteListRepos []*regexp.Regexp
  182. entropyRanges []entropyRange
  183. fileDiffRegex *regexp.Regexp
  184. sshAuth *ssh.PublicKeys
  185. dir string
  186. threads int
  187. totalCommits int64
  188. commitMap = make(map[string]bool)
  189. cMutex = &sync.Mutex{}
  190. )
  191. func init() {
  192. log.SetOutput(os.Stdout)
  193. // threads = runtime.GOMAXPROCS(0) / 2
  194. threads = 1
  195. regexes = make(map[string]*regexp.Regexp)
  196. whiteListCommits = make(map[string]bool)
  197. }
  198. func main() {
  199. parser := flags.NewParser(&opts, flags.Default)
  200. _, err := parser.Parse()
  201. if err != nil {
  202. if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
  203. os.Exit(0)
  204. }
  205. }
  206. if len(os.Args) == 1 {
  207. parser.WriteHelp(os.Stdout)
  208. os.Exit(0)
  209. }
  210. if opts.Version {
  211. fmt.Println(version)
  212. os.Exit(0)
  213. }
  214. if opts.SampleConfig {
  215. fmt.Println(defaultConfig)
  216. os.Exit(0)
  217. }
  218. now := time.Now()
  219. leaks, err := run()
  220. if err != nil {
  221. if strings.Contains(err.Error(), "whitelisted") {
  222. log.Info(err.Error())
  223. os.Exit(0)
  224. }
  225. log.Error(err)
  226. os.Exit(errExit)
  227. }
  228. if opts.Report != "" {
  229. writeReport(leaks)
  230. }
  231. if len(leaks) != 0 {
  232. log.Warnf("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
  233. os.Exit(leakExit)
  234. } else {
  235. log.Infof("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
  236. }
  237. }
  238. // run parses options and kicks off the audit
  239. func run() ([]Leak, error) {
  240. var leaks []Leak
  241. setLogs()
  242. err := optsGuard()
  243. if err != nil {
  244. return nil, err
  245. }
  246. err = loadToml()
  247. if err != nil {
  248. return nil, err
  249. }
  250. sshAuth, err = getSSHAuth()
  251. if err != nil {
  252. return leaks, err
  253. }
  254. if opts.Disk {
  255. // temporary directory where all the gitleaks plain clones will reside
  256. dir, err = ioutil.TempDir("", "gitleaks")
  257. defer os.RemoveAll(dir)
  258. if err != nil {
  259. return nil, err
  260. }
  261. }
  262. // start audits
  263. if opts.Repo != "" || opts.RepoPath != "" {
  264. // Audit a single remote repo or a local repo.
  265. repo, err := cloneRepo()
  266. if err != nil {
  267. return leaks, err
  268. }
  269. return auditGitRepo(repo)
  270. } else if opts.OwnerPath != "" {
  271. // Audit local repos. Gitleaks will look for all child directories of OwnerPath for
  272. // git repos and perform an audit on said repos.
  273. repos, err := discoverRepos(opts.OwnerPath)
  274. if err != nil {
  275. return leaks, err
  276. }
  277. for _, repo := range repos {
  278. leaksFromRepo, err := auditGitRepo(repo)
  279. if err != nil {
  280. return leaks, err
  281. }
  282. leaks = append(leaksFromRepo, leaks...)
  283. }
  284. } else if opts.GithubOrg != "" || opts.GithubUser != "" {
  285. // Audit a github owner -- a user or organization.
  286. leaks, err = auditGithubRepos()
  287. if err != nil {
  288. return leaks, err
  289. }
  290. } else if opts.GithubPR != "" {
  291. return auditGithubPR()
  292. }
  293. return leaks, nil
  294. }
  295. // writeReport writes a report to a file specified in the --report= option.
  296. // Default format for report is JSON. You can use the --csv option to write the report as a csv
  297. func writeReport(leaks []Leak) error {
  298. var err error
  299. log.Infof("writing report to %s", opts.Report)
  300. if strings.HasSuffix(opts.Report, ".csv") {
  301. f, err := os.Create(opts.Report)
  302. if err != nil {
  303. return err
  304. }
  305. defer f.Close()
  306. w := csv.NewWriter(f)
  307. w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "date"})
  308. for _, leak := range leaks {
  309. w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Date.Format(time.RFC3339)})
  310. }
  311. w.Flush()
  312. } else {
  313. reportJSON, _ := json.MarshalIndent(leaks, "", "\t")
  314. err = ioutil.WriteFile(opts.Report, reportJSON, 0644)
  315. }
  316. return err
  317. }
  318. // cloneRepo clones a repo to memory(default) or to disk if the --disk option is set.
  319. func cloneRepo() (*RepoDescriptor, error) {
  320. var (
  321. err error
  322. repo *git.Repository
  323. )
  324. // check if whitelist
  325. for _, re := range whiteListRepos {
  326. if re.FindString(opts.Repo) != "" {
  327. return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
  328. }
  329. }
  330. if opts.Disk {
  331. log.Infof("cloning %s", opts.Repo)
  332. cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
  333. if strings.HasPrefix(opts.Repo, "git") {
  334. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  335. URL: opts.Repo,
  336. Progress: os.Stdout,
  337. Auth: sshAuth,
  338. })
  339. } else {
  340. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  341. URL: opts.Repo,
  342. Progress: os.Stdout,
  343. })
  344. }
  345. } else if opts.RepoPath != "" {
  346. log.Infof("opening %s", opts.RepoPath)
  347. repo, err = git.PlainOpen(opts.RepoPath)
  348. } else {
  349. log.Infof("cloning %s", opts.Repo)
  350. if strings.HasPrefix(opts.Repo, "git") {
  351. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  352. URL: opts.Repo,
  353. Progress: os.Stdout,
  354. Auth: sshAuth,
  355. })
  356. } else {
  357. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  358. URL: opts.Repo,
  359. Progress: os.Stdout,
  360. })
  361. }
  362. }
  363. return &RepoDescriptor{
  364. repository: repo,
  365. path: opts.RepoPath,
  366. url: opts.Repo,
  367. name: filepath.Base(opts.Repo),
  368. err: err,
  369. }, nil
  370. }
  371. // auditGitRepo beings an audit on a git repository
  372. func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
  373. var (
  374. err error
  375. leaks []Leak
  376. )
  377. for _, re := range whiteListRepos {
  378. if re.FindString(repo.name) != "" {
  379. return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
  380. }
  381. }
  382. // clear commit cache
  383. commitMap = make(map[string]bool)
  384. refs, err := repo.repository.Storer.IterReferences()
  385. if err != nil {
  386. return leaks, err
  387. }
  388. err = refs.ForEach(func(ref *plumbing.Reference) error {
  389. if ref.Name().IsTag() {
  390. return nil
  391. }
  392. branchLeaks := auditGitReference(repo, ref)
  393. for _, leak := range branchLeaks {
  394. leaks = append(leaks, leak)
  395. }
  396. return nil
  397. })
  398. return leaks, err
  399. }
  400. // auditGitReference beings the audit for a git reference. This function will
  401. // traverse the git reference and audit each line of each diff.
  402. func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
  403. var (
  404. err error
  405. repoName string
  406. leaks []Leak
  407. commitCount int
  408. commitWg sync.WaitGroup
  409. mutex = &sync.Mutex{}
  410. semaphore chan bool
  411. )
  412. repoName = repo.name
  413. if opts.Threads != 0 {
  414. threads = opts.Threads
  415. }
  416. if opts.RepoPath != "" {
  417. threads = 1
  418. }
  419. semaphore = make(chan bool, threads)
  420. cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
  421. if err != nil {
  422. return nil
  423. }
  424. err = cIter.ForEach(func(c *object.Commit) error {
  425. if commitMap[c.Hash.String()] {
  426. return nil
  427. }
  428. cMutex.Lock()
  429. commitMap[c.Hash.String()] = true
  430. cMutex.Unlock()
  431. if c == nil || c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
  432. cIter.Close()
  433. return errors.New("ErrStop")
  434. }
  435. commitCount = commitCount + 1
  436. totalCommits = totalCommits + 1
  437. if whiteListCommits[c.Hash.String()] {
  438. log.Infof("skipping commit: %s\n", c.Hash.String())
  439. return nil
  440. }
  441. err = c.Parents().ForEach(func(parent *object.Commit) error {
  442. commitWg.Add(1)
  443. semaphore <- true
  444. go func(c *object.Commit, parent *object.Commit) {
  445. var (
  446. filePath string
  447. skipFile bool
  448. )
  449. defer func() {
  450. commitWg.Done()
  451. <-semaphore
  452. if r := recover(); r != nil {
  453. log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
  454. }
  455. }()
  456. patch, err := c.Patch(parent)
  457. if err != nil {
  458. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  459. return
  460. }
  461. for _, f := range patch.FilePatches() {
  462. if f.IsBinary() {
  463. continue
  464. }
  465. skipFile = false
  466. from, to := f.Files()
  467. filePath = "???"
  468. if from != nil {
  469. filePath = from.Path()
  470. } else if to != nil {
  471. filePath = to.Path()
  472. }
  473. for _, re := range whiteListFiles {
  474. if re.FindString(filePath) != "" {
  475. skipFile = true
  476. break
  477. }
  478. }
  479. if skipFile {
  480. continue
  481. }
  482. chunks := f.Chunks()
  483. for _, chunk := range chunks {
  484. if chunk.Type() == 1 || chunk.Type() == 2 {
  485. diff := gitDiff{
  486. repoName: repoName,
  487. filePath: filePath,
  488. content: chunk.Content(),
  489. sha: c.Hash.String(),
  490. author: c.Author.String(),
  491. message: strings.Replace(c.Message, "\n", " ", -1),
  492. date: c.Author.When,
  493. }
  494. chunkLeaks := inspect(diff)
  495. for _, leak := range chunkLeaks {
  496. mutex.Lock()
  497. leaks = append(leaks, leak)
  498. mutex.Unlock()
  499. }
  500. }
  501. }
  502. }
  503. }(c, parent)
  504. return nil
  505. })
  506. return nil
  507. })
  508. commitWg.Wait()
  509. return leaks
  510. }
  511. // inspect will parse each line of the git diff's content against a set of regexes or
  512. // a set of regexes set by the config (see gitleaks.toml for example). This function
  513. // will skip lines that include a whitelisted regex. A list of leaks is returned.
  514. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
  515. func inspect(diff gitDiff) []Leak {
  516. lines := strings.Split(diff.content, "\n")
  517. var (
  518. leaks []Leak
  519. skipLine bool
  520. )
  521. for _, line := range lines {
  522. skipLine = false
  523. for leakType, re := range regexes {
  524. match := re.FindString(line)
  525. if match == "" {
  526. continue
  527. }
  528. // if offender matches whitelist regex, ignore it
  529. for _, wRe := range whiteListRegexes {
  530. whitelistMatch := wRe.FindString(line)
  531. if whitelistMatch != "" {
  532. skipLine = true
  533. break
  534. }
  535. }
  536. if skipLine {
  537. break
  538. }
  539. leaks = addLeak(leaks, line, match, leakType, diff)
  540. }
  541. if opts.Entropy > 0 || len(entropyRanges) != 0 {
  542. entropyLeak := false
  543. words := strings.Fields(line)
  544. for _, word := range words {
  545. entropy := getShannonEntropy(word)
  546. if entropy >= opts.Entropy && len(entropyRanges) == 0 {
  547. entropyLeak = true
  548. }
  549. if len(entropyRanges) != 0 {
  550. for _, eR := range entropyRanges {
  551. if entropy > eR.v1 && entropy < eR.v2 {
  552. entropyLeak = true
  553. }
  554. }
  555. }
  556. if entropyLeak {
  557. leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
  558. entropyLeak = false
  559. }
  560. }
  561. }
  562. }
  563. return leaks
  564. }
  565. // addLeak is helper for func inspect() to append leaks if found during a diff check.
  566. func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
  567. leak := Leak{
  568. Line: line,
  569. Commit: diff.sha,
  570. Offender: offender,
  571. Type: leakType,
  572. Author: diff.author,
  573. File: diff.filePath,
  574. Repo: diff.repoName,
  575. Message: diff.message,
  576. Date: diff.date,
  577. }
  578. if opts.Redact {
  579. leak.Offender = "REDACTED"
  580. leak.Line = "REDACTED"
  581. }
  582. if opts.Verbose {
  583. leak.log()
  584. }
  585. leaks = append(leaks, leak)
  586. return leaks
  587. }
  588. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  589. func getShannonEntropy(data string) (entropy float64) {
  590. if data == "" {
  591. return 0
  592. }
  593. charCounts := make(map[rune]int)
  594. for _, char := range data {
  595. charCounts[char]++
  596. }
  597. invLength := 1.0 / float64(len(data))
  598. for _, count := range charCounts {
  599. freq := float64(count) * invLength
  600. entropy -= freq * math.Log2(freq)
  601. }
  602. return entropy
  603. }
  604. // discoverRepos walks all the children of `path`. If a child directory
  605. // contain a .git file then that repo will be added to the list of repos returned
  606. func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
  607. var (
  608. err error
  609. repos []*RepoDescriptor
  610. )
  611. files, err := ioutil.ReadDir(ownerPath)
  612. if err != nil {
  613. return repos, err
  614. }
  615. for _, f := range files {
  616. if f.IsDir() {
  617. repoPath := path.Join(ownerPath, f.Name())
  618. r, err := git.PlainOpen(repoPath)
  619. if err != nil {
  620. continue
  621. }
  622. repos = append(repos, &RepoDescriptor{
  623. repository: r,
  624. name: f.Name(),
  625. path: repoPath,
  626. })
  627. }
  628. }
  629. return repos, err
  630. }
  631. // setLogLevel sets log level for gitleaks. Default is Warning
  632. func setLogs() {
  633. switch opts.Log {
  634. case "info":
  635. log.SetLevel(log.InfoLevel)
  636. case "debug":
  637. log.SetLevel(log.DebugLevel)
  638. case "warn":
  639. log.SetLevel(log.WarnLevel)
  640. default:
  641. log.SetLevel(log.InfoLevel)
  642. }
  643. log.SetFormatter(&log.TextFormatter{
  644. FullTimestamp: true,
  645. })
  646. }
  647. // optsGuard prevents invalid options
  648. func optsGuard() error {
  649. var err error
  650. if opts.GithubOrg != "" && opts.GithubUser != "" {
  651. return fmt.Errorf("github user and organization set")
  652. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  653. return fmt.Errorf("github organization set and local owner path")
  654. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  655. return fmt.Errorf("github user set and local owner path")
  656. }
  657. if opts.Threads > runtime.GOMAXPROCS(0) {
  658. return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
  659. }
  660. // do the URL Parse and error checking here, so we can skip it later
  661. // empty string is OK, it will default to the public github URL.
  662. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  663. if !strings.HasSuffix(opts.GithubURL, "/") {
  664. opts.GithubURL += "/"
  665. }
  666. ghURL, err := url.Parse(opts.GithubURL)
  667. if err != nil {
  668. return err
  669. }
  670. tcpPort := "443"
  671. if ghURL.Scheme == "http" {
  672. tcpPort = "80"
  673. }
  674. timeout := time.Duration(1 * time.Second)
  675. _, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
  676. if err != nil {
  677. return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
  678. }
  679. }
  680. if opts.SingleSearch != "" {
  681. singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
  682. if err != nil {
  683. return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
  684. }
  685. }
  686. if opts.Entropy > 8 {
  687. return fmt.Errorf("The maximum level of entropy is 8")
  688. }
  689. if opts.Report != "" {
  690. if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
  691. return fmt.Errorf("Report should be a .json or .csv file")
  692. }
  693. dirPath := filepath.Dir(opts.Report)
  694. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  695. return fmt.Errorf("%s does not exist", dirPath)
  696. }
  697. }
  698. return nil
  699. }
  700. // loadToml loads of the toml config containing regexes and whitelists.
  701. // This function will first look if the configPath is set and load the config
  702. // from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
  703. // env var. If that is not set, then gitleaks will continue with the default configs
  704. // specified by the const var at the top `defaultConfig`
  705. func loadToml() error {
  706. var (
  707. config Config
  708. configPath string
  709. )
  710. if opts.ConfigPath != "" {
  711. configPath = opts.ConfigPath
  712. _, err := os.Stat(configPath)
  713. if err != nil {
  714. return fmt.Errorf("no gitleaks config at %s", configPath)
  715. }
  716. } else {
  717. configPath = os.Getenv("GITLEAKS_CONFIG")
  718. }
  719. if configPath != "" {
  720. if _, err := toml.DecodeFile(configPath, &config); err != nil {
  721. return fmt.Errorf("problem loading config: %v", err)
  722. }
  723. } else {
  724. _, err := toml.Decode(defaultConfig, &config)
  725. if err != nil {
  726. return fmt.Errorf("problem loading default config: %v", err)
  727. }
  728. }
  729. if len(config.Misc.Entropy) != 0 {
  730. err := entropyLimits(config.Misc.Entropy)
  731. if err != nil {
  732. return err
  733. }
  734. }
  735. if singleSearchRegex != nil {
  736. regexes["singleSearch"] = singleSearchRegex
  737. } else {
  738. for _, regex := range config.Regexes {
  739. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  740. }
  741. }
  742. whiteListCommits = make(map[string]bool)
  743. for _, commit := range config.Whitelist.Commits {
  744. whiteListCommits[commit] = true
  745. }
  746. for _, regex := range config.Whitelist.Files {
  747. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  748. }
  749. for _, regex := range config.Whitelist.Regexes {
  750. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  751. }
  752. for _, regex := range config.Whitelist.Repos {
  753. whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
  754. }
  755. return nil
  756. }
  757. // entropyLimits hydrates entropyRanges which allows for fine tuning entropy checking
  758. func entropyLimits(entropyLimitStr []string) error {
  759. for _, span := range entropyLimitStr {
  760. split := strings.Split(span, "-")
  761. v1, err := strconv.ParseFloat(split[0], 64)
  762. if err != nil {
  763. return err
  764. }
  765. v2, err := strconv.ParseFloat(split[1], 64)
  766. if err != nil {
  767. return err
  768. }
  769. if v1 > v2 {
  770. return fmt.Errorf("entropy range must be ascending")
  771. }
  772. r := entropyRange{
  773. v1: v1,
  774. v2: v2,
  775. }
  776. if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
  777. return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
  778. }
  779. entropyRanges = append(entropyRanges, r)
  780. }
  781. return nil
  782. }
  783. // getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
  784. // If --ssh-key is set then it will attempt to load the key from that path. If not,
  785. // gitleaks will use the default $HOME/.ssh/id_rsa key
  786. func getSSHAuth() (*ssh.PublicKeys, error) {
  787. var (
  788. sshKeyPath string
  789. )
  790. if opts.SSHKey != "" {
  791. sshKeyPath = opts.SSHKey
  792. } else {
  793. // try grabbing default
  794. c, err := user.Current()
  795. if err != nil {
  796. return nil, nil
  797. }
  798. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  799. }
  800. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  801. if err != nil {
  802. if strings.HasPrefix(opts.Repo, "git") {
  803. // if you are attempting to clone a git repo via ssh and supply a bad ssh key,
  804. // the clone will fail.
  805. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  806. }
  807. }
  808. return sshAuth, nil
  809. }
  810. func (leak Leak) log() {
  811. b, _ := json.MarshalIndent(leak, "", " ")
  812. fmt.Println(string(b))
  813. }