main.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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/storer"
  26. "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
  27. "gopkg.in/src-d/go-git.v4/storage/memory"
  28. "github.com/BurntSushi/toml"
  29. "github.com/google/go-github/github"
  30. "github.com/hako/durafmt"
  31. "github.com/jessevdk/go-flags"
  32. log "github.com/sirupsen/logrus"
  33. "gopkg.in/src-d/go-git.v4"
  34. )
  35. // Leak represents a leaked secret or regex match.
  36. type Leak struct {
  37. Line string `json:"line"`
  38. Commit string `json:"commit"`
  39. Offender string `json:"offender"`
  40. Type string `json:"reason"`
  41. Message string `json:"commitMsg"`
  42. Author string `json:"author"`
  43. File string `json:"file"`
  44. Repo string `json:"repo"`
  45. Date time.Time `json:"date"`
  46. }
  47. // RepoDescriptor contains a src-d git repository and other data about the repo
  48. type RepoDescriptor struct {
  49. path string
  50. url string
  51. name string
  52. repository *git.Repository
  53. err error
  54. }
  55. // Options for gitleaks
  56. type Options struct {
  57. // remote target options
  58. Repo string `short:"r" long:"repo" description:"Repo url to audit"`
  59. GithubUser string `long:"github-user" description:"Github user to audit"`
  60. GithubOrg string `long:"github-org" description:"Github organization to audit"`
  61. 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/"`
  62. GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
  63. GitLabUser string `long:"gitlab-user" description:"GitLab user ID to audit"`
  64. GitLabOrg string `long:"gitlab-org" description:"GitLab group ID to audit"`
  65. Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
  66. Depth int `long:"depth" description:"maximum commit depth"`
  67. Branch plumbing.ReferenceName `long:"branch" description:"scan remote branch only (default is all)"`
  68. // local target option
  69. RepoPath string `long:"repo-path" description:"Path to repo"`
  70. OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
  71. // Process options
  72. Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
  73. Disk bool `long:"disk" description:"Clones repo(s) to disk"`
  74. SingleSearch string `long:"single-search" description:"single regular expression to search for"`
  75. ConfigPath string `long:"config" description:"path to gitleaks config"`
  76. SSHKey string `long:"ssh-key" description:"path to ssh key"`
  77. ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
  78. Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
  79. NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"`
  80. RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""`
  81. // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
  82. // Output options
  83. Log string `short:"l" long:"log" description:"log level"`
  84. Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
  85. Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
  86. Redact bool `long:"redact" description:"redact secrets from log messages and report"`
  87. Version bool `long:"version" description:"version number"`
  88. SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
  89. }
  90. // Config struct for regexes matching and whitelisting
  91. type Config struct {
  92. Regexes []struct {
  93. Description string
  94. Regex string
  95. }
  96. Entropy struct {
  97. LineRegexes []string
  98. }
  99. Whitelist struct {
  100. Files []string
  101. Regexes []string
  102. Commits []string
  103. Repos []string
  104. }
  105. Misc struct {
  106. Entropy []string
  107. }
  108. }
  109. type gitDiff struct {
  110. content string
  111. commit *object.Commit
  112. filePath string
  113. repoName string
  114. githubCommit *github.RepositoryCommit
  115. sha string
  116. message string
  117. author string
  118. date time.Time
  119. }
  120. type entropyRange struct {
  121. v1 float64
  122. v2 float64
  123. }
  124. const defaultGithubURL = "https://api.github.com/"
  125. const version = "1.23.0"
  126. const errExit = 2
  127. const leakExit = 1
  128. const defaultConfig = `
  129. # This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
  130. # The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
  131. # is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
  132. # configurations from that path. Gitleaks does not whitelist anything by default.
  133. title = "gitleaks config"
  134. # add regexes to the regex table
  135. [[regexes]]
  136. description = "AWS"
  137. regex = '''AKIA[0-9A-Z]{16}'''
  138. [[regexes]]
  139. description = "PKCS8"
  140. regex = '''-----BEGIN PRIVATE KEY-----'''
  141. [[regexes]]
  142. description = "RSA"
  143. regex = '''-----BEGIN RSA PRIVATE KEY-----'''
  144. [[regexes]]
  145. description = "SSH"
  146. regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
  147. [[regexes]]
  148. description = "PGP"
  149. regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
  150. [[regexes]]
  151. description = "Facebook"
  152. regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]'''
  153. [[regexes]]
  154. description = "Twitter"
  155. regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]'''
  156. [[regexes]]
  157. description = "Github"
  158. regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
  159. [[regexes]]
  160. description = "Slack"
  161. regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
  162. [entropy]
  163. lineregexes = [
  164. "api",
  165. "key",
  166. "signature",
  167. "secret",
  168. "password",
  169. "pass",
  170. "pwd",
  171. "token",
  172. "curl",
  173. "wget",
  174. "https?",
  175. ]
  176. [whitelist]
  177. files = [
  178. "(.*?)(jpg|gif|doc|pdf|bin)$"
  179. ]
  180. #commits = [
  181. # "BADHA5H1",
  182. # "BADHA5H2",
  183. #]
  184. #repos = [
  185. # "mygoodrepo"
  186. #]
  187. [misc]
  188. #entropy = [
  189. # "3.3-4.30"
  190. # "6.0-8.0
  191. #]
  192. `
  193. var (
  194. opts Options
  195. regexes map[string]*regexp.Regexp
  196. singleSearchRegex *regexp.Regexp
  197. whiteListRegexes []*regexp.Regexp
  198. whiteListFiles []*regexp.Regexp
  199. whiteListCommits map[string]bool
  200. whiteListRepos []*regexp.Regexp
  201. entropyRanges []entropyRange
  202. entropyRegexes []*regexp.Regexp
  203. fileDiffRegex *regexp.Regexp
  204. sshAuth *ssh.PublicKeys
  205. dir string
  206. threads int
  207. totalCommits int64
  208. commitMap = make(map[string]bool)
  209. cMutex = &sync.Mutex{}
  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. refs storer.ReferenceIter
  438. )
  439. for _, re := range whiteListRepos {
  440. if re.FindString(repo.name) != "" {
  441. return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
  442. }
  443. }
  444. // check if target contains an external gitleaks toml
  445. if opts.RepoConfig {
  446. err := externalConfig(repo)
  447. if err != nil {
  448. return leaks, nil
  449. }
  450. }
  451. // clear commit cache
  452. commitMap = make(map[string]bool)
  453. if opts.Branch != "" {
  454. // var branchRef plumbing.ReferenceName
  455. branchRef := "refs/remotes/origin/" + opts.Branch
  456. log.Debugf("Auditing ref: %v", branchRef)
  457. ref, err := repo.repository.Storer.Reference(branchRef)
  458. if err != nil {
  459. return leaks, err
  460. }
  461. branchLeaks := auditGitReference(repo, ref)
  462. for _, leak := range branchLeaks {
  463. leaks = append(leaks, leak)
  464. }
  465. return leaks, nil
  466. }
  467. refs, err = repo.repository.Storer.IterReferences()
  468. if err != nil {
  469. return leaks, err
  470. }
  471. err = refs.ForEach(func(ref *plumbing.Reference) error {
  472. if ref.Name().IsTag() {
  473. return nil
  474. }
  475. branchLeaks := auditGitReference(repo, ref)
  476. for _, leak := range branchLeaks {
  477. leaks = append(leaks, leak)
  478. }
  479. return nil
  480. })
  481. return leaks, err
  482. }
  483. // externalConfig will attempt to load a pinned ".gitleaks.toml" configuration file
  484. // from a remote or local repo. Use the --repo-config option to trigger this.
  485. func externalConfig(repo *RepoDescriptor) error {
  486. var config Config
  487. wt, err := repo.repository.Worktree()
  488. if err != nil {
  489. return err
  490. }
  491. f, err := wt.Filesystem.Open(".gitleaks.toml")
  492. if err != nil {
  493. return err
  494. }
  495. if _, err := toml.DecodeReader(f, &config); err != nil {
  496. return fmt.Errorf("problem loading config: %v", err)
  497. }
  498. f.Close()
  499. if err != nil {
  500. return err
  501. }
  502. updateConfig(config)
  503. return nil
  504. }
  505. // auditGitReference beings the audit for a git reference. This function will
  506. // traverse the git reference and audit each line of each diff.
  507. func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
  508. var (
  509. err error
  510. repoName string
  511. leaks []Leak
  512. commitCount int
  513. commitWg sync.WaitGroup
  514. mutex = &sync.Mutex{}
  515. semaphore chan bool
  516. )
  517. repoName = repo.name
  518. if opts.Threads != 0 {
  519. threads = opts.Threads
  520. }
  521. if opts.RepoPath != "" {
  522. threads = 1
  523. }
  524. semaphore = make(chan bool, threads)
  525. cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
  526. if err != nil {
  527. return nil
  528. }
  529. err = cIter.ForEach(func(c *object.Commit) error {
  530. if c == nil || c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
  531. cIter.Close()
  532. return errors.New("ErrStop")
  533. }
  534. commitCount = commitCount + 1
  535. if whiteListCommits[c.Hash.String()] {
  536. log.Infof("skipping commit: %s\n", c.Hash.String())
  537. return nil
  538. }
  539. // commits w/o parent (root of git the git ref)
  540. if len(c.ParentHashes) == 0 {
  541. if commitMap[c.Hash.String()] {
  542. return nil
  543. }
  544. cMutex.Lock()
  545. commitMap[c.Hash.String()] = true
  546. cMutex.Unlock()
  547. totalCommits = totalCommits + 1
  548. fIter, err := c.Files()
  549. if err != nil {
  550. return nil
  551. }
  552. err = fIter.ForEach(func(f *object.File) error {
  553. bin, err := f.IsBinary()
  554. if bin || err != nil {
  555. return nil
  556. }
  557. for _, re := range whiteListFiles {
  558. if re.FindString(f.Name) != "" {
  559. log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.Name)
  560. return nil
  561. }
  562. }
  563. content, err := f.Contents()
  564. if err != nil {
  565. return nil
  566. }
  567. diff := gitDiff{
  568. repoName: repoName,
  569. filePath: f.Name,
  570. content: content,
  571. sha: c.Hash.String(),
  572. author: c.Author.String(),
  573. message: strings.Replace(c.Message, "\n", " ", -1),
  574. date: c.Author.When,
  575. }
  576. fileLeaks := inspect(diff)
  577. mutex.Lock()
  578. leaks = append(leaks, fileLeaks...)
  579. mutex.Unlock()
  580. return nil
  581. })
  582. return nil
  583. }
  584. skipCount := false
  585. err = c.Parents().ForEach(func(parent *object.Commit) error {
  586. // check if we've seen this diff before
  587. if commitMap[c.Hash.String()+parent.Hash.String()] {
  588. return nil
  589. }
  590. cMutex.Lock()
  591. commitMap[c.Hash.String()+parent.Hash.String()] = true
  592. cMutex.Unlock()
  593. if !skipCount {
  594. totalCommits = totalCommits + 1
  595. skipCount = true
  596. }
  597. commitWg.Add(1)
  598. semaphore <- true
  599. go func(c *object.Commit, parent *object.Commit) {
  600. var (
  601. filePath string
  602. skipFile bool
  603. )
  604. defer func() {
  605. commitWg.Done()
  606. <-semaphore
  607. if r := recover(); r != nil {
  608. log.Warnf("recovering from panic on commit %s, likely large diff causing panic", c.Hash.String())
  609. }
  610. }()
  611. patch, err := c.Patch(parent)
  612. if err != nil {
  613. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  614. return
  615. }
  616. for _, f := range patch.FilePatches() {
  617. if f.IsBinary() {
  618. continue
  619. }
  620. skipFile = false
  621. from, to := f.Files()
  622. filePath = "???"
  623. if from != nil {
  624. filePath = from.Path()
  625. } else if to != nil {
  626. filePath = to.Path()
  627. }
  628. for _, re := range whiteListFiles {
  629. if re.FindString(filePath) != "" {
  630. log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath)
  631. skipFile = true
  632. break
  633. }
  634. }
  635. if skipFile {
  636. continue
  637. }
  638. chunks := f.Chunks()
  639. for _, chunk := range chunks {
  640. if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete {
  641. diff := gitDiff{
  642. repoName: repoName,
  643. filePath: filePath,
  644. content: chunk.Content(),
  645. sha: c.Hash.String(),
  646. author: c.Author.String(),
  647. message: strings.Replace(c.Message, "\n", " ", -1),
  648. date: c.Author.When,
  649. }
  650. chunkLeaks := inspect(diff)
  651. for _, leak := range chunkLeaks {
  652. mutex.Lock()
  653. leaks = append(leaks, leak)
  654. mutex.Unlock()
  655. }
  656. }
  657. }
  658. }
  659. }(c, parent)
  660. return nil
  661. })
  662. return nil
  663. })
  664. commitWg.Wait()
  665. return leaks
  666. }
  667. // inspect will parse each line of the git diff's content against a set of regexes or
  668. // a set of regexes set by the config (see gitleaks.toml for example). This function
  669. // will skip lines that include a whitelisted regex. A list of leaks is returned.
  670. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
  671. func inspect(diff gitDiff) []Leak {
  672. var (
  673. leaks []Leak
  674. skipLine bool
  675. )
  676. lines := strings.Split(diff.content, "\n")
  677. for _, line := range lines {
  678. skipLine = false
  679. for leakType, re := range regexes {
  680. match := re.FindString(line)
  681. if match == "" {
  682. continue
  683. }
  684. if skipLine = isLineWhitelisted(line); skipLine {
  685. break
  686. }
  687. leaks = addLeak(leaks, line, match, leakType, diff)
  688. }
  689. if !skipLine && (opts.Entropy > 0 || len(entropyRanges) != 0) {
  690. words := strings.Fields(line)
  691. for _, word := range words {
  692. entropy := getShannonEntropy(word)
  693. // Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type
  694. // was found above, since regex checks are expensive.
  695. if !entropyIsHighEnough(entropy) {
  696. continue
  697. }
  698. // If either the line is whitelisted or the line fails the noiseReduction check (when enabled),
  699. // then we can skip checking the rest of the line for high entropy words.
  700. if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine {
  701. break
  702. }
  703. leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
  704. }
  705. }
  706. }
  707. return leaks
  708. }
  709. // isLineWhitelisted returns true iff the line is matched by at least one of the whiteListRegexes.
  710. func isLineWhitelisted(line string) bool {
  711. for _, wRe := range whiteListRegexes {
  712. whitelistMatch := wRe.FindString(line)
  713. if whitelistMatch != "" {
  714. return true
  715. }
  716. }
  717. return false
  718. }
  719. // addLeak is helper for func inspect() to append leaks if found during a diff check.
  720. func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
  721. leak := Leak{
  722. Line: line,
  723. Commit: diff.sha,
  724. Offender: offender,
  725. Type: leakType,
  726. Author: diff.author,
  727. File: diff.filePath,
  728. Repo: diff.repoName,
  729. Message: diff.message,
  730. Date: diff.date,
  731. }
  732. if opts.Redact {
  733. leak.Offender = "REDACTED"
  734. leak.Line = strings.Replace(line, offender, "REDACTED", -1)
  735. }
  736. if opts.Verbose {
  737. leak.log()
  738. }
  739. leaks = append(leaks, leak)
  740. return leaks
  741. }
  742. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  743. func getShannonEntropy(data string) (entropy float64) {
  744. if data == "" {
  745. return 0
  746. }
  747. charCounts := make(map[rune]int)
  748. for _, char := range data {
  749. charCounts[char]++
  750. }
  751. invLength := 1.0 / float64(len(data))
  752. for _, count := range charCounts {
  753. freq := float64(count) * invLength
  754. entropy -= freq * math.Log2(freq)
  755. }
  756. return entropy
  757. }
  758. func entropyIsHighEnough(entropy float64) bool {
  759. if entropy >= opts.Entropy && len(entropyRanges) == 0 {
  760. return true
  761. }
  762. if len(entropyRanges) != 0 {
  763. for _, eR := range entropyRanges {
  764. if entropy > eR.v1 && entropy < eR.v2 {
  765. return true
  766. }
  767. }
  768. }
  769. return false
  770. }
  771. func highEntropyLineIsALeak(line string) bool {
  772. if !opts.NoiseReduction {
  773. return true
  774. }
  775. for _, re := range entropyRegexes {
  776. if re.FindString(line) != "" {
  777. return true
  778. }
  779. }
  780. return false
  781. }
  782. // discoverRepos walks all the children of `path`. If a child directory
  783. // contain a .git file then that repo will be added to the list of repos returned
  784. func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
  785. var (
  786. err error
  787. repos []*RepoDescriptor
  788. )
  789. files, err := ioutil.ReadDir(ownerPath)
  790. if err != nil {
  791. return repos, err
  792. }
  793. for _, f := range files {
  794. if f.IsDir() {
  795. repoPath := path.Join(ownerPath, f.Name())
  796. r, err := git.PlainOpen(repoPath)
  797. if err != nil {
  798. continue
  799. }
  800. repos = append(repos, &RepoDescriptor{
  801. repository: r,
  802. name: f.Name(),
  803. path: repoPath,
  804. })
  805. }
  806. }
  807. return repos, err
  808. }
  809. // setLogLevel sets log level for gitleaks. Default is Warning
  810. func setLogs() {
  811. switch opts.Log {
  812. case "info":
  813. log.SetLevel(log.InfoLevel)
  814. case "debug":
  815. log.SetLevel(log.DebugLevel)
  816. case "warn":
  817. log.SetLevel(log.WarnLevel)
  818. default:
  819. log.SetLevel(log.InfoLevel)
  820. }
  821. log.SetFormatter(&log.TextFormatter{
  822. FullTimestamp: true,
  823. })
  824. }
  825. // optsGuard prevents invalid options
  826. func optsGuard() error {
  827. var err error
  828. if opts.GithubOrg != "" && opts.GithubUser != "" {
  829. return fmt.Errorf("github user and organization set")
  830. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  831. return fmt.Errorf("github organization set and local owner path")
  832. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  833. return fmt.Errorf("github user set and local owner path")
  834. }
  835. if opts.Threads > runtime.GOMAXPROCS(0) {
  836. return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
  837. }
  838. // do the URL Parse and error checking here, so we can skip it later
  839. // empty string is OK, it will default to the public github URL.
  840. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  841. if !strings.HasSuffix(opts.GithubURL, "/") {
  842. opts.GithubURL += "/"
  843. }
  844. ghURL, err := url.Parse(opts.GithubURL)
  845. if err != nil {
  846. return err
  847. }
  848. tcpPort := "443"
  849. if ghURL.Scheme == "http" {
  850. tcpPort = "80"
  851. }
  852. timeout := time.Duration(1 * time.Second)
  853. _, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
  854. if err != nil {
  855. return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
  856. }
  857. }
  858. if opts.SingleSearch != "" {
  859. singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
  860. if err != nil {
  861. return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
  862. }
  863. }
  864. if opts.Entropy > 8 {
  865. return fmt.Errorf("The maximum level of entropy is 8")
  866. }
  867. if opts.Report != "" {
  868. if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
  869. return fmt.Errorf("Report should be a .json or .csv file")
  870. }
  871. dirPath := filepath.Dir(opts.Report)
  872. if _, err := os.Stat(dirPath); os.IsNotExist(err) {
  873. return fmt.Errorf("%s does not exist", dirPath)
  874. }
  875. }
  876. return nil
  877. }
  878. // loadToml loads of the toml config containing regexes and whitelists.
  879. // This function will first look if the configPath is set and load the config
  880. // from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
  881. // env var. If that is not set, then gitleaks will continue with the default configs
  882. // specified by the const var at the top `defaultConfig`
  883. func loadToml() error {
  884. var (
  885. config Config
  886. configPath string
  887. )
  888. if opts.ConfigPath != "" {
  889. configPath = opts.ConfigPath
  890. _, err := os.Stat(configPath)
  891. if err != nil {
  892. return fmt.Errorf("no gitleaks config at %s", configPath)
  893. }
  894. } else {
  895. configPath = os.Getenv("GITLEAKS_CONFIG")
  896. }
  897. if configPath != "" {
  898. if _, err := toml.DecodeFile(configPath, &config); err != nil {
  899. return fmt.Errorf("problem loading config: %v", err)
  900. }
  901. } else {
  902. _, err := toml.Decode(defaultConfig, &config)
  903. if err != nil {
  904. return fmt.Errorf("problem loading default config: %v", err)
  905. }
  906. }
  907. return updateConfig(config)
  908. }
  909. // updateConfig will update a the global config values
  910. func updateConfig(config Config) error {
  911. if len(config.Misc.Entropy) != 0 {
  912. err := entropyLimits(config.Misc.Entropy)
  913. if err != nil {
  914. return err
  915. }
  916. }
  917. for _, regex := range config.Entropy.LineRegexes {
  918. entropyRegexes = append(entropyRegexes, regexp.MustCompile(regex))
  919. }
  920. if singleSearchRegex != nil {
  921. regexes["singleSearch"] = singleSearchRegex
  922. } else {
  923. for _, regex := range config.Regexes {
  924. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  925. }
  926. }
  927. whiteListCommits = make(map[string]bool)
  928. for _, commit := range config.Whitelist.Commits {
  929. whiteListCommits[commit] = true
  930. }
  931. for _, regex := range config.Whitelist.Files {
  932. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  933. }
  934. for _, regex := range config.Whitelist.Regexes {
  935. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  936. }
  937. for _, regex := range config.Whitelist.Repos {
  938. whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
  939. }
  940. return nil
  941. }
  942. // entropyLimits hydrates entropyRanges which allows for fine tuning entropy checking
  943. func entropyLimits(entropyLimitStr []string) error {
  944. for _, span := range entropyLimitStr {
  945. split := strings.Split(span, "-")
  946. v1, err := strconv.ParseFloat(split[0], 64)
  947. if err != nil {
  948. return err
  949. }
  950. v2, err := strconv.ParseFloat(split[1], 64)
  951. if err != nil {
  952. return err
  953. }
  954. if v1 > v2 {
  955. return fmt.Errorf("entropy range must be ascending")
  956. }
  957. r := entropyRange{
  958. v1: v1,
  959. v2: v2,
  960. }
  961. if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
  962. return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
  963. }
  964. entropyRanges = append(entropyRanges, r)
  965. }
  966. return nil
  967. }
  968. // getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
  969. // If --ssh-key is set then it will attempt to load the key from that path. If not,
  970. // gitleaks will use the default $HOME/.ssh/id_rsa key
  971. func getSSHAuth() (*ssh.PublicKeys, error) {
  972. var (
  973. sshKeyPath string
  974. )
  975. if opts.SSHKey != "" {
  976. sshKeyPath = opts.SSHKey
  977. } else {
  978. // try grabbing default
  979. c, err := user.Current()
  980. if err != nil {
  981. return nil, nil
  982. }
  983. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  984. }
  985. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  986. if err != nil {
  987. if strings.HasPrefix(opts.Repo, "git") {
  988. // if you are attempting to clone a git repo via ssh and supply a bad ssh key,
  989. // the clone will fail.
  990. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  991. }
  992. }
  993. return sshAuth, nil
  994. }
  995. func (leak Leak) log() {
  996. b, _ := json.MarshalIndent(leak, "", " ")
  997. fmt.Println(string(b))
  998. }