git.go 4.2 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 ok, c := d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
  39. logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
  40. continue
  41. }
  42. }
  43. d.addCommit(commitSHA)
  44. d.Sema.Go(func() error {
  45. for _, textFragment := range gitdiffFile.TextFragments {
  46. if textFragment == nil {
  47. return nil
  48. }
  49. fragment := Fragment{
  50. Raw: textFragment.Raw(gitdiff.OpAdd),
  51. CommitSHA: commitSHA,
  52. FilePath: gitdiffFile.NewName,
  53. }
  54. for _, finding := range d.Detect(fragment) {
  55. d.addFinding(augmentGitFinding(remote.Platform, remote.Url, finding, textFragment, gitdiffFile))
  56. }
  57. }
  58. return nil
  59. })
  60. case err, open := <-errCh:
  61. if !open {
  62. errCh = nil
  63. break
  64. }
  65. return d.findings, err
  66. }
  67. }
  68. if err := d.Sema.Wait(); err != nil {
  69. return d.findings, err
  70. }
  71. logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
  72. logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
  73. return d.findings, nil
  74. }
  75. type RemoteInfo struct {
  76. Platform scm.Platform
  77. Url string
  78. }
  79. func NewRemoteInfo(platform scm.Platform, source string) (*RemoteInfo, error) {
  80. remoteUrl, err := getRemoteUrl(source)
  81. if err != nil {
  82. if strings.Contains(err.Error(), "No remote configured") {
  83. logging.Debug().Msg("skipping finding links: repository has no configured remote.")
  84. platform = scm.NoPlatform
  85. goto End
  86. }
  87. return nil, fmt.Errorf("unable to get remote URL: %w", err)
  88. }
  89. if platform == scm.NoPlatform {
  90. platform = platformFromHost(remoteUrl)
  91. if platform == scm.NoPlatform {
  92. logging.Info().
  93. Str("host", remoteUrl.Hostname()).
  94. Msg("Unknown SCM platform. Use --platform to include links in findings.")
  95. } else {
  96. logging.Debug().
  97. Str("host", remoteUrl.Hostname()).
  98. Str("platform", platform.String()).
  99. Msg("SCM platform parsed from host")
  100. }
  101. }
  102. End:
  103. var rUrl string
  104. if remoteUrl != nil {
  105. rUrl = remoteUrl.String()
  106. }
  107. return &RemoteInfo{
  108. Platform: platform,
  109. Url: rUrl,
  110. }, nil
  111. }
  112. var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
  113. func getRemoteUrl(source string) (*url.URL, error) {
  114. // This will return the first remote — typically, "origin".
  115. cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
  116. if source != "." {
  117. cmd.Dir = source
  118. }
  119. stdout, err := cmd.Output()
  120. if err != nil {
  121. var exitError *exec.ExitError
  122. if errors.As(err, &exitError) {
  123. return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
  124. }
  125. return nil, err
  126. }
  127. remoteUrl := string(bytes.TrimSpace(stdout))
  128. if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
  129. remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
  130. }
  131. remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
  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. }