main.go 24 KB

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