detect.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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)
  46. }
  47. source, err := cmd.Flags().GetString("source")
  48. if err != nil {
  49. log.Fatal().Err(err)
  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)
  59. }
  60. // set redact flag
  61. if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
  62. log.Fatal().Err(err)
  63. }
  64. if fileExists(filepath.Join(source, ".gitleaksignore")) {
  65. detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore"))
  66. }
  67. // ignore findings from the baseline (an existing report in json format generated earlier)
  68. baselinePath, _ := cmd.Flags().GetString("baseline-path")
  69. if baselinePath != "" {
  70. err = detector.AddBaseline(baselinePath)
  71. if err != nil {
  72. log.Error().Msgf("Could not load baseline. The path must point of a gitleaks report generated using the default format: %s", err)
  73. }
  74. }
  75. // set exit code
  76. exitCode, err := cmd.Flags().GetInt("exit-code")
  77. if err != nil {
  78. log.Fatal().Err(err)
  79. }
  80. // determine what type of scan:
  81. // - git: scan the history of the repo
  82. // - no-git: scan files by treating the repo as a plain directory
  83. noGit, err := cmd.Flags().GetBool("no-git")
  84. if err != nil {
  85. log.Fatal().Err(err)
  86. }
  87. // start the detector scan
  88. if noGit {
  89. findings, err = detector.DetectFiles(source)
  90. if err != nil {
  91. // don't exit on error, just log it
  92. log.Error().Msg(err.Error())
  93. }
  94. } else {
  95. var logOpts string
  96. logOpts, err = cmd.Flags().GetString("log-opts")
  97. if err != nil {
  98. log.Fatal().Err(err)
  99. }
  100. findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
  101. if err != nil {
  102. // don't exit on error, just log it
  103. log.Error().Msg(err.Error())
  104. }
  105. }
  106. // log info about the scan
  107. if err == nil {
  108. log.Info().Msgf("scan completed in %s", FormatDuration(time.Since(start)))
  109. if len(findings) != 0 {
  110. log.Warn().Msgf("leaks found: %d", len(findings))
  111. } else {
  112. log.Info().Msg("no leaks found")
  113. }
  114. } else {
  115. log.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
  116. if len(findings) != 0 {
  117. log.Warn().Msgf("%d leaks found in partial scan", len(findings))
  118. } else {
  119. log.Warn().Msg("no leaks found in partial scan")
  120. }
  121. }
  122. // write report if desired
  123. reportPath, _ := cmd.Flags().GetString("report-path")
  124. ext, _ := cmd.Flags().GetString("report-format")
  125. if reportPath != "" {
  126. if err := report.Write(findings, cfg, ext, reportPath); err != nil {
  127. log.Fatal().Err(err)
  128. }
  129. }
  130. if err != nil {
  131. os.Exit(1)
  132. }
  133. if len(findings) != 0 {
  134. os.Exit(exitCode)
  135. }
  136. }
  137. func fileExists(fileName string) bool {
  138. // check for a .gitleaksignore file
  139. info, err := os.Stat(fileName)
  140. if err != nil && !os.IsNotExist(err) {
  141. return false
  142. }
  143. if info != nil && err == nil {
  144. if !info.IsDir() {
  145. return true
  146. }
  147. }
  148. return false
  149. }
  150. func FormatDuration(d time.Duration) string {
  151. scale := 100 * time.Second
  152. // look for the max scale that is smaller than d
  153. for scale > d {
  154. scale = scale / 10
  155. }
  156. return d.Round(scale / 100).String()
  157. }