repo.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. 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. // TODO having --commit= and --fites-at-commit= set should probably be guarded against
  230. if repo.Manager.Opts.Commit != "" {
  231. return inspectCommit(repo.Manager.Opts.Commit, repo, inspectCommitPatches)
  232. } else if repo.Manager.Opts.FilesAtCommit != "" {
  233. return inspectCommit(repo.Manager.Opts.FilesAtCommit, repo, inspectFilesAtCommit)
  234. }
  235. logOpts, err := getLogOptions(repo)
  236. if err != nil {
  237. return err
  238. }
  239. cIter, err := repo.Log(logOpts)
  240. if err != nil {
  241. return err
  242. }
  243. cc := 0
  244. semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
  245. wg := sync.WaitGroup{}
  246. err = cIter.ForEach(func(c *object.Commit) error {
  247. if c == nil || repo.timeoutReached() || repo.depthReached(cc) {
  248. return storer.ErrStop
  249. }
  250. if len(c.ParentHashes) == 0 {
  251. cc++
  252. err = inspectFilesAtCommit(c, repo)
  253. if err != nil {
  254. return err
  255. }
  256. return nil
  257. }
  258. if isCommitWhiteListed(c.Hash.String(), repo.config.Whitelist.Commits) {
  259. return nil
  260. }
  261. cc++
  262. err = c.Parents().ForEach(func(parent *object.Commit) error {
  263. defer func() {
  264. if err := recover(); err != nil {
  265. // sometimes the patch generation will fail due to a known bug in
  266. // sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
  267. // Once a fix has been merged I will remove this recover.
  268. return
  269. }
  270. }()
  271. if repo.timeoutReached() {
  272. return nil
  273. }
  274. start := time.Now()
  275. patch, err := c.Patch(parent)
  276. if err != nil {
  277. return fmt.Errorf("could not generate patch")
  278. }
  279. repo.Manager.RecordTime(manager.PatchTime(howLong(start)))
  280. wg.Add(1)
  281. semaphore <- true
  282. go func(c *object.Commit, patch *object.Patch) {
  283. defer func() {
  284. <-semaphore
  285. wg.Done()
  286. }()
  287. inspectPatch(patch, c, repo)
  288. }(c, patch)
  289. return nil
  290. })
  291. if c.Hash.String() == repo.Manager.Opts.CommitTo {
  292. return storer.ErrStop
  293. }
  294. return nil
  295. })
  296. wg.Wait()
  297. repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
  298. repo.Manager.IncrementCommits(cc)
  299. return nil
  300. }
  301. // Open opens a local repo either from repo-path or $PWD
  302. func (repo *Repo) Open() error {
  303. if repo.Manager.Opts.RepoPath != "" {
  304. // open git repo from repo path
  305. repository, err := git.PlainOpen(repo.Manager.Opts.RepoPath)
  306. if err != nil {
  307. return err
  308. }
  309. repo.Repository = repository
  310. } else {
  311. // open git repo from PWD
  312. dir, err := os.Getwd()
  313. if err != nil {
  314. return err
  315. }
  316. repository, err := git.PlainOpen(dir)
  317. if err != nil {
  318. return err
  319. }
  320. repo.Repository = repository
  321. repo.Name = path.Base(dir)
  322. }
  323. return nil
  324. }
  325. func (repo *Repo) loadRepoConfig() (config.Config, error) {
  326. wt, err := repo.Repository.Worktree()
  327. if err != nil {
  328. return config.Config{}, err
  329. }
  330. var f billy.File
  331. f, _ = wt.Filesystem.Open(".gitleaks.toml")
  332. if f == nil {
  333. f, err = wt.Filesystem.Open("gitleaks.toml")
  334. if err != nil {
  335. return config.Config{}, fmt.Errorf("problem loading repo config: %v", err)
  336. }
  337. }
  338. defer f.Close()
  339. var tomlLoader config.TomlLoader
  340. _, err = toml.DecodeReader(f, &tomlLoader)
  341. return tomlLoader.Parse()
  342. }
  343. // timeoutReached returns true if the timeout deadline has been met. This function should be used
  344. // at the top of loops and before potentially long running goroutines (like checking inefficient regexes)
  345. func (repo *Repo) timeoutReached() bool {
  346. if repo.ctx.Err() == context.DeadlineExceeded {
  347. return true
  348. }
  349. return false
  350. }
  351. // setupTimeout parses the --timeout option and assigns a context with timeout to the manager
  352. // which will exit early if the timeout has been met.
  353. func (repo *Repo) setupTimeout() error {
  354. if repo.Manager.Opts.Timeout == "" {
  355. return nil
  356. }
  357. timeout, err := time.ParseDuration(repo.Manager.Opts.Timeout)
  358. if err != nil {
  359. return err
  360. }
  361. repo.ctx, repo.cancel = context.WithTimeout(context.Background(), timeout)
  362. go func() {
  363. select {
  364. case <-repo.ctx.Done():
  365. if repo.timeoutReached() {
  366. log.Warnf("Timeout deadline (%s) exceeded for %s", timeout.String(), repo.Name)
  367. }
  368. }
  369. }()
  370. return nil
  371. }
  372. func (repo *Repo) depthReached(i int) bool {
  373. if repo.Manager.Opts.Depth != 0 && repo.Manager.Opts.Depth == i {
  374. log.Warnf("Exceeded depth limit (%d)", i)
  375. return true
  376. }
  377. return false
  378. }