repo.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package audit
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "sync"
  11. "time"
  12. "github.com/zricethezav/gitleaks/config"
  13. "github.com/zricethezav/gitleaks/manager"
  14. "github.com/BurntSushi/toml"
  15. "github.com/sergi/go-diff/diffmatchpatch"
  16. log "github.com/sirupsen/logrus"
  17. "gopkg.in/src-d/go-billy.v4"
  18. "gopkg.in/src-d/go-git.v4"
  19. "gopkg.in/src-d/go-git.v4/plumbing"
  20. "gopkg.in/src-d/go-git.v4/plumbing/object"
  21. "gopkg.in/src-d/go-git.v4/plumbing/storer"
  22. "gopkg.in/src-d/go-git.v4/storage/memory"
  23. )
  24. // Repo wraps a *git.Repository object in addition to a manager object and the name of the repo.
  25. // Commits are inspected from the *git.Repository object. If a commit is found then we send it
  26. // via the manager LeakChan where the manager receives and keeps track of all leaks.
  27. type Repo struct {
  28. *git.Repository
  29. // config is used when the --repo-config option is set.
  30. // This allows users to load up configs specific to their repos.
  31. // Imagine the scenario where you are doing an audit of a large organization
  32. // and you want certain repos to look for specific rules. If those specific repos
  33. // have a gitleaks.toml or .gitleaks.toml config then those configs will be used specifically
  34. // for those repo audits.
  35. config config.Config
  36. Name string
  37. Manager *manager.Manager
  38. }
  39. // NewRepo initializes and returns a Repo struct.
  40. func NewRepo(m *manager.Manager) *Repo {
  41. return &Repo{
  42. Manager: m,
  43. config: m.Config,
  44. }
  45. }
  46. // Clone will clone a repo and return a Repo struct which contains a go-git repo. The clone method
  47. // is determined by the clone options set in Manager.metadata.cloneOptions
  48. func (repo *Repo) Clone(cloneOption *git.CloneOptions) error {
  49. var (
  50. repository *git.Repository
  51. err error
  52. )
  53. if cloneOption == nil {
  54. cloneOption = repo.Manager.CloneOptions
  55. }
  56. log.Infof("cloning... %s", cloneOption.URL)
  57. start := time.Now()
  58. if repo.Manager.CloneDir != "" {
  59. clonePath := fmt.Sprintf("%s/%x", repo.Manager.CloneDir, md5.Sum([]byte(time.Now().String())))
  60. repository, err = git.PlainClone(clonePath, false, cloneOption)
  61. } else {
  62. repository, err = git.Clone(memory.NewStorage(), nil, cloneOption)
  63. }
  64. if err != nil {
  65. return err
  66. }
  67. repo.Name = filepath.Base(repo.Manager.Opts.Repo)
  68. repo.Repository = repository
  69. repo.Manager.RecordTime(manager.CloneTime(howLong(start)))
  70. return nil
  71. }
  72. // AuditUncommitted will do a `git diff` and scan changed files that are being tracked. This is useful functionality
  73. // for a pre-commit hook so you can make sure your code does not have any leaks before committing.
  74. func (repo *Repo) AuditUncommitted() error {
  75. // load up alternative config if possible, if not use manager's config
  76. if repo.Manager.Opts.RepoConfig {
  77. cfg, err := repo.loadRepoConfig()
  78. if err != nil {
  79. return err
  80. }
  81. repo.config = cfg
  82. }
  83. auditTimeStart := time.Now()
  84. r, err := repo.Head()
  85. if err != nil {
  86. return err
  87. }
  88. c, err := repo.CommitObject(r.Hash())
  89. if err != nil {
  90. return err
  91. }
  92. prevTree, err := c.Tree()
  93. if err != nil {
  94. return err
  95. }
  96. wt, err := repo.Worktree()
  97. if err != nil {
  98. return err
  99. }
  100. status, err := wt.Status()
  101. for fn, state := range status {
  102. var (
  103. prevFileContents string
  104. currFileContents string
  105. filename string
  106. )
  107. if state.Staging != git.Untracked {
  108. if state.Staging == git.Deleted {
  109. // file in staging has been deleted, aka it is not on the filesystem
  110. // so the contents of the file are ""
  111. currFileContents = ""
  112. } else {
  113. workTreeBuf := bytes.NewBuffer(nil)
  114. workTreeFile, err := wt.Filesystem.Open(fn)
  115. if err != nil {
  116. continue
  117. }
  118. if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
  119. return err
  120. }
  121. currFileContents = workTreeBuf.String()
  122. filename = workTreeFile.Name()
  123. }
  124. // get files at HEAD state
  125. prevFile, err := prevTree.File(fn)
  126. if err != nil {
  127. prevFileContents = ""
  128. } else {
  129. prevFileContents, err = prevFile.Contents()
  130. if err != nil {
  131. return err
  132. }
  133. if filename == "" {
  134. filename = prevFile.Name
  135. }
  136. }
  137. if fileMatched(filename, repo.config.Whitelist.File) {
  138. log.Debugf("whitelisted file found, skipping audit of file: %s", filename)
  139. } else if fileMatched(filename, repo.config.FileRegex) {
  140. repo.Manager.SendLeaks(manager.Leak{
  141. Line: "N/A",
  142. Offender: filename,
  143. Commit: c.Hash.String(),
  144. Repo: repo.Name,
  145. Rule: "file regex matched" + repo.config.FileRegex.String(),
  146. Author: c.Author.Name,
  147. Email: c.Author.Email,
  148. Date: c.Author.When,
  149. File: filename,
  150. })
  151. } else {
  152. dmp := diffmatchpatch.New()
  153. diffs := dmp.DiffMain(prevFileContents, currFileContents, false)
  154. var diffContents string
  155. for _, d := range diffs {
  156. switch d.Type {
  157. case diffmatchpatch.DiffInsert:
  158. diffContents += fmt.Sprintf("%s\n", d.Text)
  159. case diffmatchpatch.DiffDelete:
  160. diffContents += fmt.Sprintf("%s\n", d.Text)
  161. }
  162. }
  163. InspectString(diffContents, c, repo, filename)
  164. }
  165. }
  166. }
  167. if err != nil {
  168. return err
  169. }
  170. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  171. return nil
  172. }
  173. // Audit is responsible for scanning the entire history (default behavior) of a
  174. // git repo. Options that can change the behavior of this function include: --commit, --depth, --branch.
  175. // See options/options.go for an explanation on these options.
  176. func (repo *Repo) Audit() error {
  177. if repo.Repository == nil {
  178. return fmt.Errorf("%s repo is empty", repo.Name)
  179. }
  180. // load up alternative config if possible, if not use manager's config
  181. if repo.Manager.Opts.RepoConfig {
  182. cfg, err := repo.loadRepoConfig()
  183. if err != nil {
  184. return err
  185. }
  186. repo.config = cfg
  187. }
  188. auditTimeStart := time.Now()
  189. // audit single Commit
  190. if repo.Manager.Opts.Commit != "" {
  191. h := plumbing.NewHash(repo.Manager.Opts.Commit)
  192. c, err := repo.CommitObject(h)
  193. if err != nil {
  194. return err
  195. }
  196. err = inspectCommit(c, repo)
  197. if err != nil {
  198. return err
  199. }
  200. return nil
  201. }
  202. logOpts, err := getLogOptions(repo)
  203. if err != nil {
  204. return err
  205. }
  206. cIter, err := repo.Log(logOpts)
  207. if err != nil {
  208. return err
  209. }
  210. cc := 0
  211. semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
  212. wg := sync.WaitGroup{}
  213. err = cIter.ForEach(func(c *object.Commit) error {
  214. if c == nil {
  215. return storer.ErrStop
  216. }
  217. if len(c.ParentHashes) == 0 {
  218. cc++
  219. err = inspectCommit(c, repo)
  220. if err != nil {
  221. return err
  222. }
  223. return nil
  224. }
  225. if isCommitWhiteListed(c.Hash.String(), repo.config.Whitelist.Commits) {
  226. return nil
  227. }
  228. cc++
  229. err = c.Parents().ForEach(func(parent *object.Commit) error {
  230. defer func() {
  231. if err := recover(); err != nil {
  232. // sometimes the patch generation will fail due to a known bug in
  233. // sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
  234. // Once a fix has been merged I will remove this recover.
  235. return
  236. }
  237. }()
  238. start := time.Now()
  239. patch, err := c.Patch(parent)
  240. if err != nil {
  241. return fmt.Errorf("could not generate patch")
  242. }
  243. repo.Manager.RecordTime(manager.PatchTime(howLong(start)))
  244. wg.Add(1)
  245. semaphore <- true
  246. go func(c *object.Commit, patch *object.Patch) {
  247. defer func() {
  248. <-semaphore
  249. wg.Done()
  250. }()
  251. inspectPatch(patch, c, repo)
  252. }(c, patch)
  253. return nil
  254. })
  255. return nil
  256. })
  257. wg.Wait()
  258. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  259. repo.Manager.IncrementCommits(cc)
  260. return nil
  261. }
  262. // Open opens a local repo either from repo-path or $PWD
  263. func (repo *Repo) Open() error {
  264. if repo.Manager.Opts.RepoPath != "" {
  265. // open git repo from repo path
  266. repository, err := git.PlainOpen(repo.Manager.Opts.RepoPath)
  267. if err != nil {
  268. return err
  269. }
  270. repo.Repository = repository
  271. } else {
  272. // open git repo from PWD
  273. dir, err := os.Getwd()
  274. if err != nil {
  275. return err
  276. }
  277. repository, err := git.PlainOpen(dir)
  278. if err != nil {
  279. return err
  280. }
  281. repo.Repository = repository
  282. repo.Name = path.Base(dir)
  283. }
  284. return nil
  285. }
  286. func (repo *Repo) loadRepoConfig() (config.Config, error) {
  287. wt, err := repo.Repository.Worktree()
  288. if err != nil {
  289. return config.Config{}, err
  290. }
  291. var f billy.File
  292. f, _ = wt.Filesystem.Open(".gitleaks.toml")
  293. if f == nil {
  294. f, err = wt.Filesystem.Open("gitleaks.toml")
  295. if err != nil {
  296. return config.Config{}, fmt.Errorf("problem loading repo config: %v", err)
  297. }
  298. }
  299. defer f.Close()
  300. var tomlLoader config.TomlLoader
  301. _, err = toml.DecodeReader(f, &tomlLoader)
  302. return tomlLoader.Parse()
  303. }