detect.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package cmd
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "time"
  7. "github.com/rs/zerolog/log"
  8. "github.com/spf13/cobra"
  9. "github.com/spf13/viper"
  10. "github.com/zricethezav/gitleaks/v8/config"
  11. "github.com/zricethezav/gitleaks/v8/detect"
  12. "github.com/zricethezav/gitleaks/v8/report"
  13. )
  14. func init() {
  15. rootCmd.AddCommand(detectCmd)
  16. detectCmd.Flags().String("log-opts", "", "git log options")
  17. 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")
  18. detectCmd.Flags().Bool("pipe", false, "scan input from stdin, ex: `cat some_file | gitleaks detect --pipe`")
  19. detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files")
  20. detectCmd.Flags().StringSlice("enable-rule", []string{}, "only enable specific rules by id, ex: `gitleaks detect --enable-rule=atlassian-api-token --enable-rule=slack-access-token`")
  21. detectCmd.Flags().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
  22. }
  23. var detectCmd = &cobra.Command{
  24. Use: "detect",
  25. Short: "detect secrets in code",
  26. Run: runDetect,
  27. }
  28. func runDetect(cmd *cobra.Command, args []string) {
  29. initConfig()
  30. var (
  31. vc config.ViperConfig
  32. findings []report.Finding
  33. err error
  34. )
  35. // Load config
  36. if err = viper.Unmarshal(&vc); err != nil {
  37. log.Fatal().Err(err).Msg("Failed to load config")
  38. }
  39. cfg, err := vc.Translate()
  40. if err != nil {
  41. log.Fatal().Err(err).Msg("Failed to load config")
  42. }
  43. cfg.Path, _ = cmd.Flags().GetString("config")
  44. // start timer
  45. start := time.Now()
  46. // Setup detector
  47. detector := detect.NewDetector(cfg)
  48. detector.Config.Path, err = cmd.Flags().GetString("config")
  49. if err != nil {
  50. log.Fatal().Err(err).Msg("")
  51. }
  52. source, err := cmd.Flags().GetString("source")
  53. if err != nil {
  54. log.Fatal().Err(err).Msg("")
  55. }
  56. // if config path is not set, then use the {source}/.gitleaks.toml path.
  57. // note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
  58. if detector.Config.Path == "" {
  59. detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
  60. }
  61. // set verbose flag
  62. if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
  63. log.Fatal().Err(err).Msg("")
  64. }
  65. // set redact flag
  66. if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
  67. log.Fatal().Err(err).Msg("")
  68. }
  69. if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
  70. log.Fatal().Err(err).Msg("")
  71. }
  72. // set color flag
  73. if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
  74. log.Fatal().Err(err).Msg("")
  75. }
  76. gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
  77. if err != nil {
  78. log.Fatal().Err(err).Msg("could not get .gitleaksignore path")
  79. }
  80. if fileExists(gitleaksIgnorePath) {
  81. if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
  82. log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  83. }
  84. }
  85. if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
  86. if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
  87. log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  88. }
  89. }
  90. if fileExists(filepath.Join(source, ".gitleaksignore")) {
  91. if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
  92. log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  93. }
  94. }
  95. // ignore findings from the baseline (an existing report in json format generated earlier)
  96. baselinePath, _ := cmd.Flags().GetString("baseline-path")
  97. if baselinePath != "" {
  98. err = detector.AddBaseline(baselinePath, source)
  99. if err != nil {
  100. log.Error().Msgf("Could not load baseline. The path must point of a gitleaks report generated using the default format: %s", err)
  101. }
  102. }
  103. // If set, only apply rules that are defined in the flag
  104. rules, _ := cmd.Flags().GetStringSlice("enable-rule")
  105. if len(rules) > 0 {
  106. log.Info().Msg("Overriding enabled rules: " + strings.Join(rules, ", "))
  107. ruleOverride := make(map[string]config.Rule)
  108. for _, ruleName := range rules {
  109. if rule, ok := cfg.Rules[ruleName]; ok {
  110. ruleOverride[ruleName] = rule
  111. } else {
  112. log.Fatal().Msgf("Requested rule %s not found in rules", ruleName)
  113. }
  114. }
  115. detector.Config.Rules = ruleOverride
  116. }
  117. // set follow symlinks flag
  118. if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
  119. log.Fatal().Err(err).Msg("")
  120. }
  121. // set exit code
  122. exitCode, err := cmd.Flags().GetInt("exit-code")
  123. if err != nil {
  124. log.Fatal().Err(err).Msg("could not get exit code")
  125. }
  126. // determine what type of scan:
  127. // - git: scan the history of the repo
  128. // - no-git: scan files by treating the repo as a plain directory
  129. noGit, err := cmd.Flags().GetBool("no-git")
  130. if err != nil {
  131. log.Fatal().Err(err).Msg("could not call GetBool() for no-git")
  132. }
  133. fromPipe, err := cmd.Flags().GetBool("pipe")
  134. if err != nil {
  135. log.Fatal().Err(err)
  136. }
  137. // start the detector scan
  138. if noGit {
  139. findings, err = detector.DetectFiles(source)
  140. if err != nil {
  141. // don't exit on error, just log it
  142. log.Error().Err(err).Msg("")
  143. }
  144. } else if fromPipe {
  145. findings, err = detector.DetectReader(os.Stdin, 10)
  146. if err != nil {
  147. // log fatal to exit, no need to continue since a report
  148. // will not be generated when scanning from a pipe...for now
  149. log.Fatal().Err(err).Msg("")
  150. }
  151. } else {
  152. var logOpts string
  153. logOpts, err = cmd.Flags().GetString("log-opts")
  154. if err != nil {
  155. log.Fatal().Err(err).Msg("")
  156. }
  157. findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
  158. if err != nil {
  159. // don't exit on error, just log it
  160. log.Error().Err(err).Msg("")
  161. }
  162. }
  163. // log info about the scan
  164. if err == nil {
  165. log.Info().Msgf("scan completed in %s", FormatDuration(time.Since(start)))
  166. if len(findings) != 0 {
  167. log.Warn().Msgf("leaks found: %d", len(findings))
  168. } else {
  169. log.Info().Msg("no leaks found")
  170. }
  171. } else {
  172. log.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
  173. if len(findings) != 0 {
  174. log.Warn().Msgf("%d leaks found in partial scan", len(findings))
  175. } else {
  176. log.Warn().Msg("no leaks found in partial scan")
  177. }
  178. }
  179. // write report if desired
  180. reportPath, _ := cmd.Flags().GetString("report-path")
  181. ext, _ := cmd.Flags().GetString("report-format")
  182. if reportPath != "" {
  183. if err := report.Write(findings, cfg, ext, reportPath); err != nil {
  184. log.Fatal().Err(err).Msg("could not write")
  185. }
  186. }
  187. if err != nil {
  188. os.Exit(1)
  189. }
  190. if len(findings) != 0 {
  191. os.Exit(exitCode)
  192. }
  193. }
  194. func fileExists(fileName string) bool {
  195. // check for a .gitleaksignore file
  196. info, err := os.Stat(fileName)
  197. if err != nil && !os.IsNotExist(err) {
  198. return false
  199. }
  200. if info != nil && err == nil {
  201. if !info.IsDir() {
  202. return true
  203. }
  204. }
  205. return false
  206. }
  207. func FormatDuration(d time.Duration) string {
  208. scale := 100 * time.Second
  209. // look for the max scale that is smaller than d
  210. for scale > d {
  211. scale = scale / 10
  212. }
  213. return d.Round(scale / 100).String()
  214. }