repo.go 10 KB

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