main.go 25 KB

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