main.go 26 KB

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