4
0

config.go 12 KB

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