repo.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "sync"
  12. )
  13. // Repo represents a git repo
  14. type Repo struct {
  15. name string
  16. url string
  17. path string
  18. status string // TODO
  19. leaks []Leak
  20. reportPath string
  21. }
  22. // Leak struct for reporting
  23. type Leak struct {
  24. Line string `json:"line"`
  25. Commit string `json:"commit"`
  26. Offender string `json:"string"`
  27. Reason string `json:"reason"`
  28. Msg string `json:"commitMsg"`
  29. Time string `json:"time"`
  30. Author string `json:"author"`
  31. File string `json:"file"`
  32. RepoURL string `json:"repoURL"`
  33. }
  34. // Commit represents a git commit
  35. type Commit struct {
  36. Hash string
  37. Author string
  38. Time string
  39. Msg string
  40. }
  41. // newRepo creates a new repo based on name, url, and a clone path
  42. func newRepo(name string, url string, path string) *Repo {
  43. repo := &Repo{
  44. name: name,
  45. url: url,
  46. path: path,
  47. reportPath: opts.ReportPath,
  48. }
  49. return repo
  50. }
  51. // rmTmp removes the temporary directory: repo.path
  52. func (repo *Repo) rmTmp() {
  53. log.Printf("removing tmp gitleaks repo %s\n", repo.path)
  54. os.Remove(repo.path)
  55. }
  56. // Audit operates on a single repo and searches the full or partial history of the repo.
  57. // A semaphore is declared for every repo to bind concurrency. If unbounded, the system will throw a
  58. // `too many open files` error. Eventually, gitleaks should use src-d/go-git to avoid shelling out
  59. // commands so that users could opt for doing all clones/diffs in memory.
  60. // Audit also declares two WaitGroups, one for distributing regex/entropy checks, and one for receiving
  61. // the leaks if there are any. This could be done a little more elegantly in the future.
  62. func (repo *Repo) audit() (bool, error) {
  63. var (
  64. out []byte
  65. err error
  66. commitWG sync.WaitGroup
  67. gitLeakReceiverWG sync.WaitGroup
  68. gitLeaksChan = make(chan Leak)
  69. leaks []Leak
  70. semaphoreChan = make(chan struct{}, opts.Concurrency)
  71. leaksPst bool
  72. )
  73. if opts.Tmp {
  74. defer repo.rmTmp()
  75. }
  76. dotGitPath := filepath.Join(repo.path, ".git")
  77. // Navigate to proper location to being audit. Clone repo
  78. // if not present, otherwise fetch for new changes.
  79. if _, err := os.Stat(dotGitPath); os.IsNotExist(err) {
  80. if opts.LocalMode {
  81. return false, fmt.Errorf("%s does not exist", repo.path)
  82. }
  83. // no repo present, clone it
  84. log.Printf("cloning \x1b[37;1m%s\x1b[0m into %s...\n", repo.url, repo.path)
  85. err = exec.Command("git", "clone", repo.url, repo.path).Run()
  86. if err != nil {
  87. return false, fmt.Errorf("cannot clone %s into %s", repo.url, repo.path)
  88. }
  89. } else {
  90. log.Printf("fetching \x1b[37;1m%s\x1b[0m from %s ...\n", repo.name, repo.path)
  91. err = os.Chdir(fmt.Sprintf(repo.path))
  92. if err != nil {
  93. return false, fmt.Errorf("cannot navigate to %s", repo.path)
  94. }
  95. err = exec.Command("git", "fetch").Run()
  96. if err != nil {
  97. return false, fmt.Errorf("cannot fetch %s from %s", repo.url, repo.path)
  98. }
  99. }
  100. err = os.Chdir(fmt.Sprintf(repo.path))
  101. if err != nil {
  102. return false, fmt.Errorf("cannot navigate to %s", repo.path)
  103. }
  104. gitFormat := "--format=%H%n%an%n%s%n%ci"
  105. out, err = exec.Command("git", "rev-list", "--all",
  106. "--remotes", "--topo-order", gitFormat).Output()
  107. if err != nil {
  108. return false, fmt.Errorf("could not retreive rev-list from %s", repo.name)
  109. }
  110. revListLines := bytes.Split(out, []byte("\n"))
  111. commits := parseRevList(revListLines)
  112. for _, commit := range commits {
  113. if commit.Hash == "" {
  114. continue
  115. }
  116. commitWG.Add(1)
  117. go auditDiff(commit, repo, &commitWG, &gitLeakReceiverWG,
  118. semaphoreChan, gitLeaksChan)
  119. if commit.Hash == opts.SinceCommit {
  120. break
  121. }
  122. }
  123. go reportAggregator(&gitLeakReceiverWG, gitLeaksChan, &leaks)
  124. commitWG.Wait()
  125. gitLeakReceiverWG.Wait()
  126. if len(leaks) != 0 {
  127. leaksPst = true
  128. log.Printf("\x1b[31;2mLEAKS DETECTED for %s\x1b[0m!\n", repo.name)
  129. } else {
  130. log.Printf("No Leaks detected for \x1b[32;2m%s\x1b[0m\n", repo.name)
  131. }
  132. if opts.ReportPath != "" && len(leaks) != 0 {
  133. err = repo.writeReport(leaks)
  134. if err != nil {
  135. return leaksPst, fmt.Errorf("could not write report to %s", opts.ReportPath)
  136. }
  137. }
  138. return leaksPst, nil
  139. }
  140. // Used by audit, writeReport will generate a report and write it out to
  141. // --report-path=<path> if specified, otherwise a report will be generated to
  142. // $PWD/<repo_name>_leaks.json. No report will be generated if
  143. // no leaks have been found or --report-out is not set.
  144. func (repo *Repo) writeReport(leaks []Leak) error {
  145. reportJSON, _ := json.MarshalIndent(leaks, "", "\t")
  146. if _, err := os.Stat(opts.ReportPath); os.IsNotExist(err) {
  147. os.MkdirAll(opts.ReportPath, os.ModePerm)
  148. }
  149. reportFileName := fmt.Sprintf("%s_leaks.json", repo.name)
  150. reportFile := filepath.Join(repo.reportPath, reportFileName)
  151. err := ioutil.WriteFile(reportFile, reportJSON, 0644)
  152. if err != nil {
  153. return err
  154. }
  155. log.Printf("report for %s written to %s", repo.name, reportFile)
  156. return nil
  157. }
  158. // parseRevList is responsible for parsing the output of
  159. // $ `git rev-list --all -remotes --topo-order --format=%H%n%an%n%s%n%ci`
  160. // sample output from the above command looks like:
  161. // ...
  162. // SHA
  163. // Author Name
  164. // Commit Msg
  165. // Commit Date
  166. // ...
  167. // Used by audit
  168. func parseRevList(revList [][]byte) []Commit {
  169. var commits []Commit
  170. for i := 0; i < len(revList)-1; i = i + 5 {
  171. commit := Commit{
  172. Hash: string(revList[i+1]),
  173. Author: string(revList[i+2]),
  174. Msg: string(revList[i+3]),
  175. Time: string(revList[i+4]),
  176. }
  177. commits = append(commits, commit)
  178. }
  179. return commits
  180. }
  181. // reportAggregator is will consume Leak messages from the gitLeaks channel and report them
  182. func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, leaks *[]Leak) {
  183. for gitLeak := range gitLeaks {
  184. *leaks = append(*leaks, gitLeak)
  185. if opts.Verbose {
  186. b, err := json.MarshalIndent(gitLeak, "", " ")
  187. if err != nil {
  188. fmt.Printf("failed to output leak: %v", err)
  189. }
  190. fmt.Println(string(b))
  191. }
  192. gitLeakReceiverWG.Done()
  193. }
  194. }
  195. // Used by audit, auditDiff is a go func responsible for diffing and auditing a commit.
  196. // Three channels are input here: 1. a semaphore to bind gitleaks, 2. a leak stream, 3. error handling (TODO)
  197. // This func performs a diff and runs regexes checks on each line of the diff.
  198. func auditDiff(currCommit Commit, repo *Repo, commitWG *sync.WaitGroup,
  199. gitLeakReceiverWG *sync.WaitGroup, semaphoreChan chan struct{},
  200. gitLeaks chan Leak) {
  201. // signal to WG this diff is done being audited
  202. defer commitWG.Done()
  203. if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil {
  204. log.Fatalf("unable to navigate to %s", repo.path)
  205. }
  206. commitCmp := fmt.Sprintf("%s^!", currCommit.Hash)
  207. semaphoreChan <- struct{}{}
  208. out, err := exec.Command("git", "diff", commitCmp).Output()
  209. <-semaphoreChan
  210. if err != nil {
  211. log.Fatalf("unable to diff for %s: %v", currCommit.Hash, err)
  212. }
  213. leaks := doChecks(string(out), currCommit, repo)
  214. if len(leaks) == 0 {
  215. return
  216. }
  217. for _, leak := range leaks {
  218. gitLeakReceiverWG.Add(1)
  219. gitLeaks <- leak
  220. }
  221. }