main.go 28 KB

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