main.go 24 KB

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