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