main.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/csv"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "math"
  10. "net"
  11. "net/url"
  12. "os"
  13. "os/user"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. "gopkg.in/src-d/go-git.v4/plumbing"
  23. diffType "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
  24. "gopkg.in/src-d/go-git.v4/plumbing/object"
  25. "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
  26. "gopkg.in/src-d/go-git.v4/storage/memory"
  27. "github.com/BurntSushi/toml"
  28. "github.com/google/go-github/github"
  29. "github.com/hako/durafmt"
  30. "github.com/jessevdk/go-flags"
  31. log "github.com/sirupsen/logrus"
  32. "gopkg.in/src-d/go-git.v4"
  33. )
  34. // Leak represents a leaked secret or regex match.
  35. type Leak struct {
  36. Line string `json:"line"`
  37. Commit string `json:"commit"`
  38. Offender string `json:"offender"`
  39. Type string `json:"reason"`
  40. Message string `json:"commitMsg"`
  41. Author string `json:"author"`
  42. File string `json:"file"`
  43. Repo string `json:"repo"`
  44. Date time.Time `json:"date"`
  45. }
  46. // RepoDescriptor contains a src-d git repository and other data about the repo
  47. type RepoDescriptor struct {
  48. path string
  49. url string
  50. name string
  51. repository *git.Repository
  52. err error
  53. }
  54. // Options for gitleaks
  55. type Options struct {
  56. // remote target options
  57. Repo string `short:"r" long:"repo" description:"Repo url to audit"`
  58. GithubUser string `long:"github-user" description:"Github user to audit"`
  59. GithubOrg string `long:"github-org" description:"Github organization to audit"`
  60. GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"`
  61. GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
  62. GitLabUser string `long:"gitlab-user" description:"GitLab user ID to audit"`
  63. GitLabOrg string `long:"gitlab-org" description:"GitLab group ID to audit"`
  64. Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
  65. Depth int `long:"depth" description:"maximum commit depth"`
  66. // local target option
  67. RepoPath string `long:"repo-path" description:"Path to repo"`
  68. OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
  69. // Process options
  70. Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
  71. Disk bool `long:"disk" description:"Clones repo(s) to disk"`
  72. SingleSearch string `long:"single-search" description:"single regular expression to search for"`
  73. ConfigPath string `long:"config" description:"path to gitleaks config"`
  74. SSHKey string `long:"ssh-key" description:"path to ssh key"`
  75. ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
  76. Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
  77. NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"`
  78. RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""`
  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.23.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. var (
  340. f *os.File
  341. encoder *json.Encoder
  342. )
  343. f, err := os.Create(opts.Report)
  344. if err != nil {
  345. return err
  346. }
  347. defer f.Close()
  348. encoder = json.NewEncoder(f)
  349. encoder.SetIndent("", "\t")
  350. if _, err := f.WriteString("[\n"); err != nil {
  351. return err
  352. }
  353. for i := 0; i < len(leaks); i++ {
  354. if err := encoder.Encode(leaks[i]); err != nil {
  355. return err
  356. }
  357. // for all but the last leak, seek back and overwrite the newline appended by Encode() with comma & newline
  358. if i+1 < len(leaks) {
  359. if _, err := f.Seek(-1, 1); err != nil {
  360. return err
  361. }
  362. if _, err := f.WriteString(",\n"); err != nil {
  363. return err
  364. }
  365. }
  366. }
  367. if _, err := f.WriteString("]"); err != nil {
  368. return err
  369. }
  370. if err := f.Sync(); err != nil {
  371. log.Error(err)
  372. return err
  373. }
  374. }
  375. return err
  376. }
  377. // cloneRepo clones a repo to memory(default) or to disk if the --disk option is set.
  378. func cloneRepo() (*RepoDescriptor, error) {
  379. var (
  380. err error
  381. repo *git.Repository
  382. )
  383. // check if whitelist
  384. for _, re := range whiteListRepos {
  385. if re.FindString(opts.Repo) != "" {
  386. return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
  387. }
  388. }
  389. if opts.Disk {
  390. log.Infof("cloning %s", opts.Repo)
  391. cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
  392. if strings.HasPrefix(opts.Repo, "git") {
  393. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  394. URL: opts.Repo,
  395. Progress: os.Stdout,
  396. Auth: sshAuth,
  397. })
  398. } else {
  399. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  400. URL: opts.Repo,
  401. Progress: os.Stdout,
  402. })
  403. }
  404. } else if opts.RepoPath != "" {
  405. log.Infof("opening %s", opts.RepoPath)
  406. repo, err = git.PlainOpen(opts.RepoPath)
  407. } else {
  408. log.Infof("cloning %s", opts.Repo)
  409. if strings.HasPrefix(opts.Repo, "git") {
  410. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  411. URL: opts.Repo,
  412. Progress: os.Stdout,
  413. Auth: sshAuth,
  414. })
  415. } else {
  416. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  417. URL: opts.Repo,
  418. Progress: os.Stdout,
  419. })
  420. }
  421. }
  422. return &RepoDescriptor{
  423. repository: repo,
  424. path: opts.RepoPath,
  425. url: opts.Repo,
  426. name: filepath.Base(opts.Repo),
  427. err: err,
  428. }, nil
  429. }
  430. // auditGitRepo beings an audit on a git repository
  431. func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
  432. var (
  433. err error
  434. leaks []Leak
  435. )
  436. for _, re := range whiteListRepos {
  437. if re.FindString(repo.name) != "" {
  438. return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
  439. }
  440. }
  441. // check if target contains an external gitleaks toml
  442. if opts.RepoConfig {
  443. err := externalConfig(repo)
  444. if err != nil {
  445. return leaks, nil
  446. }
  447. }
  448. // clear commit cache
  449. commitMap = make(map[string]bool)
  450. refs, err := repo.repository.Storer.IterReferences()
  451. if err != nil {
  452. return leaks, err
  453. }
  454. err = refs.ForEach(func(ref *plumbing.Reference) error {
  455. if ref.Name().IsTag() {
  456. return nil
  457. }
  458. branchLeaks := auditGitReference(repo, ref)
  459. for _, leak := range branchLeaks {
  460. leaks = append(leaks, leak)
  461. }
  462. return nil
  463. })
  464. return leaks, err
  465. }
  466. // externalConfig will attempt to load a pinned ".gitleaks.toml" configuration file
  467. // from a remote or local repo. Use the --repo-config option to trigger this.
  468. func externalConfig(repo *RepoDescriptor) error {
  469. var config Config
  470. wt, err := repo.repository.Worktree()
  471. if err != nil {
  472. return err
  473. }
  474. f, err := wt.Filesystem.Open(".gitleaks.toml")
  475. if err != nil {
  476. return err
  477. }
  478. if _, err := toml.DecodeReader(f, &config); err != nil {
  479. return fmt.Errorf("problem loading config: %v", err)
  480. }
  481. f.Close()
  482. if err != nil {
  483. return err
  484. }
  485. updateConfig(config)
  486. return nil
  487. }
  488. // auditGitReference beings the audit for a git reference. This function will
  489. // traverse the git reference and audit each line of each diff.
  490. func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
  491. var (
  492. err error
  493. repoName string
  494. leaks []Leak
  495. commitCount int
  496. commitWg sync.WaitGroup
  497. mutex = &sync.Mutex{}
  498. semaphore chan bool
  499. )
  500. repoName = repo.name
  501. if opts.Threads != 0 {
  502. threads = opts.Threads
  503. }
  504. if opts.RepoPath != "" {
  505. threads = 1
  506. }
  507. semaphore = make(chan bool, threads)
  508. cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
  509. if err != nil {
  510. return nil
  511. }
  512. err = cIter.ForEach(func(c *object.Commit) error {
  513. if c == nil || c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
  514. cIter.Close()
  515. return errors.New("ErrStop")
  516. }
  517. commitCount = commitCount + 1
  518. if whiteListCommits[c.Hash.String()] {
  519. log.Infof("skipping commit: %s\n", c.Hash.String())
  520. return nil
  521. }
  522. // commits w/o parent (root of git the git ref)
  523. if len(c.ParentHashes) == 0 {
  524. if commitMap[c.Hash.String()] {
  525. return nil
  526. }
  527. cMutex.Lock()
  528. commitMap[c.Hash.String()] = true
  529. cMutex.Unlock()
  530. totalCommits = totalCommits + 1
  531. fIter, err := c.Files()
  532. if err != nil {
  533. return nil
  534. }
  535. err = fIter.ForEach(func(f *object.File) error {
  536. bin, err := f.IsBinary()
  537. if bin || err != nil {
  538. return nil
  539. }
  540. for _, re := range whiteListFiles {
  541. if re.FindString(f.Name) != "" {
  542. log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.Name)
  543. return nil
  544. }
  545. }
  546. content, err := f.Contents()
  547. if err != nil {
  548. return nil
  549. }
  550. diff := gitDiff{
  551. repoName: repoName,
  552. filePath: f.Name,
  553. content: content,
  554. sha: c.Hash.String(),
  555. author: c.Author.String(),
  556. message: strings.Replace(c.Message, "\n", " ", -1),
  557. date: c.Author.When,
  558. }
  559. fileLeaks := inspect(diff)
  560. mutex.Lock()
  561. leaks = append(leaks, fileLeaks...)
  562. mutex.Unlock()
  563. return nil
  564. })
  565. return nil
  566. }
  567. skipCount := false
  568. err = c.Parents().ForEach(func(parent *object.Commit) error {
  569. // check if we've seen this diff before
  570. if commitMap[c.Hash.String()+parent.Hash.String()] {
  571. return nil
  572. }
  573. cMutex.Lock()
  574. commitMap[c.Hash.String()+parent.Hash.String()] = true
  575. cMutex.Unlock()
  576. if !skipCount {
  577. totalCommits = totalCommits + 1
  578. skipCount = true
  579. }
  580. commitWg.Add(1)
  581. semaphore <- true
  582. go func(c *object.Commit, parent *object.Commit) {
  583. var (
  584. filePath string
  585. skipFile bool
  586. )
  587. defer func() {
  588. commitWg.Done()
  589. <-semaphore
  590. if r := recover(); r != nil {
  591. log.Warnf("recovering from panic on commit %s, likely large diff causing panic", c.Hash.String())
  592. }
  593. }()
  594. patch, err := c.Patch(parent)
  595. if err != nil {
  596. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  597. return
  598. }
  599. for _, f := range patch.FilePatches() {
  600. if f.IsBinary() {
  601. continue
  602. }
  603. skipFile = false
  604. from, to := f.Files()
  605. filePath = "???"
  606. if from != nil {
  607. filePath = from.Path()
  608. } else if to != nil {
  609. filePath = to.Path()
  610. }
  611. for _, re := range whiteListFiles {
  612. if re.FindString(filePath) != "" {
  613. log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath)
  614. skipFile = true
  615. break
  616. }
  617. }
  618. if skipFile {
  619. continue
  620. }
  621. chunks := f.Chunks()
  622. for _, chunk := range chunks {
  623. if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete {
  624. diff := gitDiff{
  625. repoName: repoName,
  626. filePath: filePath,
  627. content: chunk.Content(),
  628. sha: c.Hash.String(),
  629. author: c.Author.String(),
  630. message: strings.Replace(c.Message, "\n", " ", -1),
  631. date: c.Author.When,
  632. }
  633. chunkLeaks := inspect(diff)
  634. for _, leak := range chunkLeaks {
  635. mutex.Lock()
  636. leaks = append(leaks, leak)
  637. mutex.Unlock()
  638. }
  639. }
  640. }
  641. }
  642. }(c, parent)
  643. return nil
  644. })
  645. return nil
  646. })
  647. commitWg.Wait()
  648. return leaks
  649. }
  650. // inspect will parse each line of the git diff's content against a set of regexes or
  651. // a set of regexes set by the config (see gitleaks.toml for example). This function
  652. // will skip lines that include a whitelisted regex. A list of leaks is returned.
  653. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
  654. func inspect(diff gitDiff) []Leak {
  655. var (
  656. leaks []Leak
  657. skipLine bool
  658. )
  659. lines := strings.Split(diff.content, "\n")
  660. for _, line := range lines {
  661. skipLine = false
  662. for leakType, re := range regexes {
  663. match := re.FindString(line)
  664. if match == "" {
  665. continue
  666. }
  667. if skipLine = isLineWhitelisted(line); skipLine {
  668. break
  669. }
  670. leaks = addLeak(leaks, line, match, leakType, diff)
  671. }
  672. if !skipLine && (opts.Entropy > 0 || len(entropyRanges) != 0) {
  673. words := strings.Fields(line)
  674. for _, word := range words {
  675. entropy := getShannonEntropy(word)
  676. // Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type
  677. // was found above, since regex checks are expensive.
  678. if !entropyIsHighEnough(entropy) {
  679. continue
  680. }
  681. // If either the line is whitelisted or the line fails the noiseReduction check (when enabled),
  682. // then we can skip checking the rest of the line for high entropy words.
  683. if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine {
  684. break
  685. }
  686. leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
  687. }
  688. }
  689. }
  690. return leaks
  691. }
  692. // isLineWhitelisted returns true iff the line is matched by at least one of the whiteListRegexes.
  693. func isLineWhitelisted(line string) bool {
  694. for _, wRe := range whiteListRegexes {
  695. whitelistMatch := wRe.FindString(line)
  696. if whitelistMatch != "" {
  697. return true
  698. }
  699. }
  700. return false
  701. }
  702. // addLeak is helper for func inspect() to append leaks if found during a diff check.
  703. func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
  704. leak := Leak{
  705. Line: line,
  706. Commit: diff.sha,
  707. Offender: offender,
  708. Type: leakType,
  709. Author: diff.author,
  710. File: diff.filePath,
  711. Repo: diff.repoName,
  712. Message: diff.message,
  713. Date: diff.date,
  714. }
  715. if opts.Redact {
  716. leak.Offender = "REDACTED"
  717. leak.Line = strings.Replace(line, offender, "REDACTED", -1)
  718. }
  719. if opts.Verbose {
  720. leak.log()
  721. }
  722. leaks = append(leaks, leak)
  723. return leaks
  724. }
  725. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  726. func getShannonEntropy(data string) (entropy float64) {
  727. if data == "" {
  728. return 0
  729. }
  730. charCounts := make(map[rune]int)
  731. for _, char := range data {
  732. charCounts[char]++
  733. }
  734. invLength := 1.0 / float64(len(data))
  735. for _, count := range charCounts {
  736. freq := float64(count) * invLength
  737. entropy -= freq * math.Log2(freq)
  738. }
  739. return entropy
  740. }
  741. func entropyIsHighEnough(entropy float64) bool {
  742. if entropy >= opts.Entropy && len(entropyRanges) == 0 {
  743. return true
  744. }
  745. if len(entropyRanges) != 0 {
  746. for _, eR := range entropyRanges {
  747. if entropy > eR.v1 && entropy < eR.v2 {
  748. return true
  749. }
  750. }
  751. }
  752. return false
  753. }
  754. func highEntropyLineIsALeak(line string) bool {
  755. if !opts.NoiseReduction {
  756. return true
  757. }
  758. for _, re := range entropyRegexes {
  759. if re.FindString(line) != "" {
  760. return true
  761. }
  762. }
  763. return false
  764. }
  765. // discoverRepos walks all the children of `path`. If a child directory
  766. // contain a .git file then that repo will be added to the list of repos returned
  767. func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
  768. var (
  769. err error
  770. repos []*RepoDescriptor
  771. )
  772. files, err := ioutil.ReadDir(ownerPath)
  773. if err != nil {
  774. return repos, err
  775. }
  776. for _, f := range files {
  777. if f.IsDir() {
  778. repoPath := path.Join(ownerPath, f.Name())
  779. r, err := git.PlainOpen(repoPath)
  780. if err != nil {
  781. continue
  782. }
  783. repos = append(repos, &RepoDescriptor{
  784. repository: r,
  785. name: f.Name(),
  786. path: repoPath,
  787. })
  788. }
  789. }
  790. return repos, err
  791. }
  792. // setLogLevel sets log level for gitleaks. Default is Warning
  793. func setLogs() {
  794. switch opts.Log {
  795. case "info":
  796. log.SetLevel(log.InfoLevel)
  797. case "debug":
  798. log.SetLevel(log.DebugLevel)
  799. case "warn":
  800. log.SetLevel(log.WarnLevel)
  801. default:
  802. log.SetLevel(log.InfoLevel)
  803. }
  804. log.SetFormatter(&log.TextFormatter{
  805. FullTimestamp: true,
  806. })
  807. }
  808. // optsGuard prevents invalid options
  809. func optsGuard() error {
  810. var err error
  811. if opts.GithubOrg != "" && opts.GithubUser != "" {
  812. return fmt.Errorf("github user and organization set")
  813. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  814. return fmt.Errorf("github organization set and local owner path")
  815. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  816. return fmt.Errorf("github user set and local owner path")
  817. }
  818. if opts.Threads > runtime.GOMAXPROCS(0) {
  819. return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
  820. }
  821. // do the URL Parse and error checking here, so we can skip it later
  822. // empty string is OK, it will default to the public github URL.
  823. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  824. if !strings.HasSuffix(opts.GithubURL, "/") {
  825. opts.GithubURL += "/"
  826. }
  827. ghURL, err := url.Parse(opts.GithubURL)
  828. if err != nil {
  829. return err
  830. }
  831. tcpPort := "443"
  832. if ghURL.Scheme == "http" {
  833. tcpPort = "80"
  834. }
  835. timeout := time.Duration(1 * time.Second)
  836. _, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
  837. if err != nil {
  838. return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
  839. }
  840. }
  841. if opts.SingleSearch != "" {
  842. singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
  843. if err != nil {
  844. return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
  845. }
  846. }
  847. if opts.Entropy > 8 {
  848. return fmt.Errorf("The maximum level of entropy is 8")
  849. }
  850. if opts.Report != "" {
  851. if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
  852. return fmt.Errorf("Report should be a .json or .csv file")
  853. }
  854. dirPath := filepath.Dir(opts.Report)
  855. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  856. return fmt.Errorf("%s does not exist", dirPath)
  857. }
  858. }
  859. return nil
  860. }
  861. // loadToml loads of the toml config containing regexes and whitelists.
  862. // This function will first look if the configPath is set and load the config
  863. // from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
  864. // env var. If that is not set, then gitleaks will continue with the default configs
  865. // specified by the const var at the top `defaultConfig`
  866. func loadToml() error {
  867. var (
  868. config Config
  869. configPath string
  870. )
  871. if opts.ConfigPath != "" {
  872. configPath = opts.ConfigPath
  873. _, err := os.Stat(configPath)
  874. if err != nil {
  875. return fmt.Errorf("no gitleaks config at %s", configPath)
  876. }
  877. } else {
  878. configPath = os.Getenv("GITLEAKS_CONFIG")
  879. }
  880. if configPath != "" {
  881. if _, err := toml.DecodeFile(configPath, &config); err != nil {
  882. return fmt.Errorf("problem loading config: %v", err)
  883. }
  884. } else {
  885. _, err := toml.Decode(defaultConfig, &config)
  886. if err != nil {
  887. return fmt.Errorf("problem loading default config: %v", err)
  888. }
  889. }
  890. return updateConfig(config)
  891. }
  892. // updateConfig will update a the global config values
  893. func updateConfig(config Config) error {
  894. if len(config.Misc.Entropy) != 0 {
  895. err := entropyLimits(config.Misc.Entropy)
  896. if err != nil {
  897. return err
  898. }
  899. }
  900. for _, regex := range config.Entropy.LineRegexes {
  901. entropyRegexes = append(entropyRegexes, regexp.MustCompile(regex))
  902. }
  903. if singleSearchRegex != nil {
  904. regexes["singleSearch"] = singleSearchRegex
  905. } else {
  906. for _, regex := range config.Regexes {
  907. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  908. }
  909. }
  910. whiteListCommits = make(map[string]bool)
  911. for _, commit := range config.Whitelist.Commits {
  912. whiteListCommits[commit] = true
  913. }
  914. for _, regex := range config.Whitelist.Files {
  915. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  916. }
  917. for _, regex := range config.Whitelist.Regexes {
  918. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  919. }
  920. for _, regex := range config.Whitelist.Repos {
  921. whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
  922. }
  923. return nil
  924. }
  925. // entropyLimits hydrates entropyRanges which allows for fine tuning entropy checking
  926. func entropyLimits(entropyLimitStr []string) error {
  927. for _, span := range entropyLimitStr {
  928. split := strings.Split(span, "-")
  929. v1, err := strconv.ParseFloat(split[0], 64)
  930. if err != nil {
  931. return err
  932. }
  933. v2, err := strconv.ParseFloat(split[1], 64)
  934. if err != nil {
  935. return err
  936. }
  937. if v1 > v2 {
  938. return fmt.Errorf("entropy range must be ascending")
  939. }
  940. r := entropyRange{
  941. v1: v1,
  942. v2: v2,
  943. }
  944. if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
  945. return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
  946. }
  947. entropyRanges = append(entropyRanges, r)
  948. }
  949. return nil
  950. }
  951. // getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
  952. // If --ssh-key is set then it will attempt to load the key from that path. If not,
  953. // gitleaks will use the default $HOME/.ssh/id_rsa key
  954. func getSSHAuth() (*ssh.PublicKeys, error) {
  955. var (
  956. sshKeyPath string
  957. )
  958. if opts.SSHKey != "" {
  959. sshKeyPath = opts.SSHKey
  960. } else {
  961. // try grabbing default
  962. c, err := user.Current()
  963. if err != nil {
  964. return nil, nil
  965. }
  966. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  967. }
  968. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  969. if err != nil {
  970. if strings.HasPrefix(opts.Repo, "git") {
  971. // if you are attempting to clone a git repo via ssh and supply a bad ssh key,
  972. // the clone will fail.
  973. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  974. }
  975. }
  976. return sshAuth, nil
  977. }
  978. func (leak Leak) log() {
  979. b, _ := json.MarshalIndent(leak, "", " ")
  980. fmt.Println(string(b))
  981. }