main.go 28 KB

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