git.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package detect
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net/url"
  7. "os/exec"
  8. "regexp"
  9. "strings"
  10. "github.com/gitleaks/go-gitdiff/gitdiff"
  11. "github.com/zricethezav/gitleaks/v8/cmd/scm"
  12. "github.com/zricethezav/gitleaks/v8/logging"
  13. "github.com/zricethezav/gitleaks/v8/report"
  14. "github.com/zricethezav/gitleaks/v8/sources"
  15. )
  16. func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.Finding, error) {
  17. defer cmd.Wait()
  18. var (
  19. diffFilesCh = cmd.DiffFilesCh()
  20. errCh = cmd.ErrCh()
  21. )
  22. // loop to range over both DiffFiles (stdout) and ErrCh (stderr)
  23. for diffFilesCh != nil || errCh != nil {
  24. select {
  25. case gitdiffFile, open := <-diffFilesCh:
  26. if !open {
  27. diffFilesCh = nil
  28. break
  29. }
  30. // skip binary files
  31. if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
  32. continue
  33. }
  34. // Check if commit is allowed
  35. commitSHA := ""
  36. if gitdiffFile.PatchHeader != nil {
  37. commitSHA = gitdiffFile.PatchHeader.SHA
  38. if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
  39. continue
  40. }
  41. }
  42. d.addCommit(commitSHA)
  43. d.Sema.Go(func() error {
  44. for _, textFragment := range gitdiffFile.TextFragments {
  45. if textFragment == nil {
  46. return nil
  47. }
  48. fragment := Fragment{
  49. Raw: textFragment.Raw(gitdiff.OpAdd),
  50. CommitSHA: commitSHA,
  51. FilePath: gitdiffFile.NewName,
  52. }
  53. for _, finding := range d.Detect(fragment) {
  54. d.addFinding(augmentGitFinding(remote.Platform, remote.Url, finding, textFragment, gitdiffFile))
  55. }
  56. }
  57. return nil
  58. })
  59. case err, open := <-errCh:
  60. if !open {
  61. errCh = nil
  62. break
  63. }
  64. return d.findings, err
  65. }
  66. }
  67. if err := d.Sema.Wait(); err != nil {
  68. return d.findings, err
  69. }
  70. logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
  71. logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
  72. return d.findings, nil
  73. }
  74. type RemoteInfo struct {
  75. Platform scm.Platform
  76. Url string
  77. }
  78. func NewRemoteInfo(platform scm.Platform, source string) (*RemoteInfo, error) {
  79. remoteUrl, err := getRemoteUrl(source)
  80. if err != nil {
  81. if strings.Contains(err.Error(), "No remote configured") {
  82. logging.Debug().Msg("skipping finding links: repository has no configured remote.")
  83. platform = scm.NoPlatform
  84. goto End
  85. }
  86. return nil, fmt.Errorf("unable to get remote URL: %w", err)
  87. }
  88. if platform == scm.NoPlatform {
  89. platform = platformFromHost(remoteUrl)
  90. if platform == scm.NoPlatform {
  91. logging.Info().
  92. Str("host", remoteUrl.Hostname()).
  93. Msg("Unknown SCM platform. Use --platform to include links in findings.")
  94. } else {
  95. logging.Debug().
  96. Str("host", remoteUrl.Hostname()).
  97. Str("platform", platform.String()).
  98. Msg("SCM platform parsed from host")
  99. }
  100. }
  101. End:
  102. var rUrl string
  103. if remoteUrl != nil {
  104. rUrl = remoteUrl.String()
  105. }
  106. return &RemoteInfo{
  107. Platform: platform,
  108. Url: rUrl,
  109. }, nil
  110. }
  111. var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
  112. func getRemoteUrl(source string) (*url.URL, error) {
  113. // This will return the first remote — typically, "origin".
  114. cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
  115. if source != "." {
  116. cmd.Dir = source
  117. }
  118. stdout, err := cmd.Output()
  119. if err != nil {
  120. var exitError *exec.ExitError
  121. if errors.As(err, &exitError) {
  122. return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
  123. }
  124. return nil, err
  125. }
  126. remoteUrl := string(bytes.TrimSpace(stdout))
  127. if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
  128. host := matches[1]
  129. repo := strings.TrimSuffix(matches[2], ".git")
  130. remoteUrl = fmt.Sprintf("https://%s/%s", host, repo)
  131. }
  132. parsedUrl, err := url.Parse(remoteUrl)
  133. if err != nil {
  134. return nil, fmt.Errorf("unable to parse remote URL: %w", err)
  135. }
  136. // Remove any user info.
  137. parsedUrl.User = nil
  138. return parsedUrl, nil
  139. }
  140. func platformFromHost(u *url.URL) scm.Platform {
  141. switch strings.ToLower(u.Hostname()) {
  142. case "github.com":
  143. return scm.GitHubPlatform
  144. case "gitlab.com":
  145. return scm.GitLabPlatform
  146. default:
  147. return scm.NoPlatform
  148. }
  149. }