git.go 4.4 KB

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