main.go 27 KB

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