main.go 24 KB

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