detect.go 7.1 KB

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