root.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. package cmd
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/rs/zerolog"
  11. "github.com/rs/zerolog/log"
  12. "github.com/spf13/cobra"
  13. "github.com/spf13/viper"
  14. "github.com/zricethezav/gitleaks/v8/config"
  15. "github.com/zricethezav/gitleaks/v8/detect"
  16. "github.com/zricethezav/gitleaks/v8/logging"
  17. "github.com/zricethezav/gitleaks/v8/regexp"
  18. "github.com/zricethezav/gitleaks/v8/report"
  19. )
  20. const banner = `
  21. │╲
  22. │ ○
  23. ○ ░
  24. ░ gitleaks
  25. `
  26. const configDescription = `config file path
  27. order of precedence:
  28. 1. --config/-c
  29. 2. env var GITLEAKS_CONFIG
  30. 3. env var GITLEAKS_CONFIG_TOML with the file content
  31. 4. (target path)/.gitleaks.toml
  32. If none of the four options are used, then gitleaks will use the default config`
  33. var rootCmd = &cobra.Command{
  34. Use: "gitleaks",
  35. Short: "Gitleaks scans code, past or present, for secrets",
  36. Version: Version,
  37. }
  38. const (
  39. BYTE = 1.0
  40. KILOBYTE = BYTE * 1000
  41. MEGABYTE = KILOBYTE * 1000
  42. GIGABYTE = MEGABYTE * 1000
  43. )
  44. func init() {
  45. cobra.OnInitialize(initLog)
  46. rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
  47. rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered")
  48. rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file")
  49. rootCmd.PersistentFlags().StringP("report-format", "f", "", "output format (json, csv, junit, sarif, template)")
  50. rootCmd.PersistentFlags().StringP("report-template", "", "", "template file used to generate the report (implies --report-format=template)")
  51. rootCmd.PersistentFlags().StringP("baseline-path", "b", "", "path to baseline with issues that can be ignored")
  52. rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (trace, debug, info, warn, error, fatal)")
  53. rootCmd.PersistentFlags().BoolP("verbose", "v", false, "show verbose output from scan")
  54. rootCmd.PersistentFlags().BoolP("no-color", "", false, "turn off color for verbose output")
  55. rootCmd.PersistentFlags().Int("max-target-megabytes", 0, "files larger than this will be skipped")
  56. rootCmd.PersistentFlags().BoolP("ignore-gitleaks-allow", "", false, "ignore gitleaks:allow comments")
  57. rootCmd.PersistentFlags().Uint("redact", 0, "redact secrets from logs and stdout. To redact only parts of the secret just apply a percent value from 0..100. For example --redact=20 (default 100%)")
  58. rootCmd.Flag("redact").NoOptDefVal = "100"
  59. rootCmd.PersistentFlags().Bool("no-banner", false, "suppress banner")
  60. rootCmd.PersistentFlags().StringSlice("enable-rule", []string{}, "only enable specific rules by id")
  61. rootCmd.PersistentFlags().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
  62. rootCmd.PersistentFlags().Int("max-decode-depth", 0, "allow recursive decoding up to this depth (default \"0\", no decoding is done)")
  63. err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
  64. if err != nil {
  65. logging.Fatal().Msgf("err binding config %s", err.Error())
  66. }
  67. }
  68. var logLevel = zerolog.InfoLevel
  69. func initLog() {
  70. ll, err := rootCmd.Flags().GetString("log-level")
  71. if err != nil {
  72. logging.Fatal().Msg(err.Error())
  73. }
  74. switch strings.ToLower(ll) {
  75. case "trace":
  76. logLevel = zerolog.TraceLevel
  77. case "debug":
  78. logLevel = zerolog.DebugLevel
  79. case "info":
  80. logLevel = zerolog.InfoLevel
  81. case "warn":
  82. logLevel = zerolog.WarnLevel
  83. case "err", "error":
  84. logLevel = zerolog.ErrorLevel
  85. case "fatal":
  86. logLevel = zerolog.FatalLevel
  87. default:
  88. logging.Warn().Msgf("unknown log level: %s", ll)
  89. }
  90. logging.Logger = logging.Logger.Level(logLevel)
  91. }
  92. func initConfig(source string) {
  93. hideBanner, err := rootCmd.Flags().GetBool("no-banner")
  94. viper.SetConfigType("toml")
  95. if err != nil {
  96. logging.Fatal().Msg(err.Error())
  97. }
  98. if !hideBanner {
  99. _, _ = fmt.Fprint(os.Stderr, banner)
  100. }
  101. logging.Debug().Msgf("using %s regex engine", regexp.Version)
  102. cfgPath, err := rootCmd.Flags().GetString("config")
  103. if err != nil {
  104. logging.Fatal().Msg(err.Error())
  105. }
  106. if cfgPath != "" {
  107. viper.SetConfigFile(cfgPath)
  108. logging.Debug().Msgf("using gitleaks config %s from `--config`", cfgPath)
  109. } else if os.Getenv("GITLEAKS_CONFIG") != "" {
  110. envPath := os.Getenv("GITLEAKS_CONFIG")
  111. viper.SetConfigFile(envPath)
  112. logging.Debug().Msgf("using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
  113. } else if os.Getenv("GITLEAKS_CONFIG_TOML") != "" {
  114. configContent := []byte(os.Getenv("GITLEAKS_CONFIG_TOML"))
  115. if err := viper.ReadConfig(bytes.NewBuffer(configContent)); err != nil {
  116. logging.Fatal().Err(err).Str("content", os.Getenv("GITLEAKS_CONFIG_TOML")).Msg("unable to load gitleaks config from GITLEAKS_CONFIG_TOML env var")
  117. }
  118. logging.Debug().Str("content", os.Getenv("GITLEAKS_CONFIG_TOML")).Msg("using gitleaks config from GITLEAKS_CONFIG_TOML env var content")
  119. return
  120. } else {
  121. fileInfo, err := os.Stat(source)
  122. if err != nil {
  123. logging.Fatal().Msg(err.Error())
  124. }
  125. if !fileInfo.IsDir() {
  126. logging.Debug().Msgf("unable to load gitleaks config from %s since --source=%s is a file, using default config",
  127. filepath.Join(source, ".gitleaks.toml"), source)
  128. if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
  129. logging.Fatal().Msgf("err reading toml %s", err.Error())
  130. }
  131. return
  132. }
  133. if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
  134. logging.Debug().Msgf("no gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
  135. if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
  136. logging.Fatal().Msgf("err reading default config toml %s", err.Error())
  137. }
  138. return
  139. } else {
  140. logging.Debug().Msgf("using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml"))
  141. }
  142. viper.AddConfigPath(source)
  143. viper.SetConfigName(".gitleaks")
  144. }
  145. if err := viper.ReadInConfig(); err != nil {
  146. logging.Fatal().Msgf("unable to load gitleaks config, err: %s", err)
  147. }
  148. }
  149. func Execute() {
  150. if err := rootCmd.Execute(); err != nil {
  151. if strings.Contains(err.Error(), "unknown flag") {
  152. // exit code 126: Command invoked cannot execute
  153. os.Exit(126)
  154. }
  155. logging.Fatal().Msg(err.Error())
  156. }
  157. }
  158. func Config(cmd *cobra.Command) config.Config {
  159. var vc config.ViperConfig
  160. if err := viper.Unmarshal(&vc); err != nil {
  161. logging.Fatal().Err(err).Msg("Failed to load config")
  162. }
  163. cfg, err := vc.Translate()
  164. if err != nil {
  165. logging.Fatal().Err(err).Msg("Failed to load config")
  166. }
  167. cfg.Path, _ = cmd.Flags().GetString("config")
  168. return cfg
  169. }
  170. func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Detector {
  171. var err error
  172. // Setup common detector
  173. detector := detect.NewDetector(cfg)
  174. if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
  175. logging.Fatal().Err(err).Msg("")
  176. }
  177. // set color flag at first
  178. if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
  179. logging.Fatal().Err(err).Msg("")
  180. }
  181. // also init logger again without color
  182. if detector.NoColor {
  183. logging.Logger = log.Output(zerolog.ConsoleWriter{
  184. Out: os.Stderr,
  185. NoColor: detector.NoColor,
  186. }).Level(logLevel)
  187. }
  188. detector.Config.Path, err = cmd.Flags().GetString("config")
  189. if err != nil {
  190. logging.Fatal().Err(err).Msg("")
  191. }
  192. // if config path is not set, then use the {source}/.gitleaks.toml path.
  193. // note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
  194. if detector.Config.Path == "" {
  195. detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
  196. }
  197. // set verbose flag
  198. if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
  199. logging.Fatal().Err(err).Msg("")
  200. }
  201. // set redact flag
  202. if detector.Redact, err = cmd.Flags().GetUint("redact"); err != nil {
  203. logging.Fatal().Err(err).Msg("")
  204. }
  205. if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
  206. logging.Fatal().Err(err).Msg("")
  207. }
  208. // set ignore gitleaks:allow flag
  209. if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
  210. logging.Fatal().Err(err).Msg("")
  211. }
  212. gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
  213. if err != nil {
  214. logging.Fatal().Err(err).Msg("could not get .gitleaksignore path")
  215. }
  216. if fileExists(gitleaksIgnorePath) {
  217. if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
  218. logging.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  219. }
  220. }
  221. if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
  222. if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
  223. logging.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  224. }
  225. }
  226. if fileExists(filepath.Join(source, ".gitleaksignore")) {
  227. if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
  228. logging.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
  229. }
  230. }
  231. // ignore findings from the baseline (an existing report in json format generated earlier)
  232. baselinePath, _ := cmd.Flags().GetString("baseline-path")
  233. if baselinePath != "" {
  234. err = detector.AddBaseline(baselinePath, source)
  235. if err != nil {
  236. logging.Error().Msgf("Could not load baseline. The path must point of a gitleaks report generated using the default format: %s", err)
  237. }
  238. }
  239. // If set, only apply rules that are defined in the flag
  240. rules, _ := cmd.Flags().GetStringSlice("enable-rule")
  241. if len(rules) > 0 {
  242. logging.Info().Msg("Overriding enabled rules: " + strings.Join(rules, ", "))
  243. ruleOverride := make(map[string]config.Rule)
  244. for _, ruleName := range rules {
  245. if r, ok := cfg.Rules[ruleName]; ok {
  246. ruleOverride[ruleName] = r
  247. } else {
  248. logging.Fatal().Msgf("Requested rule %s not found in rules", ruleName)
  249. }
  250. }
  251. detector.Config.Rules = ruleOverride
  252. }
  253. // Validate report settings.
  254. reportPath := mustGetStringFlag(cmd, "report-path")
  255. if reportPath != "" {
  256. if reportPath != report.StdoutReportPath {
  257. // Ensure the path is writable.
  258. if f, err := os.Create(reportPath); err != nil {
  259. logging.Fatal().Err(err).Msgf("Report path is not writable: %s", reportPath)
  260. } else {
  261. _ = f.Close()
  262. _ = os.Remove(reportPath)
  263. }
  264. }
  265. // Build report writer.
  266. var (
  267. reporter report.Reporter
  268. reportFormat = mustGetStringFlag(cmd, "report-format")
  269. reportTemplate = mustGetStringFlag(cmd, "report-template")
  270. )
  271. if reportFormat == "" {
  272. ext := strings.ToLower(filepath.Ext(reportPath))
  273. switch ext {
  274. case ".csv":
  275. reportFormat = "csv"
  276. case ".json":
  277. reportFormat = "json"
  278. case ".sarif":
  279. reportFormat = "sarif"
  280. default:
  281. logging.Fatal().Msgf("Unknown report format: %s", reportFormat)
  282. }
  283. logging.Debug().Msgf("No report format specified, inferred %q from %q", reportFormat, ext)
  284. }
  285. switch strings.TrimSpace(strings.ToLower(reportFormat)) {
  286. case "csv":
  287. reporter = &report.CsvReporter{}
  288. case "json":
  289. reporter = &report.JsonReporter{}
  290. case "junit":
  291. reporter = &report.JunitReporter{}
  292. case "sarif":
  293. reporter = &report.SarifReporter{
  294. OrderedRules: cfg.GetOrderedRules(),
  295. }
  296. case "template":
  297. if reporter, err = report.NewTemplateReporter(reportTemplate); err != nil {
  298. logging.Fatal().Err(err).Msg("Invalid report template")
  299. }
  300. default:
  301. logging.Fatal().Msgf("unknown report format %s", reportFormat)
  302. }
  303. // Sanity check.
  304. if reportTemplate != "" && reportFormat != "template" {
  305. logging.Fatal().Msgf("Report format must be 'template' if --report-template is specified")
  306. }
  307. detector.ReportPath = reportPath
  308. detector.Reporter = reporter
  309. }
  310. return detector
  311. }
  312. func bytesConvert(bytes uint64) string {
  313. unit := ""
  314. value := float32(bytes)
  315. switch {
  316. case bytes >= GIGABYTE:
  317. unit = "GB"
  318. value = value / GIGABYTE
  319. case bytes >= MEGABYTE:
  320. unit = "MB"
  321. value = value / MEGABYTE
  322. case bytes >= KILOBYTE:
  323. unit = "KB"
  324. value = value / KILOBYTE
  325. case bytes >= BYTE:
  326. unit = "bytes"
  327. case bytes == 0:
  328. return "0"
  329. }
  330. stringValue := strings.TrimSuffix(
  331. fmt.Sprintf("%.2f", value), ".00",
  332. )
  333. return fmt.Sprintf("%s %s", stringValue, unit)
  334. }
  335. func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, exitCode int, start time.Time, err error) {
  336. totalBytes := detector.TotalBytes.Load()
  337. bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
  338. if err == nil {
  339. logging.Info().Msgf("%s in %s", bytesMsg, FormatDuration(time.Since(start)))
  340. if len(findings) != 0 {
  341. logging.Warn().Msgf("leaks found: %d", len(findings))
  342. } else {
  343. logging.Info().Msg("no leaks found")
  344. }
  345. } else {
  346. logging.Warn().Msg(bytesMsg)
  347. logging.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
  348. if len(findings) != 0 {
  349. logging.Warn().Msgf("%d leaks found in partial scan", len(findings))
  350. } else {
  351. logging.Warn().Msg("no leaks found in partial scan")
  352. }
  353. }
  354. // write report if desired
  355. if detector.Reporter != nil {
  356. var (
  357. file io.WriteCloser
  358. reportErr error
  359. )
  360. if detector.ReportPath == report.StdoutReportPath {
  361. file = os.Stdout
  362. } else {
  363. // Open the file.
  364. if file, reportErr = os.Create(detector.ReportPath); reportErr != nil {
  365. goto ReportEnd
  366. }
  367. defer func() {
  368. _ = file.Close()
  369. }()
  370. }
  371. // Write to the file.
  372. if reportErr = detector.Reporter.Write(file, findings); reportErr != nil {
  373. goto ReportEnd
  374. }
  375. ReportEnd:
  376. if reportErr != nil {
  377. logging.Fatal().Err(reportErr).Msg("failed to write report")
  378. }
  379. }
  380. if err != nil {
  381. os.Exit(1)
  382. }
  383. if len(findings) != 0 {
  384. os.Exit(exitCode)
  385. }
  386. }
  387. func fileExists(fileName string) bool {
  388. // check for a .gitleaksignore file
  389. info, err := os.Stat(fileName)
  390. if err != nil && !os.IsNotExist(err) {
  391. return false
  392. }
  393. if info != nil && err == nil {
  394. if !info.IsDir() {
  395. return true
  396. }
  397. }
  398. return false
  399. }
  400. func FormatDuration(d time.Duration) string {
  401. scale := 100 * time.Second
  402. // look for the max scale that is smaller than d
  403. for scale > d {
  404. scale = scale / 10
  405. }
  406. return d.Round(scale / 100).String()
  407. }
  408. func mustGetBoolFlag(cmd *cobra.Command, name string) bool {
  409. value, err := cmd.Flags().GetBool(name)
  410. if err != nil {
  411. logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
  412. }
  413. return value
  414. }
  415. func mustGetIntFlag(cmd *cobra.Command, name string) int {
  416. value, err := cmd.Flags().GetInt(name)
  417. if err != nil {
  418. logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
  419. }
  420. return value
  421. }
  422. func mustGetStringFlag(cmd *cobra.Command, name string) string {
  423. value, err := cmd.Flags().GetString(name)
  424. if err != nil {
  425. logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
  426. }
  427. return value
  428. }