main.go 25 KB

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