main.go 25 KB

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