repo.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package audit
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "fmt"
  6. "github.com/BurntSushi/toml"
  7. "github.com/sergi/go-diff/diffmatchpatch"
  8. log "github.com/sirupsen/logrus"
  9. "github.com/zricethezav/gitleaks/config"
  10. "github.com/zricethezav/gitleaks/manager"
  11. "gopkg.in/src-d/go-billy.v4"
  12. "gopkg.in/src-d/go-git.v4"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. "gopkg.in/src-d/go-git.v4/plumbing/object"
  15. "gopkg.in/src-d/go-git.v4/plumbing/storer"
  16. "gopkg.in/src-d/go-git.v4/storage/memory"
  17. "io"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "sync"
  22. "time"
  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. auditTimeStart := time.Now()
  76. r, err := repo.Head()
  77. if err != nil {
  78. return err
  79. }
  80. c, err := repo.CommitObject(r.Hash())
  81. if err != nil {
  82. return err
  83. }
  84. prevTree, err := c.Tree()
  85. if err != nil {
  86. return err
  87. }
  88. wt, err := repo.Worktree()
  89. if err != nil {
  90. return err
  91. }
  92. status, err := wt.Status()
  93. for fn, state := range status {
  94. var (
  95. prevFileContents string
  96. currFileContents string
  97. filename string
  98. )
  99. if state.Staging != git.Untracked {
  100. if state.Staging == git.Deleted {
  101. // file in staging has been deleted, aka it is not on the filesystem
  102. // so the contents of the file are ""
  103. currFileContents = ""
  104. } else {
  105. workTreeBuf := bytes.NewBuffer(nil)
  106. workTreeFile, err := wt.Filesystem.Open(fn)
  107. if err != nil {
  108. continue
  109. }
  110. if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
  111. return err
  112. }
  113. currFileContents = workTreeBuf.String()
  114. filename = workTreeFile.Name()
  115. }
  116. // get files at HEAD state
  117. prevFile, err := prevTree.File(fn)
  118. if err != nil {
  119. prevFileContents = ""
  120. } else {
  121. prevFileContents, err = prevFile.Contents()
  122. if err != nil {
  123. return err
  124. }
  125. if filename == "" {
  126. filename = prevFile.Name
  127. }
  128. }
  129. dmp := diffmatchpatch.New()
  130. diffs := dmp.DiffMain(prevFileContents, currFileContents, false)
  131. var diffContents string
  132. for _, d := range diffs {
  133. switch d.Type {
  134. case diffmatchpatch.DiffInsert:
  135. diffContents += fmt.Sprintf("%s\n", d.Text)
  136. case diffmatchpatch.DiffDelete:
  137. diffContents += fmt.Sprintf("%s\n", d.Text)
  138. }
  139. }
  140. InspectString(diffContents, c, repo, filename)
  141. }
  142. }
  143. if err != nil {
  144. return err
  145. }
  146. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  147. return nil
  148. }
  149. // Audit is responsible for scanning the entire history (default behavior) of a
  150. // git repo. Options that can change the behavior of this function include: --commit, --depth, --branch.
  151. // See options/options.go for an explanation on these options.
  152. func (repo *Repo) Audit() error {
  153. if repo.Repository == nil {
  154. return fmt.Errorf("%s repo is empty", repo.Name)
  155. }
  156. // load up alternative config if possible, if not use manager's config
  157. if repo.Manager.Opts.RepoConfig {
  158. cfg, err := repo.loadRepoConfig()
  159. if err != nil {
  160. return err
  161. }
  162. repo.config = cfg
  163. }
  164. auditTimeStart := time.Now()
  165. // audit single Commit
  166. if repo.Manager.Opts.Commit != "" {
  167. h := plumbing.NewHash(repo.Manager.Opts.Commit)
  168. c, err := repo.CommitObject(h)
  169. if err != nil {
  170. return err
  171. }
  172. err = inspectCommit(c, repo)
  173. if err != nil {
  174. return err
  175. }
  176. return nil
  177. }
  178. logOpts, err := getLogOptions(repo)
  179. if err != nil {
  180. return err
  181. }
  182. cIter, err := repo.Log(logOpts)
  183. if err != nil {
  184. return err
  185. }
  186. //checker := make(map[string]bool)
  187. cc := 0
  188. semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
  189. wg := sync.WaitGroup{}
  190. err = cIter.ForEach(func(c *object.Commit) error {
  191. if c == nil {
  192. return storer.ErrStop
  193. }
  194. if len(c.ParentHashes) == 0 {
  195. cc++
  196. err = inspectCommit(c, repo)
  197. if err != nil {
  198. return err
  199. }
  200. return nil
  201. }
  202. if isCommitWhiteListed(c.Hash.String(), repo.config.Whitelist.Commits) {
  203. return nil
  204. }
  205. cc++
  206. err = c.Parents().ForEach(func(parent *object.Commit) error {
  207. start := time.Now()
  208. patch, err := c.Patch(parent)
  209. if err != nil {
  210. return fmt.Errorf("could not generate patch")
  211. }
  212. repo.Manager.RecordTime(manager.PatchTime(howLong(start)))
  213. wg.Add(1)
  214. semaphore <- true
  215. go func(c *object.Commit, patch *object.Patch) {
  216. defer func() {
  217. <-semaphore
  218. wg.Done()
  219. }()
  220. inspectPatch(patch, c, repo)
  221. }(c, patch)
  222. return nil
  223. })
  224. return nil
  225. })
  226. wg.Wait()
  227. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  228. repo.Manager.IncrementCommits(cc)
  229. return nil
  230. }
  231. // Open opens a local repo either from repo-path or $PWD
  232. func (repo *Repo) Open() error {
  233. if repo.Manager.Opts.RepoPath != "" {
  234. // open git repo from repo path
  235. repository, err := git.PlainOpen(repo.Manager.Opts.RepoPath)
  236. if err != nil {
  237. return err
  238. }
  239. repo.Repository = repository
  240. } else {
  241. // open git repo from PWD
  242. dir, err := os.Getwd()
  243. if err != nil {
  244. return err
  245. }
  246. repository, err := git.PlainOpen(dir)
  247. if err != nil {
  248. return err
  249. }
  250. repo.Repository = repository
  251. repo.Name = path.Base(dir)
  252. }
  253. return nil
  254. }
  255. func (repo *Repo) loadRepoConfig() (config.Config, error) {
  256. wt, err := repo.Repository.Worktree()
  257. if err != nil {
  258. return config.Config{}, err
  259. }
  260. var f billy.File
  261. f, _ = wt.Filesystem.Open(".gitleaks.toml")
  262. if f == nil {
  263. f, err = wt.Filesystem.Open("gitleaks.toml")
  264. if err != nil {
  265. return config.Config{}, fmt.Errorf("problem loading repo config: %v", err)
  266. }
  267. }
  268. defer f.Close()
  269. var tomlLoader config.TomlLoader
  270. _, err = toml.DecodeReader(f, &tomlLoader)
  271. return tomlLoader.Parse()
  272. }