repo.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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/v4/config"
  14. "github.com/zricethezav/gitleaks/v4/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. diffs := diffmatchpatch.New().DiffMain(prevFileContents, currFileContents, false)
  152. var diffContents string
  153. for _, d := range diffs {
  154. switch d.Type {
  155. case diffmatchpatch.DiffInsert:
  156. diffContents += fmt.Sprintf("%s\n", d.Text)
  157. case diffmatchpatch.DiffDelete:
  158. diffContents += fmt.Sprintf("%s\n", d.Text)
  159. }
  160. }
  161. InspectFile(diffContents, filename, c, repo)
  162. }
  163. }
  164. if err != nil {
  165. return err
  166. }
  167. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  168. return nil
  169. }
  170. // Audit is responsible for scanning the entire history (default behavior) of a
  171. // git repo. Options that can change the behavior of this function include: --commit, --depth, --branch.
  172. // See options/options.go for an explanation on these options.
  173. func (repo *Repo) Audit() error {
  174. if err := repo.setupTimeout(); err != nil {
  175. return err
  176. }
  177. if repo.cancel != nil {
  178. defer repo.cancel()
  179. }
  180. if repo.Repository == nil {
  181. return fmt.Errorf("%s repo is empty", repo.Name)
  182. }
  183. // load up alternative config if possible, if not use manager's config
  184. if repo.Manager.Opts.RepoConfig {
  185. cfg, err := repo.loadRepoConfig()
  186. if err != nil {
  187. return err
  188. }
  189. repo.config = cfg
  190. }
  191. auditTimeStart := time.Now()
  192. // audit commit patches OR all files at commit. See https://github.com/zricethezav/gitleaks/issues/326
  193. // TODO having --commit= and --files-at-commit= set should probably be guarded against
  194. if repo.Manager.Opts.Commit != "" {
  195. return inspectCommit(repo.Manager.Opts.Commit, repo, inspectCommitPatches)
  196. } else if repo.Manager.Opts.FilesAtCommit != "" {
  197. if repo.Manager.Opts.FilesAtCommit == "latest" {
  198. // Getting the latest commit on the current branch
  199. // ... retrieving the branch being pointed by HEAD
  200. ref, err := repo.Repository.Head()
  201. if err != nil {
  202. return err
  203. }
  204. return inspectCommit(ref.Hash().String(), repo, inspectFilesAtCommit)
  205. }
  206. return inspectCommit(repo.Manager.Opts.FilesAtCommit, repo, inspectFilesAtCommit)
  207. }
  208. logOpts, err := getLogOptions(repo)
  209. if err != nil {
  210. return err
  211. }
  212. cIter, err := repo.Log(logOpts)
  213. if err != nil {
  214. return err
  215. }
  216. cc := 0
  217. semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
  218. wg := sync.WaitGroup{}
  219. err = cIter.ForEach(func(c *object.Commit) error {
  220. if c == nil || repo.timeoutReached() || repo.depthReached(cc) {
  221. return storer.ErrStop
  222. }
  223. if len(c.ParentHashes) == 0 {
  224. cc++
  225. err = inspectFilesAtCommit(c, repo)
  226. if err != nil {
  227. return err
  228. }
  229. return nil
  230. }
  231. if isCommitWhiteListed(c.Hash.String(), repo.config.Whitelist.Commits) {
  232. return nil
  233. }
  234. cc++
  235. err = c.Parents().ForEach(func(parent *object.Commit) error {
  236. defer func() {
  237. if err := recover(); err != nil {
  238. // sometimes the patch generation will fail due to a known bug in
  239. // sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
  240. // Once a fix has been merged I will remove this recover.
  241. return
  242. }
  243. }()
  244. if repo.timeoutReached() {
  245. return nil
  246. }
  247. start := time.Now()
  248. patch, err := c.Patch(parent)
  249. if err != nil {
  250. return fmt.Errorf("could not generate patch")
  251. }
  252. repo.Manager.RecordTime(manager.PatchTime(howLong(start)))
  253. wg.Add(1)
  254. semaphore <- true
  255. go func(c *object.Commit, patch *object.Patch) {
  256. defer func() {
  257. <-semaphore
  258. wg.Done()
  259. }()
  260. inspectPatch(patch, c, repo)
  261. }(c, patch)
  262. return nil
  263. })
  264. if c.Hash.String() == repo.Manager.Opts.CommitTo {
  265. return storer.ErrStop
  266. }
  267. return nil
  268. })
  269. wg.Wait()
  270. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  271. repo.Manager.IncrementCommits(cc)
  272. return nil
  273. }
  274. // Open opens a local repo either from repo-path or $PWD
  275. func (repo *Repo) Open() error {
  276. if repo.Manager.Opts.RepoPath != "" {
  277. // open git repo from repo path
  278. repository, err := git.PlainOpen(repo.Manager.Opts.RepoPath)
  279. if err != nil {
  280. return err
  281. }
  282. repo.Repository = repository
  283. } else {
  284. // open git repo from PWD
  285. dir, err := os.Getwd()
  286. if err != nil {
  287. return err
  288. }
  289. repository, err := git.PlainOpen(dir)
  290. if err != nil {
  291. return err
  292. }
  293. repo.Repository = repository
  294. repo.Name = path.Base(dir)
  295. }
  296. return nil
  297. }
  298. func (repo *Repo) loadRepoConfig() (config.Config, error) {
  299. wt, err := repo.Repository.Worktree()
  300. if err != nil {
  301. return config.Config{}, err
  302. }
  303. var f billy.File
  304. f, _ = wt.Filesystem.Open(".gitleaks.toml")
  305. if f == nil {
  306. f, err = wt.Filesystem.Open("gitleaks.toml")
  307. if err != nil {
  308. return config.Config{}, fmt.Errorf("problem loading repo config: %v", err)
  309. }
  310. }
  311. defer f.Close()
  312. var tomlLoader config.TomlLoader
  313. _, err = toml.DecodeReader(f, &tomlLoader)
  314. return tomlLoader.Parse()
  315. }
  316. // timeoutReached returns true if the timeout deadline has been met. This function should be used
  317. // at the top of loops and before potentially long running goroutines (like checking inefficient regexes)
  318. func (repo *Repo) timeoutReached() bool {
  319. if repo.ctx.Err() == context.DeadlineExceeded {
  320. return true
  321. }
  322. return false
  323. }
  324. // setupTimeout parses the --timeout option and assigns a context with timeout to the manager
  325. // which will exit early if the timeout has been met.
  326. func (repo *Repo) setupTimeout() error {
  327. if repo.Manager.Opts.Timeout == "" {
  328. return nil
  329. }
  330. timeout, err := time.ParseDuration(repo.Manager.Opts.Timeout)
  331. if err != nil {
  332. return err
  333. }
  334. repo.ctx, repo.cancel = context.WithTimeout(context.Background(), timeout)
  335. go func() {
  336. select {
  337. case <-repo.ctx.Done():
  338. if repo.timeoutReached() {
  339. log.Warnf("Timeout deadline (%s) exceeded for %s", timeout.String(), repo.Name)
  340. }
  341. }
  342. }()
  343. return nil
  344. }
  345. func (repo *Repo) depthReached(i int) bool {
  346. if repo.Manager.Opts.Depth != 0 && repo.Manager.Opts.Depth == i {
  347. log.Warnf("Exceeded depth limit (%d)", i)
  348. return true
  349. }
  350. return false
  351. }