detect.go 4.7 KB

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