repo.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. package audit
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "fmt"
  7. "github.com/go-git/go-git/v5"
  8. "io"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "sync"
  13. "time"
  14. "github.com/zricethezav/gitleaks/v4/config"
  15. "github.com/zricethezav/gitleaks/v4/manager"
  16. "github.com/BurntSushi/toml"
  17. "github.com/go-git/go-billy/v5"
  18. "github.com/go-git/go-git/v5/plumbing"
  19. "github.com/go-git/go-git/v5/plumbing/object"
  20. "github.com/go-git/go-git/v5/plumbing/storer"
  21. "github.com/go-git/go-git/v5/storage/memory"
  22. "github.com/sergi/go-diff/diffmatchpatch"
  23. log "github.com/sirupsen/logrus"
  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. func emptyCommit() *object.Commit {
  78. return &object.Commit{
  79. Hash: plumbing.Hash{},
  80. Message: "***STAGED CHANGES***",
  81. Author: object.Signature{
  82. Name: "",
  83. Email: "",
  84. When: time.Unix(0, 0).UTC(),
  85. },
  86. }
  87. }
  88. // auditEmpty audits an empty repo without any commits. See https://github.com/zricethezav/gitleaks/issues/352
  89. func (repo *Repo) auditEmpty() error {
  90. auditTimeStart := time.Now()
  91. wt, err := repo.Worktree()
  92. if err != nil {
  93. return err
  94. }
  95. status, err := wt.Status()
  96. for fn := range status {
  97. workTreeBuf := bytes.NewBuffer(nil)
  98. workTreeFile, err := wt.Filesystem.Open(fn)
  99. if err != nil {
  100. continue
  101. }
  102. if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
  103. return err
  104. }
  105. InspectFile(workTreeBuf.String(), workTreeFile.Name(), emptyCommit(), repo)
  106. }
  107. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  108. return nil
  109. }
  110. // AuditUncommitted will do a `git diff` and scan changed files that are being tracked. This is useful functionality
  111. // for a pre-commit hook so you can make sure your code does not have any leaks before committing.
  112. func (repo *Repo) AuditUncommitted() error {
  113. // load up alternative config if possible, if not use manager's config
  114. if repo.Manager.Opts.RepoConfig {
  115. cfg, err := repo.loadRepoConfig()
  116. if err != nil {
  117. return err
  118. }
  119. repo.config = cfg
  120. }
  121. if err := repo.setupTimeout(); err != nil {
  122. return err
  123. }
  124. r, err := repo.Head()
  125. if err == plumbing.ErrReferenceNotFound {
  126. // possibly an empty repo, or maybe its not, either way lets scan all the files in the directory
  127. return repo.auditEmpty()
  128. } else if err != nil {
  129. return err
  130. }
  131. auditTimeStart := time.Now()
  132. c, err := repo.CommitObject(r.Hash())
  133. if err != nil {
  134. return err
  135. }
  136. // Staged change so the commit details do not yet exist. Insert empty defaults.
  137. c.Hash = plumbing.Hash{}
  138. c.Message = "***STAGED CHANGES***"
  139. c.Author.Name = ""
  140. c.Author.Email = ""
  141. c.Author.When = time.Unix(0, 0).UTC()
  142. prevTree, err := c.Tree()
  143. if err != nil {
  144. return err
  145. }
  146. wt, err := repo.Worktree()
  147. if err != nil {
  148. return err
  149. }
  150. status, err := wt.Status()
  151. for fn, state := range status {
  152. var (
  153. prevFileContents string
  154. currFileContents string
  155. filename string
  156. )
  157. if state.Staging != git.Untracked {
  158. if state.Staging == git.Deleted {
  159. // file in staging has been deleted, aka it is not on the filesystem
  160. // so the contents of the file are ""
  161. currFileContents = ""
  162. } else {
  163. workTreeBuf := bytes.NewBuffer(nil)
  164. workTreeFile, err := wt.Filesystem.Open(fn)
  165. if err != nil {
  166. continue
  167. }
  168. if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
  169. return err
  170. }
  171. currFileContents = workTreeBuf.String()
  172. filename = workTreeFile.Name()
  173. }
  174. // get files at HEAD state
  175. prevFile, err := prevTree.File(fn)
  176. if err != nil {
  177. prevFileContents = ""
  178. } else {
  179. prevFileContents, err = prevFile.Contents()
  180. if err != nil {
  181. return err
  182. }
  183. if filename == "" {
  184. filename = prevFile.Name
  185. }
  186. }
  187. diffs := diffmatchpatch.New().DiffMain(prevFileContents, currFileContents, false)
  188. var diffContents string
  189. for _, d := range diffs {
  190. switch d.Type {
  191. case diffmatchpatch.DiffInsert:
  192. diffContents += fmt.Sprintf("%s\n", d.Text)
  193. case diffmatchpatch.DiffDelete:
  194. diffContents += fmt.Sprintf("%s\n", d.Text)
  195. }
  196. }
  197. InspectFile(diffContents, filename, c, repo)
  198. }
  199. }
  200. if err != nil {
  201. return err
  202. }
  203. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  204. return nil
  205. }
  206. // Audit is responsible for scanning the entire history (default behavior) of a
  207. // git repo. Options that can change the behavior of this function include: --commit, --depth, --branch.
  208. // See options/options.go for an explanation on these options.
  209. func (repo *Repo) Audit() error {
  210. if err := repo.setupTimeout(); err != nil {
  211. return err
  212. }
  213. if repo.cancel != nil {
  214. defer repo.cancel()
  215. }
  216. if repo.Repository == nil {
  217. return fmt.Errorf("%s repo is empty", repo.Name)
  218. }
  219. // load up alternative config if possible, if not use manager's config
  220. if repo.Manager.Opts.RepoConfig {
  221. cfg, err := repo.loadRepoConfig()
  222. if err != nil {
  223. return err
  224. }
  225. repo.config = cfg
  226. }
  227. auditTimeStart := time.Now()
  228. // audit commit patches OR all files at commit. See https://github.com/zricethezav/gitleaks/issues/326
  229. if repo.Manager.Opts.Commit != "" {
  230. return inspectCommit(repo.Manager.Opts.Commit, repo, inspectCommitPatches)
  231. } else if repo.Manager.Opts.FilesAtCommit != "" {
  232. return inspectCommit(repo.Manager.Opts.FilesAtCommit, repo, inspectFilesAtCommit)
  233. }
  234. logOpts, err := getLogOptions(repo)
  235. if err != nil {
  236. return err
  237. }
  238. cIter, err := repo.Log(logOpts)
  239. if err != nil {
  240. return err
  241. }
  242. cc := 0
  243. semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
  244. wg := sync.WaitGroup{}
  245. err = cIter.ForEach(func(c *object.Commit) error {
  246. if c == nil || repo.timeoutReached() || repo.depthReached(cc) {
  247. return storer.ErrStop
  248. }
  249. if len(c.ParentHashes) == 0 {
  250. cc++
  251. err = inspectFilesAtCommit(c, repo)
  252. if err != nil {
  253. return err
  254. }
  255. return nil
  256. }
  257. if isCommitWhiteListed(c.Hash.String(), repo.config.Whitelist.Commits) {
  258. return nil
  259. }
  260. cc++
  261. err = c.Parents().ForEach(func(parent *object.Commit) error {
  262. defer func() {
  263. if err := recover(); err != nil {
  264. // sometimes the patch generation will fail due to a known bug in
  265. // sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
  266. // Once a fix has been merged I will remove this recover.
  267. return
  268. }
  269. }()
  270. if repo.timeoutReached() {
  271. return nil
  272. }
  273. start := time.Now()
  274. patch, err := c.Patch(parent)
  275. if err != nil {
  276. return fmt.Errorf("could not generate patch")
  277. }
  278. repo.Manager.RecordTime(manager.PatchTime(howLong(start)))
  279. wg.Add(1)
  280. semaphore <- true
  281. go func(c *object.Commit, patch *object.Patch) {
  282. defer func() {
  283. <-semaphore
  284. wg.Done()
  285. }()
  286. inspectPatch(patch, c, repo)
  287. }(c, patch)
  288. return nil
  289. })
  290. if c.Hash.String() == repo.Manager.Opts.CommitTo {
  291. return storer.ErrStop
  292. }
  293. return nil
  294. })
  295. wg.Wait()
  296. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  297. repo.Manager.IncrementCommits(cc)
  298. return nil
  299. }
  300. // Open opens a local repo either from repo-path or $PWD
  301. func (repo *Repo) Open() error {
  302. if repo.Manager.Opts.RepoPath != "" {
  303. // open git repo from repo path
  304. repository, err := git.PlainOpen(repo.Manager.Opts.RepoPath)
  305. if err != nil {
  306. return err
  307. }
  308. repo.Repository = repository
  309. } else {
  310. // open git repo from PWD
  311. dir, err := os.Getwd()
  312. if err != nil {
  313. return err
  314. }
  315. repository, err := git.PlainOpen(dir)
  316. if err != nil {
  317. return err
  318. }
  319. repo.Repository = repository
  320. repo.Name = path.Base(dir)
  321. }
  322. return nil
  323. }
  324. func (repo *Repo) loadRepoConfig() (config.Config, error) {
  325. wt, err := repo.Repository.Worktree()
  326. if err != nil {
  327. return config.Config{}, err
  328. }
  329. var f billy.File
  330. f, _ = wt.Filesystem.Open(".gitleaks.toml")
  331. if f == nil {
  332. f, err = wt.Filesystem.Open("gitleaks.toml")
  333. if err != nil {
  334. return config.Config{}, fmt.Errorf("problem loading repo config: %v", err)
  335. }
  336. }
  337. defer f.Close()
  338. var tomlLoader config.TomlLoader
  339. _, err = toml.DecodeReader(f, &tomlLoader)
  340. return tomlLoader.Parse()
  341. }
  342. // timeoutReached returns true if the timeout deadline has been met. This function should be used
  343. // at the top of loops and before potentially long running goroutines (like checking inefficient regexes)
  344. func (repo *Repo) timeoutReached() bool {
  345. if repo.ctx.Err() == context.DeadlineExceeded {
  346. return true
  347. }
  348. return false
  349. }
  350. // setupTimeout parses the --timeout option and assigns a context with timeout to the manager
  351. // which will exit early if the timeout has been met.
  352. func (repo *Repo) setupTimeout() error {
  353. if repo.Manager.Opts.Timeout == "" {
  354. return nil
  355. }
  356. timeout, err := time.ParseDuration(repo.Manager.Opts.Timeout)
  357. if err != nil {
  358. return err
  359. }
  360. repo.ctx, repo.cancel = context.WithTimeout(context.Background(), timeout)
  361. go func() {
  362. select {
  363. case <-repo.ctx.Done():
  364. if repo.timeoutReached() {
  365. log.Warnf("Timeout deadline (%s) exceeded for %s", timeout.String(), repo.Name)
  366. }
  367. }
  368. }()
  369. return nil
  370. }
  371. func (repo *Repo) depthReached(i int) bool {
  372. if repo.Manager.Opts.Depth != 0 && repo.Manager.Opts.Depth == i {
  373. log.Warnf("Exceeded depth limit (%d)", i)
  374. return true
  375. }
  376. return false
  377. }