main.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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. if len(leaks) == 0 {
  321. return nil
  322. }
  323. var err error
  324. log.Infof("writing report to %s", opts.Report)
  325. if strings.HasSuffix(opts.Report, ".csv") {
  326. f, err := os.Create(opts.Report)
  327. if err != nil {
  328. return err
  329. }
  330. defer f.Close()
  331. w := csv.NewWriter(f)
  332. w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "date"})
  333. for _, leak := range leaks {
  334. w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Date.Format(time.RFC3339)})
  335. }
  336. w.Flush()
  337. } else {
  338. reportJSON, _ := json.MarshalIndent(leaks, "", "\t")
  339. err = ioutil.WriteFile(opts.Report, reportJSON, 0644)
  340. }
  341. return err
  342. }
  343. // cloneRepo clones a repo to memory(default) or to disk if the --disk option is set.
  344. func cloneRepo() (*RepoDescriptor, error) {
  345. var (
  346. err error
  347. repo *git.Repository
  348. )
  349. // check if whitelist
  350. for _, re := range whiteListRepos {
  351. if re.FindString(opts.Repo) != "" {
  352. return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
  353. }
  354. }
  355. if opts.Disk {
  356. log.Infof("cloning %s", opts.Repo)
  357. cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
  358. if strings.HasPrefix(opts.Repo, "git") {
  359. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  360. URL: opts.Repo,
  361. Progress: os.Stdout,
  362. Auth: sshAuth,
  363. })
  364. } else {
  365. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  366. URL: opts.Repo,
  367. Progress: os.Stdout,
  368. })
  369. }
  370. } else if opts.RepoPath != "" {
  371. log.Infof("opening %s", opts.RepoPath)
  372. repo, err = git.PlainOpen(opts.RepoPath)
  373. } else {
  374. log.Infof("cloning %s", opts.Repo)
  375. if strings.HasPrefix(opts.Repo, "git") {
  376. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  377. URL: opts.Repo,
  378. Progress: os.Stdout,
  379. Auth: sshAuth,
  380. })
  381. } else {
  382. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  383. URL: opts.Repo,
  384. Progress: os.Stdout,
  385. })
  386. }
  387. }
  388. return &RepoDescriptor{
  389. repository: repo,
  390. path: opts.RepoPath,
  391. url: opts.Repo,
  392. name: filepath.Base(opts.Repo),
  393. err: err,
  394. }, nil
  395. }
  396. // auditGitRepo beings an audit on a git repository
  397. func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
  398. var (
  399. err error
  400. leaks []Leak
  401. )
  402. for _, re := range whiteListRepos {
  403. if re.FindString(repo.name) != "" {
  404. return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
  405. }
  406. }
  407. // clear commit cache
  408. commitMap = make(map[string]bool)
  409. refs, err := repo.repository.Storer.IterReferences()
  410. if err != nil {
  411. return leaks, err
  412. }
  413. err = refs.ForEach(func(ref *plumbing.Reference) error {
  414. if ref.Name().IsTag() {
  415. return nil
  416. }
  417. branchLeaks := auditGitReference(repo, ref)
  418. for _, leak := range branchLeaks {
  419. leaks = append(leaks, leak)
  420. }
  421. return nil
  422. })
  423. return leaks, err
  424. }
  425. // auditGitReference beings the audit for a git reference. This function will
  426. // traverse the git reference and audit each line of each diff.
  427. func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
  428. var (
  429. err error
  430. repoName string
  431. leaks []Leak
  432. commitCount int
  433. commitWg sync.WaitGroup
  434. mutex = &sync.Mutex{}
  435. semaphore chan bool
  436. )
  437. repoName = repo.name
  438. if opts.Threads != 0 {
  439. threads = opts.Threads
  440. }
  441. if opts.RepoPath != "" {
  442. threads = 1
  443. }
  444. semaphore = make(chan bool, threads)
  445. cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
  446. if err != nil {
  447. return nil
  448. }
  449. err = cIter.ForEach(func(c *object.Commit) error {
  450. if c == nil || c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
  451. cIter.Close()
  452. return errors.New("ErrStop")
  453. }
  454. commitCount = commitCount + 1
  455. if whiteListCommits[c.Hash.String()] {
  456. log.Infof("skipping commit: %s\n", c.Hash.String())
  457. return nil
  458. }
  459. // commits w/o parent (root of git the git ref)
  460. if len(c.ParentHashes) == 0 {
  461. if commitMap[c.Hash.String()] {
  462. return nil
  463. }
  464. cMutex.Lock()
  465. commitMap[c.Hash.String()] = true
  466. cMutex.Unlock()
  467. totalCommits = totalCommits + 1
  468. fIter, err := c.Files()
  469. if err != nil {
  470. return nil
  471. }
  472. err = fIter.ForEach(func(f *object.File) error {
  473. bin, err := f.IsBinary()
  474. if bin || err != nil {
  475. return nil
  476. }
  477. for _, re := range whiteListFiles {
  478. if re.FindString(f.Name) != "" {
  479. log.Infof("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.Name)
  480. return nil
  481. }
  482. }
  483. content, err := f.Contents()
  484. if err != nil {
  485. return nil
  486. }
  487. diff := gitDiff{
  488. repoName: repoName,
  489. filePath: f.Name,
  490. content: content,
  491. sha: c.Hash.String(),
  492. author: c.Author.String(),
  493. message: strings.Replace(c.Message, "\n", " ", -1),
  494. date: c.Author.When,
  495. }
  496. fileLeaks := inspect(diff)
  497. mutex.Lock()
  498. leaks = append(leaks, fileLeaks...)
  499. mutex.Unlock()
  500. return nil
  501. })
  502. return nil
  503. }
  504. skipCount := false
  505. err = c.Parents().ForEach(func(parent *object.Commit) error {
  506. // check if we've seen this diff before
  507. if commitMap[c.Hash.String()+parent.Hash.String()] {
  508. return nil
  509. }
  510. cMutex.Lock()
  511. commitMap[c.Hash.String()+parent.Hash.String()] = true
  512. cMutex.Unlock()
  513. if !skipCount {
  514. totalCommits = totalCommits + 1
  515. skipCount = true
  516. }
  517. commitWg.Add(1)
  518. semaphore <- true
  519. go func(c *object.Commit, parent *object.Commit) {
  520. var (
  521. filePath string
  522. skipFile bool
  523. )
  524. defer func() {
  525. commitWg.Done()
  526. <-semaphore
  527. if r := recover(); r != nil {
  528. log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
  529. }
  530. }()
  531. patch, err := c.Patch(parent)
  532. if err != nil {
  533. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  534. return
  535. }
  536. for _, f := range patch.FilePatches() {
  537. if f.IsBinary() {
  538. continue
  539. }
  540. skipFile = false
  541. from, to := f.Files()
  542. filePath = "???"
  543. if from != nil {
  544. filePath = from.Path()
  545. } else if to != nil {
  546. filePath = to.Path()
  547. }
  548. for _, re := range whiteListFiles {
  549. if re.FindString(filePath) != "" {
  550. log.Infof("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath)
  551. skipFile = true
  552. break
  553. }
  554. }
  555. if skipFile {
  556. continue
  557. }
  558. chunks := f.Chunks()
  559. for _, chunk := range chunks {
  560. if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete {
  561. diff := gitDiff{
  562. repoName: repoName,
  563. filePath: filePath,
  564. content: chunk.Content(),
  565. sha: c.Hash.String(),
  566. author: c.Author.String(),
  567. message: strings.Replace(c.Message, "\n", " ", -1),
  568. date: c.Author.When,
  569. }
  570. chunkLeaks := inspect(diff)
  571. for _, leak := range chunkLeaks {
  572. mutex.Lock()
  573. leaks = append(leaks, leak)
  574. mutex.Unlock()
  575. }
  576. }
  577. }
  578. }
  579. }(c, parent)
  580. return nil
  581. })
  582. return nil
  583. })
  584. commitWg.Wait()
  585. return leaks
  586. }
  587. // inspect will parse each line of the git diff's content against a set of regexes or
  588. // a set of regexes set by the config (see gitleaks.toml for example). This function
  589. // will skip lines that include a whitelisted regex. A list of leaks is returned.
  590. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
  591. func inspect(diff gitDiff) []Leak {
  592. var (
  593. leaks []Leak
  594. skipLine bool
  595. )
  596. lines := strings.Split(diff.content, "\n")
  597. for _, line := range lines {
  598. skipLine = false
  599. for leakType, re := range regexes {
  600. match := re.FindString(line)
  601. if match == "" {
  602. continue
  603. }
  604. if skipLine = isLineWhitelisted(line); skipLine {
  605. break
  606. }
  607. leaks = addLeak(leaks, line, match, leakType, diff)
  608. }
  609. if !skipLine && (opts.Entropy > 0 || len(entropyRanges) != 0) {
  610. words := strings.Fields(line)
  611. for _, word := range words {
  612. entropy := getShannonEntropy(word)
  613. // Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type
  614. // was found above, since regex checks are expensive.
  615. if !entropyIsHighEnough(entropy) {
  616. continue
  617. }
  618. // If either the line is whitelisted or the line fails the noiseReduction check (when enabled),
  619. // then we can skip checking the rest of the line for high entropy words.
  620. if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine {
  621. break
  622. }
  623. leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
  624. }
  625. }
  626. }
  627. return leaks
  628. }
  629. // isLineWhitelisted returns true iff the line is matched by at least one of the whiteListRegexes.
  630. func isLineWhitelisted(line string) bool {
  631. for _, wRe := range whiteListRegexes {
  632. whitelistMatch := wRe.FindString(line)
  633. if whitelistMatch != "" {
  634. return true
  635. }
  636. }
  637. return false
  638. }
  639. // addLeak is helper for func inspect() to append leaks if found during a diff check.
  640. func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
  641. leak := Leak{
  642. Line: line,
  643. Commit: diff.sha,
  644. Offender: offender,
  645. Type: leakType,
  646. Author: diff.author,
  647. File: diff.filePath,
  648. Repo: diff.repoName,
  649. Message: diff.message,
  650. Date: diff.date,
  651. }
  652. if opts.Redact {
  653. leak.Offender = "REDACTED"
  654. leak.Line = strings.Replace(line, offender, "REDACTED", -1)
  655. }
  656. if opts.Verbose {
  657. leak.log()
  658. }
  659. leaks = append(leaks, leak)
  660. return leaks
  661. }
  662. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  663. func getShannonEntropy(data string) (entropy float64) {
  664. if data == "" {
  665. return 0
  666. }
  667. charCounts := make(map[rune]int)
  668. for _, char := range data {
  669. charCounts[char]++
  670. }
  671. invLength := 1.0 / float64(len(data))
  672. for _, count := range charCounts {
  673. freq := float64(count) * invLength
  674. entropy -= freq * math.Log2(freq)
  675. }
  676. return entropy
  677. }
  678. func entropyIsHighEnough(entropy float64) bool {
  679. if entropy >= opts.Entropy && len(entropyRanges) == 0 {
  680. return true
  681. }
  682. if len(entropyRanges) != 0 {
  683. for _, eR := range entropyRanges {
  684. if entropy > eR.v1 && entropy < eR.v2 {
  685. return true
  686. }
  687. }
  688. }
  689. return false
  690. }
  691. func highEntropyLineIsALeak(line string) bool {
  692. if !opts.NoiseReduction {
  693. return true
  694. }
  695. for _, re := range entropyRegexes {
  696. if re.FindString(line) != "" {
  697. return true
  698. }
  699. }
  700. return false
  701. }
  702. // discoverRepos walks all the children of `path`. If a child directory
  703. // contain a .git file then that repo will be added to the list of repos returned
  704. func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
  705. var (
  706. err error
  707. repos []*RepoDescriptor
  708. )
  709. files, err := ioutil.ReadDir(ownerPath)
  710. if err != nil {
  711. return repos, err
  712. }
  713. for _, f := range files {
  714. if f.IsDir() {
  715. repoPath := path.Join(ownerPath, f.Name())
  716. r, err := git.PlainOpen(repoPath)
  717. if err != nil {
  718. continue
  719. }
  720. repos = append(repos, &RepoDescriptor{
  721. repository: r,
  722. name: f.Name(),
  723. path: repoPath,
  724. })
  725. }
  726. }
  727. return repos, err
  728. }
  729. // setLogLevel sets log level for gitleaks. Default is Warning
  730. func setLogs() {
  731. switch opts.Log {
  732. case "info":
  733. log.SetLevel(log.InfoLevel)
  734. case "debug":
  735. log.SetLevel(log.DebugLevel)
  736. case "warn":
  737. log.SetLevel(log.WarnLevel)
  738. default:
  739. log.SetLevel(log.InfoLevel)
  740. }
  741. log.SetFormatter(&log.TextFormatter{
  742. FullTimestamp: true,
  743. })
  744. }
  745. // optsGuard prevents invalid options
  746. func optsGuard() error {
  747. var err error
  748. if opts.GithubOrg != "" && opts.GithubUser != "" {
  749. return fmt.Errorf("github user and organization set")
  750. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  751. return fmt.Errorf("github organization set and local owner path")
  752. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  753. return fmt.Errorf("github user set and local owner path")
  754. }
  755. if opts.Threads > runtime.GOMAXPROCS(0) {
  756. return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
  757. }
  758. // do the URL Parse and error checking here, so we can skip it later
  759. // empty string is OK, it will default to the public github URL.
  760. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  761. if !strings.HasSuffix(opts.GithubURL, "/") {
  762. opts.GithubURL += "/"
  763. }
  764. ghURL, err := url.Parse(opts.GithubURL)
  765. if err != nil {
  766. return err
  767. }
  768. tcpPort := "443"
  769. if ghURL.Scheme == "http" {
  770. tcpPort = "80"
  771. }
  772. timeout := time.Duration(1 * time.Second)
  773. _, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
  774. if err != nil {
  775. return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
  776. }
  777. }
  778. if opts.SingleSearch != "" {
  779. singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
  780. if err != nil {
  781. return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
  782. }
  783. }
  784. if opts.Entropy > 8 {
  785. return fmt.Errorf("The maximum level of entropy is 8")
  786. }
  787. if opts.Report != "" {
  788. if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
  789. return fmt.Errorf("Report should be a .json or .csv file")
  790. }
  791. dirPath := filepath.Dir(opts.Report)
  792. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  793. return fmt.Errorf("%s does not exist", dirPath)
  794. }
  795. }
  796. return nil
  797. }
  798. // loadToml loads of the toml config containing regexes and whitelists.
  799. // This function will first look if the configPath is set and load the config
  800. // from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
  801. // env var. If that is not set, then gitleaks will continue with the default configs
  802. // specified by the const var at the top `defaultConfig`
  803. func loadToml() error {
  804. var (
  805. config Config
  806. configPath string
  807. )
  808. if opts.ConfigPath != "" {
  809. configPath = opts.ConfigPath
  810. _, err := os.Stat(configPath)
  811. if err != nil {
  812. return fmt.Errorf("no gitleaks config at %s", configPath)
  813. }
  814. } else {
  815. configPath = os.Getenv("GITLEAKS_CONFIG")
  816. }
  817. if configPath != "" {
  818. if _, err := toml.DecodeFile(configPath, &config); err != nil {
  819. return fmt.Errorf("problem loading config: %v", err)
  820. }
  821. } else {
  822. _, err := toml.Decode(defaultConfig, &config)
  823. if err != nil {
  824. return fmt.Errorf("problem loading default config: %v", err)
  825. }
  826. }
  827. if len(config.Misc.Entropy) != 0 {
  828. err := entropyLimits(config.Misc.Entropy)
  829. if err != nil {
  830. return err
  831. }
  832. }
  833. for _, regex := range config.Entropy.LineRegexes {
  834. entropyRegexes = append(entropyRegexes, regexp.MustCompile(regex))
  835. }
  836. if singleSearchRegex != nil {
  837. regexes["singleSearch"] = singleSearchRegex
  838. } else {
  839. for _, regex := range config.Regexes {
  840. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  841. }
  842. }
  843. whiteListCommits = make(map[string]bool)
  844. for _, commit := range config.Whitelist.Commits {
  845. whiteListCommits[commit] = true
  846. }
  847. for _, regex := range config.Whitelist.Files {
  848. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  849. }
  850. for _, regex := range config.Whitelist.Regexes {
  851. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  852. }
  853. for _, regex := range config.Whitelist.Repos {
  854. whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
  855. }
  856. return nil
  857. }
  858. // entropyLimits hydrates entropyRanges which allows for fine tuning entropy checking
  859. func entropyLimits(entropyLimitStr []string) error {
  860. for _, span := range entropyLimitStr {
  861. split := strings.Split(span, "-")
  862. v1, err := strconv.ParseFloat(split[0], 64)
  863. if err != nil {
  864. return err
  865. }
  866. v2, err := strconv.ParseFloat(split[1], 64)
  867. if err != nil {
  868. return err
  869. }
  870. if v1 > v2 {
  871. return fmt.Errorf("entropy range must be ascending")
  872. }
  873. r := entropyRange{
  874. v1: v1,
  875. v2: v2,
  876. }
  877. if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
  878. return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
  879. }
  880. entropyRanges = append(entropyRanges, r)
  881. }
  882. return nil
  883. }
  884. // getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
  885. // If --ssh-key is set then it will attempt to load the key from that path. If not,
  886. // gitleaks will use the default $HOME/.ssh/id_rsa key
  887. func getSSHAuth() (*ssh.PublicKeys, error) {
  888. var (
  889. sshKeyPath string
  890. )
  891. if opts.SSHKey != "" {
  892. sshKeyPath = opts.SSHKey
  893. } else {
  894. // try grabbing default
  895. c, err := user.Current()
  896. if err != nil {
  897. return nil, nil
  898. }
  899. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  900. }
  901. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  902. if err != nil {
  903. if strings.HasPrefix(opts.Repo, "git") {
  904. // if you are attempting to clone a git repo via ssh and supply a bad ssh key,
  905. // the clone will fail.
  906. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  907. }
  908. }
  909. return sshAuth, nil
  910. }
  911. func (leak Leak) log() {
  912. b, _ := json.MarshalIndent(leak, "", " ")
  913. fmt.Println(string(b))
  914. }