detect.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package cmd
  2. import (
  3. "os"
  4. "path/filepath"
  5. "time"
  6. "github.com/rs/zerolog/log"
  7. "github.com/spf13/cobra"
  8. "github.com/spf13/viper"
  9. "github.com/zricethezav/gitleaks/v8/config"
  10. "github.com/zricethezav/gitleaks/v8/detect"
  11. "github.com/zricethezav/gitleaks/v8/report"
  12. )
  13. func init() {
  14. rootCmd.AddCommand(detectCmd)
  15. detectCmd.Flags().String("log-opts", "", "git log options")
  16. detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set")
  17. detectCmd.Flags().Bool("follow-symlinks", false, "Scan files that are symlinks to other files")
  18. }
  19. var detectCmd = &cobra.Command{
  20. Use: "detect",
  21. Short: "detect secrets in code",
  22. Run: runDetect,
  23. }
  24. func runDetect(cmd *cobra.Command, args []string) {
  25. initConfig()
  26. var (
  27. vc config.ViperConfig
  28. findings []report.Finding
  29. err error
  30. )
  31. // Load config
  32. if err = viper.Unmarshal(&vc); err != nil {
  33. log.Fatal().Err(err).Msg("Failed to load config")
  34. }
  35. cfg, err := vc.Translate()
  36. if err != nil {
  37. log.Fatal().Err(err).Msg("Failed to load config")
  38. }
  39. cfg.Path, _ = cmd.Flags().GetString("config")
  40. // start timer
  41. start := time.Now()
  42. // Setup detector
  43. detector := detect.NewDetector(cfg)
  44. detector.Config.Path, err = cmd.Flags().GetString("config")
  45. if err != nil {
  46. log.Fatal().Err(err).Msg("")
  47. }
  48. source, err := cmd.Flags().GetString("source")
  49. if err != nil {
  50. log.Fatal().Err(err).Msg("")
  51. }
  52. // if config path is not set, then use the {source}/.gitleaks.toml path.
  53. // note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
  54. if detector.Config.Path == "" {
  55. detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
  56. }
  57. // set verbose flag
  58. if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
  59. log.Fatal().Err(err).Msg("")
  60. }
  61. // set redact flag
  62. if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
  63. log.Fatal().Err(err).Msg("")
  64. }
  65. if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
  66. log.Fatal().Err(err).Msg("")
  67. }
  68. if fileExists(filepath.Join(source, ".gitleaksignore")) {
  69. if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
  70. log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  71. }
  72. }
  73. // ignore findings from the baseline (an existing report in json format generated earlier)
  74. baselinePath, _ := cmd.Flags().GetString("baseline-path")
  75. if baselinePath != "" {
  76. err = detector.AddBaseline(baselinePath)
  77. if err != nil {
  78. log.Error().Msgf("Could not load baseline. The path must point of a gitleaks report generated using the default format: %s", err)
  79. }
  80. }
  81. // set follow symlinks flag
  82. if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
  83. log.Fatal().Err(err).Msg("")
  84. }
  85. // set exit code
  86. exitCode, err := cmd.Flags().GetInt("exit-code")
  87. if err != nil {
  88. log.Fatal().Err(err).Msg("could not get exit code")
  89. }
  90. // determine what type of scan:
  91. // - git: scan the history of the repo
  92. // - no-git: scan files by treating the repo as a plain directory
  93. noGit, err := cmd.Flags().GetBool("no-git")
  94. if err != nil {
  95. log.Fatal().Err(err).Msg("could not call GetBool() for no-git")
  96. }
  97. // start the detector scan
  98. if noGit {
  99. findings, err = detector.DetectFiles(source)
  100. if err != nil {
  101. // don't exit on error, just log it
  102. log.Error().Err(err).Msg("")
  103. }
  104. } else {
  105. var logOpts string
  106. logOpts, err = cmd.Flags().GetString("log-opts")
  107. if err != nil {
  108. log.Fatal().Err(err).Msg("")
  109. }
  110. findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
  111. if err != nil {
  112. // don't exit on error, just log it
  113. log.Error().Err(err).Msg("")
  114. }
  115. }
  116. // log info about the scan
  117. if err == nil {
  118. log.Info().Msgf("scan completed in %s", FormatDuration(time.Since(start)))
  119. if len(findings) != 0 {
  120. log.Warn().Msgf("leaks found: %d", len(findings))
  121. } else {
  122. log.Info().Msg("no leaks found")
  123. }
  124. } else {
  125. log.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
  126. if len(findings) != 0 {
  127. log.Warn().Msgf("%d leaks found in partial scan", len(findings))
  128. } else {
  129. log.Warn().Msg("no leaks found in partial scan")
  130. }
  131. }
  132. // write report if desired
  133. reportPath, _ := cmd.Flags().GetString("report-path")
  134. ext, _ := cmd.Flags().GetString("report-format")
  135. if reportPath != "" {
  136. if err := report.Write(findings, cfg, ext, reportPath); err != nil {
  137. log.Fatal().Err(err).Msg("could not write")
  138. }
  139. }
  140. if err != nil {
  141. os.Exit(1)
  142. }
  143. if len(findings) != 0 {
  144. os.Exit(exitCode)
  145. }
  146. }
  147. func fileExists(fileName string) bool {
  148. // check for a .gitleaksignore file
  149. info, err := os.Stat(fileName)
  150. if err != nil && !os.IsNotExist(err) {
  151. return false
  152. }
  153. if info != nil && err == nil {
  154. if !info.IsDir() {
  155. return true
  156. }
  157. }
  158. return false
  159. }
  160. func FormatDuration(d time.Duration) string {
  161. scale := 100 * time.Second
  162. // look for the max scale that is smaller than d
  163. for scale > d {
  164. scale = scale / 10
  165. }
  166. return d.Round(scale / 100).String()
  167. }