git.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. var (
  80. remoteUrl string
  81. err error
  82. )
  83. if remoteUrl, err = getRemoteUrl(source); err != nil {
  84. if strings.Contains(err.Error(), "No remote configured") {
  85. logging.Debug().Msg("skipping finding links: repository has no configured remote.")
  86. platform = scm.NoPlatform
  87. goto End
  88. }
  89. return nil, fmt.Errorf("unable to get remote URL: %w", err)
  90. }
  91. if platform == scm.NoPlatform {
  92. parsedUrl, err := url.Parse(remoteUrl)
  93. if err != nil {
  94. return nil, fmt.Errorf("unable to parse remote URL: %w", err)
  95. }
  96. platform = platformFromHost(parsedUrl)
  97. if platform == scm.NoPlatform {
  98. logging.Info().
  99. Str("host", parsedUrl.Hostname()).
  100. Msg("Unknown SCM platform. Use --platform to include links in findings.")
  101. } else {
  102. logging.Debug().
  103. Str("host", parsedUrl.Hostname()).
  104. Str("platform", platform.String()).
  105. Msg("SCM platform parsed from host")
  106. }
  107. }
  108. End:
  109. return &RemoteInfo{
  110. Platform: platform,
  111. Url: remoteUrl,
  112. }, nil
  113. }
  114. var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
  115. func getRemoteUrl(source string) (string, error) {
  116. // This will return the first remote — typically, "origin".
  117. cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
  118. if source != "." {
  119. cmd.Dir = source
  120. }
  121. stdout, err := cmd.Output()
  122. if err != nil {
  123. var exitError *exec.ExitError
  124. if errors.As(err, &exitError) {
  125. return "", fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
  126. }
  127. return "", err
  128. }
  129. remoteUrl := string(bytes.TrimSpace(stdout))
  130. if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
  131. host := matches[1]
  132. repo := strings.TrimSuffix(matches[2], ".git")
  133. remoteUrl = fmt.Sprintf("https://%s/%s", host, repo)
  134. }
  135. return remoteUrl, nil
  136. }
  137. func platformFromHost(u *url.URL) scm.Platform {
  138. switch strings.ToLower(u.Hostname()) {
  139. case "github.com":
  140. return scm.GitHubPlatform
  141. case "gitlab.com":
  142. return scm.GitLabPlatform
  143. default:
  144. return scm.NoPlatform
  145. }
  146. }