git.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package detect
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net/url"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "time"
  13. "github.com/gitleaks/go-gitdiff/gitdiff"
  14. "github.com/zricethezav/gitleaks/v8/cmd/scm"
  15. "github.com/zricethezav/gitleaks/v8/logging"
  16. "github.com/zricethezav/gitleaks/v8/report"
  17. "github.com/zricethezav/gitleaks/v8/sources"
  18. )
  19. func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.Finding, error) {
  20. defer cmd.Wait()
  21. var (
  22. diffFilesCh = cmd.DiffFilesCh()
  23. errCh = cmd.ErrCh()
  24. )
  25. // loop to range over both DiffFiles (stdout) and ErrCh (stderr)
  26. for diffFilesCh != nil || errCh != nil {
  27. select {
  28. case gitdiffFile, open := <-diffFilesCh:
  29. if !open {
  30. diffFilesCh = nil
  31. break
  32. }
  33. commitSHA := ""
  34. if gitdiffFile.PatchHeader != nil {
  35. commitSHA = gitdiffFile.PatchHeader.SHA
  36. if ok, c := d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
  37. logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
  38. continue
  39. }
  40. }
  41. if IsArchive(gitdiffFile.NewName) {
  42. // Check if commit is allowed
  43. d.Sema.Go(func() error {
  44. // Check out the archive blob to disk
  45. archivePath, err := cmd.CheckoutBlob(commitSHA, gitdiffFile.NewName)
  46. if err != nil {
  47. logging.Warn().Err(err).Str("file", gitdiffFile.NewName).Msg("failed to checkout blob")
  48. return nil
  49. }
  50. defer os.Remove(archivePath)
  51. targets, tmpDir, err := ExtractArchive(archivePath)
  52. if err != nil {
  53. os.RemoveAll(tmpDir)
  54. logging.Warn().Err(err).Msg("failed to extract archive")
  55. return nil
  56. }
  57. // Scan each extracted file just as you would in directory mode
  58. for _, t := range targets {
  59. // build the “inside-archive” path
  60. rel, _ := filepath.Rel(tmpDir, t.Path)
  61. rel = filepath.ToSlash(rel)
  62. // chain onto any existing VirtualPath (nested archives)
  63. if t.VirtualPath != "" {
  64. t.VirtualPath = t.VirtualPath + "/" + rel
  65. } else {
  66. t.VirtualPath = filepath.Base(gitdiffFile.NewName) + "/" + rel
  67. }
  68. // TODO this isn't a great solution, and it would be nice to
  69. // have a better way to handle this.
  70. // update taget to include git information:
  71. t.Source = "github-archive"
  72. t.GitInfo.Author = gitdiffFile.PatchHeader.Author.Name
  73. t.GitInfo.Commit = commitSHA
  74. t.GitInfo.Date = gitdiffFile.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
  75. t.GitInfo.Message = gitdiffFile.PatchHeader.Message()
  76. t.GitInfo.Email = gitdiffFile.PatchHeader.Author.Email
  77. d.DetectScanTarget(t)
  78. }
  79. os.RemoveAll(tmpDir)
  80. return nil
  81. })
  82. }
  83. // skip binary files
  84. if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
  85. continue
  86. }
  87. d.addCommit(commitSHA)
  88. d.Sema.Go(func() error {
  89. for _, textFragment := range gitdiffFile.TextFragments {
  90. if textFragment == nil {
  91. return nil
  92. }
  93. fragment := Fragment{
  94. Raw: textFragment.Raw(gitdiff.OpAdd),
  95. CommitSHA: commitSHA,
  96. FilePath: gitdiffFile.NewName,
  97. }
  98. for _, finding := range d.Detect(fragment) {
  99. d.AddFinding(augmentGitFinding(remote, finding, textFragment, gitdiffFile))
  100. }
  101. }
  102. return nil
  103. })
  104. case err, open := <-errCh:
  105. if !open {
  106. errCh = nil
  107. break
  108. }
  109. return d.findings, err
  110. }
  111. }
  112. if err := d.Sema.Wait(); err != nil {
  113. return d.findings, err
  114. }
  115. logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
  116. logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
  117. return d.findings, nil
  118. }
  119. type RemoteInfo struct {
  120. Platform scm.Platform
  121. Url string
  122. }
  123. func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
  124. if platform == scm.NoPlatform {
  125. return &RemoteInfo{Platform: platform}
  126. }
  127. remoteUrl, err := getRemoteUrl(source)
  128. if err != nil {
  129. if strings.Contains(err.Error(), "No remote configured") {
  130. logging.Debug().Msg("skipping finding links: repository has no configured remote.")
  131. platform = scm.NoPlatform
  132. } else {
  133. logging.Error().Err(err).Msg("skipping finding links: unable to parse remote URL")
  134. }
  135. goto End
  136. }
  137. if platform == scm.UnknownPlatform {
  138. platform = platformFromHost(remoteUrl)
  139. if platform == scm.UnknownPlatform {
  140. logging.Info().
  141. Str("host", remoteUrl.Hostname()).
  142. Msg("Unknown SCM platform. Use --platform to include links in findings.")
  143. } else {
  144. logging.Debug().
  145. Str("host", remoteUrl.Hostname()).
  146. Str("platform", platform.String()).
  147. Msg("SCM platform parsed from host")
  148. }
  149. }
  150. End:
  151. var rUrl string
  152. if remoteUrl != nil {
  153. rUrl = remoteUrl.String()
  154. }
  155. return &RemoteInfo{
  156. Platform: platform,
  157. Url: rUrl,
  158. }
  159. }
  160. var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
  161. func getRemoteUrl(source string) (*url.URL, error) {
  162. // This will return the first remote — typically, "origin".
  163. cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
  164. if source != "." {
  165. cmd.Dir = source
  166. }
  167. stdout, err := cmd.Output()
  168. if err != nil {
  169. var exitError *exec.ExitError
  170. if errors.As(err, &exitError) {
  171. return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
  172. }
  173. return nil, err
  174. }
  175. remoteUrl := string(bytes.TrimSpace(stdout))
  176. if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
  177. remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
  178. }
  179. remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
  180. parsedUrl, err := url.Parse(remoteUrl)
  181. if err != nil {
  182. return nil, fmt.Errorf("unable to parse remote URL: %w", err)
  183. }
  184. // Remove any user info.
  185. parsedUrl.User = nil
  186. return parsedUrl, nil
  187. }
  188. func platformFromHost(u *url.URL) scm.Platform {
  189. switch strings.ToLower(u.Hostname()) {
  190. case "github.com":
  191. return scm.GitHubPlatform
  192. case "gitlab.com":
  193. return scm.GitLabPlatform
  194. case "dev.azure.com", "visualstudio.com":
  195. return scm.AzureDevOpsPlatform
  196. default:
  197. return scm.UnknownPlatform
  198. }
  199. }