config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. package config
  2. import (
  3. _ "embed"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "github.com/spf13/viper"
  9. "github.com/zricethezav/gitleaks/v8/logging"
  10. "github.com/zricethezav/gitleaks/v8/regexp"
  11. )
  12. var (
  13. //go:embed gitleaks.toml
  14. DefaultConfig string
  15. // use to keep track of how many configs we can extend
  16. // yea I know, globals bad
  17. extendDepth int
  18. )
  19. const maxExtendDepth = 2
  20. // ViperConfig is the config struct used by the Viper config package
  21. // to parse the config file. This struct does not include regular expressions.
  22. // It is used as an intermediary to convert the Viper config to the Config struct.
  23. type ViperConfig struct {
  24. Title string
  25. Description string
  26. Extend Extend
  27. Rules []struct {
  28. ID string
  29. Description string
  30. Path string
  31. Regex string
  32. SecretGroup int
  33. Entropy float64
  34. Keywords []string
  35. Tags []string
  36. // Deprecated: this is a shim for backwards-compatibility.
  37. // TODO: Remove this in 9.x.
  38. AllowList *viperRuleAllowlist
  39. Allowlists []*viperRuleAllowlist
  40. }
  41. // Deprecated: this is a shim for backwards-compatibility.
  42. // TODO: Remove this in 9.x.
  43. AllowList *viperGlobalAllowlist
  44. Allowlists []*viperGlobalAllowlist
  45. // EnableExperimentalAllowlistOptimizations enables a preview feature.
  46. // See: https://github.com/gitleaks/gitleaks/pull/1731
  47. //
  48. // NOTE: This flag may be removed in the future.
  49. EnableExperimentalAllowlistOptimizations bool
  50. }
  51. type viperRuleAllowlist struct {
  52. Description string
  53. Condition string
  54. Commits []string
  55. Paths []string
  56. RegexTarget string
  57. Regexes []string
  58. StopWords []string
  59. }
  60. type viperGlobalAllowlist struct {
  61. TargetRules []string
  62. viperRuleAllowlist `mapstructure:",squash"`
  63. }
  64. // Config is a configuration struct that contains rules and an allowlist if present.
  65. type Config struct {
  66. Title string
  67. Extend Extend
  68. Path string
  69. Description string
  70. Rules map[string]Rule
  71. Keywords map[string]struct{}
  72. // used to keep sarif results consistent
  73. OrderedRules []string
  74. Allowlists []*Allowlist
  75. }
  76. // Extend is a struct that allows users to define how they want their
  77. // configuration extended by other configuration files.
  78. type Extend struct {
  79. Path string
  80. URL string
  81. UseDefault bool
  82. DisabledRules []string
  83. }
  84. func (vc *ViperConfig) Translate() (Config, error) {
  85. var (
  86. keywords = make(map[string]struct{})
  87. orderedRules []string
  88. rulesMap = make(map[string]Rule)
  89. ruleAllowlists = make(map[string][]*Allowlist)
  90. )
  91. // Validate individual rules.
  92. for _, vr := range vc.Rules {
  93. var (
  94. pathPat *regexp.Regexp
  95. regexPat *regexp.Regexp
  96. )
  97. if vr.Path != "" {
  98. pathPat = regexp.MustCompile(vr.Path)
  99. }
  100. if vr.Regex != "" {
  101. regexPat = regexp.MustCompile(vr.Regex)
  102. }
  103. if vr.Keywords == nil {
  104. vr.Keywords = []string{}
  105. } else {
  106. for i, k := range vr.Keywords {
  107. keyword := strings.ToLower(k)
  108. keywords[keyword] = struct{}{}
  109. vr.Keywords[i] = keyword
  110. }
  111. }
  112. if vr.Tags == nil {
  113. vr.Tags = []string{}
  114. }
  115. cr := Rule{
  116. RuleID: vr.ID,
  117. Description: vr.Description,
  118. Regex: regexPat,
  119. SecretGroup: vr.SecretGroup,
  120. Entropy: vr.Entropy,
  121. Path: pathPat,
  122. Keywords: vr.Keywords,
  123. Tags: vr.Tags,
  124. }
  125. // Parse the rule allowlists, including the older format for backwards compatibility.
  126. if vr.AllowList != nil {
  127. // TODO: Remove this in v9.
  128. if len(vr.Allowlists) > 0 {
  129. return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID)
  130. }
  131. vr.Allowlists = append(vr.Allowlists, vr.AllowList)
  132. }
  133. for _, a := range vr.Allowlists {
  134. allowlist, err := vc.parseAllowlist(a)
  135. if err != nil {
  136. return Config{}, fmt.Errorf("%s: [[rules.allowlists]] %w", cr.RuleID, err)
  137. }
  138. cr.Allowlists = append(cr.Allowlists, allowlist)
  139. }
  140. orderedRules = append(orderedRules, cr.RuleID)
  141. rulesMap[cr.RuleID] = cr
  142. }
  143. // Assemble the config.
  144. c := Config{
  145. Title: vc.Title,
  146. Description: vc.Description,
  147. Extend: vc.Extend,
  148. Rules: rulesMap,
  149. Keywords: keywords,
  150. OrderedRules: orderedRules,
  151. }
  152. // Parse the config allowlists, including the older format for backwards compatibility.
  153. if vc.AllowList != nil {
  154. // TODO: Remove this in v9.
  155. if len(vc.Allowlists) > 0 {
  156. return Config{}, errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]")
  157. }
  158. vc.Allowlists = append(vc.Allowlists, vc.AllowList)
  159. }
  160. for _, a := range vc.Allowlists {
  161. allowlist, err := vc.parseAllowlist(&a.viperRuleAllowlist)
  162. if err != nil {
  163. return Config{}, fmt.Errorf("[[allowlists]] %w", err)
  164. }
  165. // Allowlists with |targetRules| aren't added to the global list.
  166. if len(a.TargetRules) > 0 {
  167. for _, ruleID := range a.TargetRules {
  168. // It's not possible to validate |ruleID| until after extend.
  169. ruleAllowlists[ruleID] = append(ruleAllowlists[ruleID], allowlist)
  170. }
  171. } else {
  172. c.Allowlists = append(c.Allowlists, allowlist)
  173. }
  174. }
  175. if maxExtendDepth != extendDepth {
  176. // disallow both usedefault and path from being set
  177. if c.Extend.Path != "" && c.Extend.UseDefault {
  178. return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
  179. }
  180. if c.Extend.UseDefault {
  181. if err := c.extendDefault(vc); err != nil {
  182. return Config{}, err
  183. }
  184. } else if c.Extend.Path != "" {
  185. if err := c.extendPath(vc); err != nil {
  186. return Config{}, err
  187. }
  188. }
  189. }
  190. // Validate the rules after everything has been assembled (including extended configs).
  191. if extendDepth == 0 {
  192. for _, rule := range c.Rules {
  193. if err := rule.Validate(); err != nil {
  194. return Config{}, err
  195. }
  196. }
  197. // Populate targeted configs.
  198. for ruleID, allowlists := range ruleAllowlists {
  199. rule, ok := c.Rules[ruleID]
  200. if !ok {
  201. return Config{}, fmt.Errorf("[[allowlists]] target rule ID '%s' does not exist", ruleID)
  202. }
  203. rule.Allowlists = append(rule.Allowlists, allowlists...)
  204. c.Rules[ruleID] = rule
  205. }
  206. }
  207. return c, nil
  208. }
  209. func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
  210. var matchCondition AllowlistMatchCondition
  211. switch strings.ToUpper(a.Condition) {
  212. case "AND", "&&":
  213. matchCondition = AllowlistMatchAnd
  214. case "", "OR", "||":
  215. matchCondition = AllowlistMatchOr
  216. default:
  217. return nil, fmt.Errorf("unknown allowlist |condition| '%s' (expected 'and', 'or')", a.Condition)
  218. }
  219. // Validate the target.
  220. regexTarget := a.RegexTarget
  221. if regexTarget != "" {
  222. switch regexTarget {
  223. case "secret":
  224. regexTarget = ""
  225. case "match", "line":
  226. // do nothing
  227. default:
  228. return nil, fmt.Errorf("unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", regexTarget)
  229. }
  230. }
  231. var allowlistRegexes []*regexp.Regexp
  232. for _, a := range a.Regexes {
  233. allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
  234. }
  235. var allowlistPaths []*regexp.Regexp
  236. for _, a := range a.Paths {
  237. allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
  238. }
  239. allowlist := &Allowlist{
  240. Description: a.Description,
  241. MatchCondition: matchCondition,
  242. Commits: a.Commits,
  243. Paths: allowlistPaths,
  244. RegexTarget: regexTarget,
  245. Regexes: allowlistRegexes,
  246. StopWords: a.StopWords,
  247. EnableExperimentalOptimizations: vc.EnableExperimentalAllowlistOptimizations,
  248. }
  249. if err := allowlist.Validate(); err != nil {
  250. return nil, err
  251. }
  252. return allowlist, nil
  253. }
  254. func (c *Config) GetOrderedRules() []Rule {
  255. var orderedRules []Rule
  256. for _, id := range c.OrderedRules {
  257. if _, ok := c.Rules[id]; ok {
  258. orderedRules = append(orderedRules, c.Rules[id])
  259. }
  260. }
  261. return orderedRules
  262. }
  263. func (c *Config) extendDefault(parent *ViperConfig) error {
  264. extendDepth++
  265. viper.SetConfigType("toml")
  266. if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
  267. return fmt.Errorf("failed to load extended default config, err: %w", err)
  268. }
  269. defaultViperConfig := ViperConfig{
  270. EnableExperimentalAllowlistOptimizations: parent.EnableExperimentalAllowlistOptimizations,
  271. }
  272. if err := viper.Unmarshal(&defaultViperConfig); err != nil {
  273. return fmt.Errorf("failed to load extended default config, err: %w", err)
  274. }
  275. cfg, err := defaultViperConfig.Translate()
  276. if err != nil {
  277. return fmt.Errorf("failed to load extended default config, err: %w", err)
  278. }
  279. logging.Debug().Msg("extending config with default config")
  280. c.extend(cfg)
  281. return nil
  282. }
  283. func (c *Config) extendPath(parent *ViperConfig) error {
  284. extendDepth++
  285. viper.SetConfigFile(c.Extend.Path)
  286. if err := viper.ReadInConfig(); err != nil {
  287. return fmt.Errorf("failed to load extended config, err: %w", err)
  288. }
  289. extensionViperConfig := ViperConfig{
  290. EnableExperimentalAllowlistOptimizations: parent.EnableExperimentalAllowlistOptimizations,
  291. }
  292. if err := viper.Unmarshal(&extensionViperConfig); err != nil {
  293. return fmt.Errorf("failed to load extended config, err: %w", err)
  294. }
  295. cfg, err := extensionViperConfig.Translate()
  296. if err != nil {
  297. return fmt.Errorf("failed to load extended config, err: %w", err)
  298. }
  299. logging.Debug().Msgf("extending config with %s", c.Extend.Path)
  300. c.extend(cfg)
  301. return nil
  302. }
  303. func (c *Config) extendURL() {
  304. // TODO
  305. }
  306. func (c *Config) extend(extensionConfig Config) {
  307. // Get config name for helpful log messages.
  308. var configName string
  309. if c.Extend.Path != "" {
  310. configName = c.Extend.Path
  311. } else {
  312. configName = "default"
  313. }
  314. // Convert |Config.DisabledRules| into a map for ease of access.
  315. disabledRuleIDs := map[string]struct{}{}
  316. for _, id := range c.Extend.DisabledRules {
  317. if _, ok := extensionConfig.Rules[id]; !ok {
  318. logging.Warn().
  319. Str("rule-id", id).
  320. Str("config", configName).
  321. Msg("Disabled rule doesn't exist in extended config.")
  322. }
  323. disabledRuleIDs[id] = struct{}{}
  324. }
  325. for ruleID, baseRule := range extensionConfig.Rules {
  326. // Skip the rule.
  327. if _, ok := disabledRuleIDs[ruleID]; ok {
  328. logging.Debug().
  329. Str("rule-id", ruleID).
  330. Str("config", configName).
  331. Msg("Ignoring rule from extended config.")
  332. continue
  333. }
  334. currentRule, ok := c.Rules[ruleID]
  335. if !ok {
  336. // Rule doesn't exist, add it to the config.
  337. c.Rules[ruleID] = baseRule
  338. for _, k := range baseRule.Keywords {
  339. c.Keywords[k] = struct{}{}
  340. }
  341. c.OrderedRules = append(c.OrderedRules, ruleID)
  342. } else {
  343. // Rule exists, merge our changes into the base.
  344. if currentRule.Description != "" {
  345. baseRule.Description = currentRule.Description
  346. }
  347. if currentRule.Entropy != 0 {
  348. baseRule.Entropy = currentRule.Entropy
  349. }
  350. if currentRule.SecretGroup != 0 {
  351. baseRule.SecretGroup = currentRule.SecretGroup
  352. }
  353. if currentRule.Regex != nil {
  354. baseRule.Regex = currentRule.Regex
  355. }
  356. if currentRule.Path != nil {
  357. baseRule.Path = currentRule.Path
  358. }
  359. baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
  360. baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
  361. baseRule.Allowlists = append(baseRule.Allowlists, currentRule.Allowlists...)
  362. // The keywords from the base rule and the extended rule must be merged into the global keywords list
  363. for _, k := range baseRule.Keywords {
  364. c.Keywords[k] = struct{}{}
  365. }
  366. c.Rules[ruleID] = baseRule
  367. }
  368. }
  369. // append allowlists, not attempting to merge
  370. c.Allowlists = append(c.Allowlists, extensionConfig.Allowlists...)
  371. // sort to keep extended rules in order
  372. sort.Strings(c.OrderedRules)
  373. }