detect.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. // set ignore gitleaks:allow flag
  85. if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
  86. log.Fatal().Err(err).Msg("")
  87. }
  88. gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
  89. if err != nil {
  90. log.Fatal().Err(err).Msg("could not get .gitleaksignore path")
  91. }
  92. if fileExists(gitleaksIgnorePath) {
  93. if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
  94. log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  95. }
  96. }
  97. if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
  98. if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
  99. log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  100. }
  101. }
  102. if fileExists(filepath.Join(source, ".gitleaksignore")) {
  103. if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
  104. log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  105. }
  106. }
  107. // ignore findings from the baseline (an existing report in json format generated earlier)
  108. baselinePath, _ := cmd.Flags().GetString("baseline-path")
  109. if baselinePath != "" {
  110. err = detector.AddBaseline(baselinePath, source)
  111. if err != nil {
  112. log.Error().Msgf("Could not load baseline. The path must point of a gitleaks report generated using the default format: %s", err)
  113. }
  114. }
  115. // If set, only apply rules that are defined in the flag
  116. rules, _ := cmd.Flags().GetStringSlice("enable-rule")
  117. if len(rules) > 0 {
  118. log.Info().Msg("Overriding enabled rules: " + strings.Join(rules, ", "))
  119. ruleOverride := make(map[string]config.Rule)
  120. for _, ruleName := range rules {
  121. if rule, ok := cfg.Rules[ruleName]; ok {
  122. ruleOverride[ruleName] = rule
  123. } else {
  124. log.Fatal().Msgf("Requested rule %s not found in rules", ruleName)
  125. }
  126. }
  127. detector.Config.Rules = ruleOverride
  128. }
  129. // set follow symlinks flag
  130. if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
  131. log.Fatal().Err(err).Msg("")
  132. }
  133. // set exit code
  134. exitCode, err := cmd.Flags().GetInt("exit-code")
  135. if err != nil {
  136. log.Fatal().Err(err).Msg("could not get exit code")
  137. }
  138. // determine what type of scan:
  139. // - git: scan the history of the repo
  140. // - no-git: scan files by treating the repo as a plain directory
  141. noGit, err := cmd.Flags().GetBool("no-git")
  142. if err != nil {
  143. log.Fatal().Err(err).Msg("could not call GetBool() for no-git")
  144. }
  145. fromPipe, err := cmd.Flags().GetBool("pipe")
  146. if err != nil {
  147. log.Fatal().Err(err)
  148. }
  149. // start the detector scan
  150. if noGit {
  151. findings, err = detector.DetectFiles(source)
  152. if err != nil {
  153. // don't exit on error, just log it
  154. log.Error().Err(err).Msg("")
  155. }
  156. } else if fromPipe {
  157. findings, err = detector.DetectReader(os.Stdin, 10)
  158. if err != nil {
  159. // log fatal to exit, no need to continue since a report
  160. // will not be generated when scanning from a pipe...for now
  161. log.Fatal().Err(err).Msg("")
  162. }
  163. } else {
  164. var logOpts string
  165. logOpts, err = cmd.Flags().GetString("log-opts")
  166. if err != nil {
  167. log.Fatal().Err(err).Msg("")
  168. }
  169. findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
  170. if err != nil {
  171. // don't exit on error, just log it
  172. log.Error().Err(err).Msg("")
  173. }
  174. }
  175. // log info about the scan
  176. if err == nil {
  177. log.Info().Msgf("scan completed in %s", FormatDuration(time.Since(start)))
  178. if len(findings) != 0 {
  179. log.Warn().Msgf("leaks found: %d", len(findings))
  180. } else {
  181. log.Info().Msg("no leaks found")
  182. }
  183. } else {
  184. log.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
  185. if len(findings) != 0 {
  186. log.Warn().Msgf("%d leaks found in partial scan", len(findings))
  187. } else {
  188. log.Warn().Msg("no leaks found in partial scan")
  189. }
  190. }
  191. // write report if desired
  192. reportPath, _ := cmd.Flags().GetString("report-path")
  193. ext, _ := cmd.Flags().GetString("report-format")
  194. if reportPath != "" {
  195. if err := report.Write(findings, cfg, ext, reportPath); err != nil {
  196. log.Fatal().Err(err).Msg("could not write")
  197. }
  198. }
  199. if err != nil {
  200. os.Exit(1)
  201. }
  202. if len(findings) != 0 {
  203. os.Exit(exitCode)
  204. }
  205. }
  206. func fileExists(fileName string) bool {
  207. // check for a .gitleaksignore file
  208. info, err := os.Stat(fileName)
  209. if err != nil && !os.IsNotExist(err) {
  210. return false
  211. }
  212. if info != nil && err == nil {
  213. if !info.IsDir() {
  214. return true
  215. }
  216. }
  217. return false
  218. }
  219. func FormatDuration(d time.Duration) string {
  220. scale := 100 * time.Second
  221. // look for the max scale that is smaller than d
  222. for scale > d {
  223. scale = scale / 10
  224. }
  225. return d.Round(scale / 100).String()
  226. }