main.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. package main
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/csv"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "math"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "os/user"
  16. "path"
  17. "path/filepath"
  18. "regexp"
  19. "runtime"
  20. "strings"
  21. "sync"
  22. "time"
  23. "gopkg.in/src-d/go-git.v4/plumbing"
  24. "golang.org/x/oauth2"
  25. "gopkg.in/src-d/go-git.v4/plumbing/object"
  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. flags "github.com/jessevdk/go-flags"
  32. log "github.com/sirupsen/logrus"
  33. git "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. Branch string `json:"branch"`
  45. Repo string `json:"repo"`
  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. IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"`
  63. /*
  64. TODO:
  65. GitLabUser string `long:"gitlab-user" description:"User url to audit"`
  66. GitLabOrg string `long:"gitlab-org" description:"Organization url to audit"`
  67. */
  68. Branch string `short:"b" long:"branch" description:"branch name to audit (defaults to HEAD)"`
  69. Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
  70. Depth int `long:"depth" description:"maximum commit depth"`
  71. // local target option
  72. RepoPath string `long:"repo-path" description:"Path to repo"`
  73. OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
  74. // Process options
  75. MaxGoRoutines int `long:"max-go" description:"Maximum number of concurrent go-routines gitleaks spawns"`
  76. Disk bool `long:"disk" description:"Clones repo(s) to disk"`
  77. AuditAllRefs bool `long:"all-refs" description:"run audit on all refs"`
  78. SingleSearch string `long:"single-search" description:"single regular expression to search for"`
  79. ConfigPath string `long:"config" description:"path to gitleaks config"`
  80. SSHKey string `long:"ssh-key" description:"path to ssh key"`
  81. ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
  82. Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
  83. // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
  84. // Output options
  85. Log string `short:"l" long:"log" description:"log level"`
  86. Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
  87. Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
  88. Redact bool `long:"redact" description:"redact secrets from log messages and report"`
  89. Version bool `long:"version" description:"version number"`
  90. SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
  91. }
  92. // Config struct for regexes matching and whitelisting
  93. type Config struct {
  94. Regexes []struct {
  95. Description string
  96. Regex string
  97. }
  98. Whitelist struct {
  99. Files []string
  100. Regexes []string
  101. Commits []string
  102. Branches []string
  103. Repos []string
  104. }
  105. }
  106. type gitDiff struct {
  107. content string
  108. commit *object.Commit
  109. filePath string
  110. branchName string
  111. repoName string
  112. }
  113. const defaultGithubURL = "https://api.github.com/"
  114. const version = "1.11.1"
  115. const errExit = 2
  116. const leakExit = 1
  117. const defaultConfig = `
  118. # This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
  119. # The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
  120. # is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
  121. # configurations from that path. Gitleaks does not whitelist anything by default.
  122. title = "gitleaks config"
  123. # add regexes to the regex table
  124. [[regexes]]
  125. description = "AWS"
  126. regex = '''AKIA[0-9A-Z]{16}'''
  127. [[regexes]]
  128. description = "RKCS8"
  129. regex = '''-----BEGIN PRIVATE KEY-----'''
  130. [[regexes]]
  131. description = "RSA"
  132. regex = '''-----BEGIN RSA PRIVATE KEY-----'''
  133. [[regexes]]
  134. description = "Github"
  135. regex = '''(?i)github.*['\"][0-9a-zA-Z]{35,40}['\"]'''
  136. [[regexes]]
  137. description = "SSH"
  138. regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
  139. [[regexes]]
  140. description = "Facebook"
  141. regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]'''
  142. [[regexes]]
  143. description = "Twitter"
  144. regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
  145. [whitelist]
  146. #regexes = [
  147. # "AKAIMYFAKEAWKKEY",
  148. #]
  149. #files = [
  150. # "(.*?)(jpg|gif|doc|pdf|bin)$"
  151. #]
  152. #commits = [
  153. # "BADHA5H1",
  154. # "BADHA5H2",
  155. #]
  156. #branches = [
  157. # "dev/STUPDIFKNFEATURE"
  158. #]
  159. #repos = [
  160. # "someYugeRepoWeKnowIsCLEAR"
  161. #]
  162. `
  163. var (
  164. opts Options
  165. regexes map[string]*regexp.Regexp
  166. singleSearchRegex *regexp.Regexp
  167. whiteListRegexes []*regexp.Regexp
  168. whiteListFiles []*regexp.Regexp
  169. whiteListCommits map[string]bool
  170. whiteListBranches []string
  171. whiteListRepos []string
  172. fileDiffRegex *regexp.Regexp
  173. sshAuth *ssh.PublicKeys
  174. dir string
  175. maxGo int
  176. totalCommits int64
  177. )
  178. func init() {
  179. log.SetOutput(os.Stdout)
  180. maxGo = runtime.GOMAXPROCS(0) / 2
  181. regexes = make(map[string]*regexp.Regexp)
  182. whiteListCommits = make(map[string]bool)
  183. }
  184. func main() {
  185. _, err := flags.Parse(&opts)
  186. if opts.Version {
  187. fmt.Println(version)
  188. os.Exit(0)
  189. }
  190. if opts.SampleConfig {
  191. fmt.Println(defaultConfig)
  192. os.Exit(0)
  193. }
  194. now := time.Now()
  195. leaks, err := run()
  196. if err != nil {
  197. log.Error(err)
  198. os.Exit(errExit)
  199. }
  200. if opts.Report != "" {
  201. writeReport(leaks)
  202. }
  203. log.Infof("%d commits inspected in %s", totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
  204. if len(leaks) != 0 {
  205. log.Warnf("%d leaks detected", len(leaks))
  206. os.Exit(leakExit)
  207. }
  208. }
  209. // run parses options and kicks off the audit
  210. func run() ([]Leak, error) {
  211. var leaks []Leak
  212. setLogs()
  213. err := optsGuard()
  214. if err != nil {
  215. return nil, err
  216. }
  217. err = loadToml()
  218. if err != nil {
  219. return nil, err
  220. }
  221. if opts.IncludePrivate {
  222. // if including private repos use ssh as authentication
  223. sshAuth, err = getSSHAuth()
  224. if err != nil {
  225. return nil, err
  226. }
  227. }
  228. if opts.Disk {
  229. // temporary directory where all the gitleaks plain clones will reside
  230. dir, err = ioutil.TempDir("", "gitleaks")
  231. defer os.RemoveAll(dir)
  232. if err != nil {
  233. return nil, err
  234. }
  235. }
  236. // start audits
  237. if opts.Repo != "" || opts.RepoPath != "" {
  238. // Audit a single remote repo or a local repo.
  239. repo, err := cloneRepo()
  240. if err != nil {
  241. return leaks, err
  242. }
  243. return auditGitRepo(repo)
  244. } else if opts.OwnerPath != "" {
  245. // Audit local repos. Gitleaks will look for all child directories of OwnerPath for
  246. // git repos and perform an audit on said repos.
  247. repos, err := discoverRepos(opts.OwnerPath)
  248. if err != nil {
  249. return leaks, err
  250. }
  251. for _, repo := range repos {
  252. leaksFromRepo, err := auditGitRepo(repo)
  253. if err != nil {
  254. return leaks, err
  255. }
  256. leaks = append(leaksFromRepo, leaks...)
  257. }
  258. } else if opts.GithubOrg != "" || opts.GithubUser != "" {
  259. // Audit a github owner -- a user or organization. If you want to include
  260. // private repos you must pass a --private/-p option and have your ssh keys set
  261. leaks, err = auditGithubRepos()
  262. if err != nil {
  263. return leaks, err
  264. }
  265. }
  266. return leaks, nil
  267. }
  268. // writeReport writes a report to a file specified in the --report= option.
  269. // Default format for report is JSON. You can use the --csv option to write the report as a csv
  270. func writeReport(leaks []Leak) error {
  271. var err error
  272. log.Infof("writing report to %s", opts.Report)
  273. if strings.HasSuffix(opts.Report, ".csv") {
  274. f, err := os.Create(opts.Report)
  275. if err != nil {
  276. return err
  277. }
  278. defer f.Close()
  279. w := csv.NewWriter(f)
  280. w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "branch"})
  281. for _, leak := range leaks {
  282. w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Branch})
  283. }
  284. w.Flush()
  285. } else {
  286. reportJSON, _ := json.MarshalIndent(leaks, "", "\t")
  287. err = ioutil.WriteFile(opts.Report, reportJSON, 0644)
  288. }
  289. return err
  290. }
  291. // cloneRepo clones a repo to memory(default) or to disk if the --disk option is set. If you want to
  292. // clone a private repo you must set the --private/-p option, use a ssh target, and have your ssh keys
  293. // configured. If you want to audit a local repo, getRepo will load up a repo located at --repo-path
  294. func cloneRepo() (*RepoDescriptor, error) {
  295. var (
  296. err error
  297. repo *git.Repository
  298. )
  299. if opts.Disk {
  300. log.Infof("cloning %s", opts.Repo)
  301. cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
  302. if opts.IncludePrivate {
  303. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  304. URL: opts.Repo,
  305. Progress: os.Stdout,
  306. Auth: sshAuth,
  307. })
  308. } else {
  309. repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
  310. URL: opts.Repo,
  311. Progress: os.Stdout,
  312. })
  313. }
  314. } else if opts.RepoPath != "" {
  315. log.Infof("opening %s", opts.Repo)
  316. repo, err = git.PlainOpen(opts.RepoPath)
  317. } else {
  318. log.Infof("cloning %s", opts.Repo)
  319. if opts.IncludePrivate {
  320. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  321. URL: opts.Repo,
  322. Progress: os.Stdout,
  323. Auth: sshAuth,
  324. })
  325. } else {
  326. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  327. URL: opts.Repo,
  328. Progress: os.Stdout,
  329. })
  330. }
  331. }
  332. return &RepoDescriptor{
  333. repository: repo,
  334. path: opts.RepoPath,
  335. url: opts.Repo,
  336. name: filepath.Base(opts.Repo),
  337. err: err,
  338. }, nil
  339. }
  340. // auditGitRepo beings an audit on a git repository by checking the default HEAD branch, all branches, or
  341. // a single branch depending on what gitleaks is configured to do. Note when I say branch I really
  342. // mean reference as these branches are read only.
  343. func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
  344. var (
  345. err error
  346. leaks []Leak
  347. )
  348. for _, repoName := range whiteListRepos {
  349. if repoName == repo.name {
  350. return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
  351. }
  352. }
  353. ref, err := repo.repository.Head()
  354. if err != nil {
  355. return leaks, err
  356. }
  357. if opts.AuditAllRefs {
  358. skipBranch := false
  359. refs, err := repo.repository.Storer.IterReferences()
  360. if err != nil {
  361. return leaks, err
  362. }
  363. err = refs.ForEach(func(ref *plumbing.Reference) error {
  364. for _, b := range whiteListBranches {
  365. if strings.HasSuffix(string(ref.Name()), b) {
  366. skipBranch = true
  367. }
  368. }
  369. if skipBranch {
  370. skipBranch = false
  371. return nil
  372. }
  373. branchLeaks := auditGitReference(repo, ref)
  374. for _, leak := range branchLeaks {
  375. leaks = append(leaks, leak)
  376. }
  377. return nil
  378. })
  379. } else {
  380. if opts.Branch != "" {
  381. foundBranch := false
  382. refs, _ := repo.repository.Storer.IterReferences()
  383. branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1]
  384. err = refs.ForEach(func(refBranch *plumbing.Reference) error {
  385. if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch {
  386. foundBranch = true
  387. ref = refBranch
  388. }
  389. return nil
  390. })
  391. if foundBranch == false {
  392. return nil, nil
  393. }
  394. }
  395. leaks = auditGitReference(repo, ref)
  396. }
  397. return leaks, err
  398. }
  399. // auditGitReference beings the audit for a git reference. This function will
  400. // traverse the git reference and audit each line of each diff. Set maximum concurrency with
  401. // the --max-go option (default is set to the number of cores on your cpu).
  402. func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
  403. var (
  404. err error
  405. prevCommit *object.Commit
  406. semaphore chan bool
  407. repoName string
  408. leaks []Leak
  409. commitWg sync.WaitGroup
  410. mutex = &sync.Mutex{}
  411. commitCount int
  412. )
  413. repoName = repo.name
  414. if opts.MaxGoRoutines != 0 {
  415. maxGo = opts.MaxGoRoutines
  416. }
  417. semaphore = make(chan bool, maxGo)
  418. cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
  419. if err != nil {
  420. return nil
  421. }
  422. err = cIter.ForEach(func(c *object.Commit) error {
  423. if c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
  424. cIter.Close()
  425. return errors.New("ErrStop")
  426. }
  427. commitCount = commitCount + 1
  428. totalCommits = totalCommits + 1
  429. if whiteListCommits[c.Hash.String()] {
  430. prevCommit = c
  431. log.Infof("skipping commit: %s\n", c.Hash.String())
  432. return nil
  433. }
  434. if prevCommit != nil {
  435. if whiteListCommits[prevCommit.Hash.String()] {
  436. prevCommit = c
  437. log.Infof("skipping commit: %s\n", c.Hash.String())
  438. return nil
  439. }
  440. }
  441. commitWg.Add(1)
  442. semaphore <- true
  443. go func(c *object.Commit, prevCommit *object.Commit) {
  444. var (
  445. filePath string
  446. skipFile bool
  447. )
  448. defer func() {
  449. commitWg.Done()
  450. <-semaphore
  451. if r := recover(); r != nil {
  452. log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
  453. }
  454. }()
  455. diff := gitDiff{
  456. commit: prevCommit,
  457. branchName: string(ref.Name()),
  458. repoName: repoName,
  459. }
  460. if prevCommit == nil {
  461. t, _ := c.Tree()
  462. files := t.Files()
  463. err := files.ForEach(func(file *object.File) error {
  464. content, err := file.Contents()
  465. if err != nil {
  466. return err
  467. }
  468. diff.filePath = file.Name
  469. diff.content = content
  470. diff.commit = c
  471. chunkLeaks := inspect(diff)
  472. for _, leak := range chunkLeaks {
  473. mutex.Lock()
  474. leaks = append(leaks, leak)
  475. mutex.Unlock()
  476. }
  477. return nil
  478. })
  479. if err != nil {
  480. log.Warnf("problem generating diff for commit: %s\n", c.Hash.String())
  481. return
  482. }
  483. } else {
  484. patch, err := c.Patch(prevCommit)
  485. if err != nil {
  486. log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
  487. return
  488. }
  489. for _, f := range patch.FilePatches() {
  490. skipFile = false
  491. from, to := f.Files()
  492. filePath = "???"
  493. if from != nil {
  494. filePath = from.Path()
  495. } else if to != nil {
  496. filePath = to.Path()
  497. }
  498. diff.filePath = filePath
  499. for _, re := range whiteListFiles {
  500. if re.FindString(filePath) != "" {
  501. skipFile = true
  502. break
  503. }
  504. }
  505. if skipFile {
  506. continue
  507. }
  508. chunks := f.Chunks()
  509. for _, chunk := range chunks {
  510. if chunk.Type() == 1 || chunk.Type() == 2 {
  511. diff.content = chunk.Content()
  512. chunkLeaks := inspect(diff)
  513. for _, leak := range chunkLeaks {
  514. mutex.Lock()
  515. leaks = append(leaks, leak)
  516. mutex.Unlock()
  517. }
  518. }
  519. }
  520. }
  521. }
  522. }(c, prevCommit)
  523. prevCommit = c
  524. return nil
  525. })
  526. commitWg.Wait()
  527. return leaks
  528. }
  529. // inspect will parse each line of the git diff's content against a set of regexes or
  530. // a set of regexes set by the config (see gitleaks.toml for example). This function
  531. // will skip lines that include a whitelisted regex. A list of leaks is returned.
  532. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
  533. func inspect(diff gitDiff) []Leak {
  534. lines := strings.Split(diff.content, "\n")
  535. var (
  536. leaks []Leak
  537. skipLine bool
  538. )
  539. for _, line := range lines {
  540. skipLine = false
  541. for leakType, re := range regexes {
  542. match := re.FindString(line)
  543. if match == "" {
  544. continue
  545. }
  546. // if offender matches whitelist regex, ignore it
  547. for _, wRe := range whiteListRegexes {
  548. whitelistMatch := wRe.FindString(line)
  549. if whitelistMatch != "" {
  550. skipLine = true
  551. break
  552. }
  553. }
  554. if skipLine {
  555. break
  556. }
  557. leaks = addLeak(leaks, line, match, leakType, diff)
  558. }
  559. if opts.Entropy > 0 {
  560. words := strings.Fields(line)
  561. for _, word := range words {
  562. if getShannonEntropy(word) >= opts.Entropy {
  563. leaks = addLeak(leaks, line, word, "High Entropy", diff)
  564. }
  565. }
  566. }
  567. }
  568. return leaks
  569. }
  570. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  571. func getShannonEntropy(data string) (entropy float64) {
  572. if data == "" {
  573. return 0
  574. }
  575. charCounts := make(map[rune]int)
  576. for _, char := range data {
  577. charCounts[char]++
  578. }
  579. invLength := 1.0 / float64(len(data))
  580. for _, count := range charCounts {
  581. freq := float64(count) * invLength
  582. entropy -= freq * math.Log2(freq)
  583. }
  584. return entropy
  585. }
  586. // addLeak is helper for func inspect() to append leaks if found during a diff check.
  587. func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
  588. leak := Leak{
  589. Line: line,
  590. Commit: diff.commit.Hash.String(),
  591. Offender: offender,
  592. Type: leakType,
  593. Message: diff.commit.Message,
  594. Author: diff.commit.Author.String(),
  595. File: diff.filePath,
  596. Branch: diff.branchName,
  597. Repo: diff.repoName,
  598. }
  599. if opts.Redact {
  600. leak.Offender = "REDACTED"
  601. leak.Line = "REDACTED"
  602. }
  603. if opts.Verbose {
  604. leak.log()
  605. }
  606. leaks = append(leaks, leak)
  607. return leaks
  608. }
  609. // auditGithubRepos kicks off audits if --github-user or --github-org options are set.
  610. // First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
  611. // After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
  612. // If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
  613. func auditGithubRepos() ([]Leak, error) {
  614. var (
  615. err error
  616. githubRepos []*github.Repository
  617. pagedGithubRepos []*github.Repository
  618. resp *github.Response
  619. githubClient *github.Client
  620. githubOrgOptions *github.RepositoryListByOrgOptions
  621. githubOptions *github.RepositoryListOptions
  622. done bool
  623. leaks []Leak
  624. ownerDir string
  625. )
  626. ctx := context.Background()
  627. if opts.GithubOrg != "" {
  628. githubClient = github.NewClient(githubToken())
  629. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  630. ghURL, _ := url.Parse(opts.GithubURL)
  631. githubClient.BaseURL = ghURL
  632. }
  633. githubOrgOptions = &github.RepositoryListByOrgOptions{
  634. ListOptions: github.ListOptions{PerPage: 100},
  635. }
  636. } else if opts.GithubUser != "" {
  637. githubClient = github.NewClient(githubToken())
  638. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  639. ghURL, _ := url.Parse(opts.GithubURL)
  640. githubClient.BaseURL = ghURL
  641. }
  642. githubOptions = &github.RepositoryListOptions{
  643. Affiliation: "owner",
  644. ListOptions: github.ListOptions{
  645. PerPage: 100,
  646. },
  647. }
  648. }
  649. for {
  650. if done {
  651. break
  652. }
  653. if opts.GithubUser != "" {
  654. if opts.IncludePrivate {
  655. pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
  656. } else {
  657. pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
  658. }
  659. if err != nil {
  660. done = true
  661. }
  662. githubOptions.Page = resp.NextPage
  663. githubRepos = append(githubRepos, pagedGithubRepos...)
  664. if resp.NextPage == 0 {
  665. done = true
  666. }
  667. } else if opts.GithubOrg != "" {
  668. pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
  669. if err != nil {
  670. done = true
  671. }
  672. githubOrgOptions.Page = resp.NextPage
  673. githubRepos = append(githubRepos, pagedGithubRepos...)
  674. if resp.NextPage == 0 {
  675. done = true
  676. }
  677. }
  678. if opts.Log == "Debug" || opts.Log == "debug" {
  679. for _, githubRepo := range pagedGithubRepos {
  680. log.Debugf("staging repos %s", *githubRepo.Name)
  681. }
  682. }
  683. }
  684. if err != nil {
  685. return nil, err
  686. }
  687. if opts.Disk {
  688. ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
  689. os.RemoveAll(ownerDir)
  690. }
  691. for _, githubRepo := range githubRepos {
  692. repo, err := cloneGithubRepo(githubRepo)
  693. if err != nil {
  694. log.Warn(err)
  695. continue
  696. }
  697. leaksFromRepo, err := auditGitRepo(repo)
  698. if opts.Disk {
  699. os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
  700. }
  701. if len(leaksFromRepo) == 0 {
  702. log.Infof("no leaks found for repo %s", *githubRepo.Name)
  703. } else {
  704. log.Warnf("leaks found for repo %s", *githubRepo.Name)
  705. }
  706. if err != nil {
  707. log.Warn(err)
  708. }
  709. leaks = append(leaks, leaksFromRepo...)
  710. }
  711. return leaks, nil
  712. }
  713. // cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
  714. // will be cloned to disk if --disk is set. If the repo is private, you must include the
  715. // --private/-p option. After the repo is clone, an audit will begin.
  716. func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
  717. var (
  718. repo *git.Repository
  719. err error
  720. )
  721. if opts.ExcludeForks && githubRepo.GetFork() {
  722. return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
  723. }
  724. for _, repoName := range whiteListRepos {
  725. if repoName == *githubRepo.Name {
  726. return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
  727. }
  728. }
  729. log.Infof("cloning: %s", *githubRepo.Name)
  730. if opts.Disk {
  731. ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
  732. if err != nil {
  733. return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
  734. }
  735. if opts.IncludePrivate {
  736. if sshAuth == nil {
  737. return nil, fmt.Errorf("no ssh auth available")
  738. }
  739. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  740. URL: *githubRepo.SSHURL,
  741. Auth: sshAuth,
  742. })
  743. } else {
  744. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  745. URL: *githubRepo.CloneURL,
  746. })
  747. }
  748. } else {
  749. if opts.IncludePrivate {
  750. if sshAuth == nil {
  751. return nil, fmt.Errorf("no ssh auth available")
  752. }
  753. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  754. URL: *githubRepo.SSHURL,
  755. Auth: sshAuth,
  756. })
  757. } else {
  758. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  759. URL: *githubRepo.CloneURL,
  760. })
  761. }
  762. }
  763. if err != nil {
  764. return nil, err
  765. }
  766. return &RepoDescriptor{
  767. repository: repo,
  768. name: *githubRepo.Name,
  769. }, nil
  770. }
  771. // githubToken returns an oauth2 client for the github api to consume. This token is necessary
  772. // if you are running audits with --github-user or --github-org
  773. func githubToken() *http.Client {
  774. githubToken := os.Getenv("GITHUB_TOKEN")
  775. if githubToken == "" {
  776. return nil
  777. }
  778. ts := oauth2.StaticTokenSource(
  779. &oauth2.Token{AccessToken: githubToken},
  780. )
  781. return oauth2.NewClient(context.Background(), ts)
  782. }
  783. // discoverRepos walks all the children of `path`. If a child directory
  784. // contain a .git file then that repo will be added to the list of repos returned
  785. func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
  786. var (
  787. err error
  788. repos []*RepoDescriptor
  789. )
  790. files, err := ioutil.ReadDir(ownerPath)
  791. if err != nil {
  792. return repos, err
  793. }
  794. for _, f := range files {
  795. if f.IsDir() {
  796. repoPath := path.Join(ownerPath, f.Name())
  797. r, err := git.PlainOpen(repoPath)
  798. if err != nil {
  799. continue
  800. }
  801. repos = append(repos, &RepoDescriptor{
  802. repository: r,
  803. name: f.Name(),
  804. path: repoPath,
  805. })
  806. }
  807. }
  808. return repos, err
  809. }
  810. // setLogLevel sets log level for gitleaks. Default is Warning
  811. func setLogs() {
  812. switch opts.Log {
  813. case "info":
  814. log.SetLevel(log.InfoLevel)
  815. case "debug":
  816. log.SetLevel(log.DebugLevel)
  817. case "warn":
  818. log.SetLevel(log.WarnLevel)
  819. default:
  820. log.SetLevel(log.InfoLevel)
  821. }
  822. log.SetFormatter(&log.TextFormatter{
  823. FullTimestamp: true,
  824. })
  825. }
  826. // optsGuard prevents invalid options
  827. func optsGuard() error {
  828. var err error
  829. if opts.GithubOrg != "" && opts.GithubUser != "" {
  830. return fmt.Errorf("github user and organization set")
  831. } else if opts.GithubOrg != "" && opts.OwnerPath != "" {
  832. return fmt.Errorf("github organization set and local owner path")
  833. } else if opts.GithubUser != "" && opts.OwnerPath != "" {
  834. return fmt.Errorf("github user set and local owner path")
  835. } else if opts.IncludePrivate && os.Getenv("GITHUB_TOKEN") == "" && (opts.GithubOrg != "" || opts.GithubUser != "") {
  836. return fmt.Errorf("user/organization private repos require env var GITHUB_TOKEN to be set")
  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. if singleSearchRegex != nil {
  908. regexes["singleSearch"] = singleSearchRegex
  909. } else {
  910. for _, regex := range config.Regexes {
  911. regexes[regex.Description] = regexp.MustCompile(regex.Regex)
  912. }
  913. }
  914. whiteListBranches = config.Whitelist.Branches
  915. whiteListRepos = config.Whitelist.Repos
  916. whiteListCommits = make(map[string]bool)
  917. for _, commit := range config.Whitelist.Commits {
  918. whiteListCommits[commit] = true
  919. }
  920. for _, regex := range config.Whitelist.Files {
  921. whiteListFiles = append(whiteListFiles, regexp.MustCompile(regex))
  922. }
  923. for _, regex := range config.Whitelist.Regexes {
  924. whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
  925. }
  926. return nil
  927. }
  928. // getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
  929. // If --ssh-key is set then it will attempt to load the key from that path. If not,
  930. // gitleaks will use the default $HOME/.ssh/id_rsa key
  931. func getSSHAuth() (*ssh.PublicKeys, error) {
  932. var (
  933. sshKeyPath string
  934. )
  935. if opts.SSHKey != "" {
  936. sshKeyPath = opts.SSHKey
  937. } else {
  938. c, _ := user.Current()
  939. sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  940. }
  941. sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
  942. if err != nil {
  943. return nil, fmt.Errorf("unable to generate ssh key: %v", err)
  944. }
  945. return sshAuth, err
  946. }
  947. func (leak Leak) log() {
  948. b, _ := json.MarshalIndent(leak, "", " ")
  949. fmt.Println(string(b))
  950. }