config.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. package nebula
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "os/signal"
  9. "path/filepath"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "syscall"
  15. "time"
  16. "github.com/imdario/mergo"
  17. "github.com/sirupsen/logrus"
  18. "gopkg.in/yaml.v2"
  19. )
  20. type Config struct {
  21. path string
  22. files []string
  23. Settings map[interface{}]interface{}
  24. oldSettings map[interface{}]interface{}
  25. callbacks []func(*Config)
  26. l *logrus.Logger
  27. }
  28. func NewConfig(l *logrus.Logger) *Config {
  29. return &Config{
  30. Settings: make(map[interface{}]interface{}),
  31. l: l,
  32. }
  33. }
  34. // Load will find all yaml files within path and load them in lexical order
  35. func (c *Config) Load(path string) error {
  36. c.path = path
  37. c.files = make([]string, 0)
  38. err := c.resolve(path, true)
  39. if err != nil {
  40. return err
  41. }
  42. if len(c.files) == 0 {
  43. return fmt.Errorf("no config files found at %s", path)
  44. }
  45. sort.Strings(c.files)
  46. err = c.parse()
  47. if err != nil {
  48. return err
  49. }
  50. return nil
  51. }
  52. func (c *Config) LoadString(raw string) error {
  53. if raw == "" {
  54. return errors.New("Empty configuration")
  55. }
  56. return c.parseRaw([]byte(raw))
  57. }
  58. // RegisterReloadCallback stores a function to be called when a config reload is triggered. The functions registered
  59. // here should decide if they need to make a change to the current process before making the change. HasChanged can be
  60. // used to help decide if a change is necessary.
  61. // These functions should return quickly or spawn their own go routine if they will take a while
  62. func (c *Config) RegisterReloadCallback(f func(*Config)) {
  63. c.callbacks = append(c.callbacks, f)
  64. }
  65. // HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
  66. // k in both the old and new settings will be serialized, the result of the string comparison is returned.
  67. // If k is an empty string the entire config is tested.
  68. // It's important to note that this is very rudimentary and susceptible to configuration ordering issues indicating
  69. // there is change when there actually wasn't any.
  70. func (c *Config) HasChanged(k string) bool {
  71. if c.oldSettings == nil {
  72. return false
  73. }
  74. var (
  75. nv interface{}
  76. ov interface{}
  77. )
  78. if k == "" {
  79. nv = c.Settings
  80. ov = c.oldSettings
  81. k = "all settings"
  82. } else {
  83. nv = c.get(k, c.Settings)
  84. ov = c.get(k, c.oldSettings)
  85. }
  86. newVals, err := yaml.Marshal(nv)
  87. if err != nil {
  88. c.l.WithField("config_path", k).WithError(err).Error("Error while marshaling new config")
  89. }
  90. oldVals, err := yaml.Marshal(ov)
  91. if err != nil {
  92. c.l.WithField("config_path", k).WithError(err).Error("Error while marshaling old config")
  93. }
  94. return string(newVals) != string(oldVals)
  95. }
  96. // CatchHUP will listen for the HUP signal in a go routine and reload all configs found in the
  97. // original path provided to Load. The old settings are shallow copied for change detection after the reload.
  98. func (c *Config) CatchHUP() {
  99. ch := make(chan os.Signal, 1)
  100. signal.Notify(ch, syscall.SIGHUP)
  101. go func() {
  102. for range ch {
  103. c.l.Info("Caught HUP, reloading config")
  104. c.ReloadConfig()
  105. }
  106. }()
  107. }
  108. func (c *Config) ReloadConfig() {
  109. c.oldSettings = make(map[interface{}]interface{})
  110. for k, v := range c.Settings {
  111. c.oldSettings[k] = v
  112. }
  113. err := c.Load(c.path)
  114. if err != nil {
  115. c.l.WithField("config_path", c.path).WithError(err).Error("Error occurred while reloading config")
  116. return
  117. }
  118. for _, v := range c.callbacks {
  119. v(c)
  120. }
  121. }
  122. // GetString will get the string for k or return the default d if not found or invalid
  123. func (c *Config) GetString(k, d string) string {
  124. r := c.Get(k)
  125. if r == nil {
  126. return d
  127. }
  128. return fmt.Sprintf("%v", r)
  129. }
  130. // GetStringSlice will get the slice of strings for k or return the default d if not found or invalid
  131. func (c *Config) GetStringSlice(k string, d []string) []string {
  132. r := c.Get(k)
  133. if r == nil {
  134. return d
  135. }
  136. rv, ok := r.([]interface{})
  137. if !ok {
  138. return d
  139. }
  140. v := make([]string, len(rv))
  141. for i := 0; i < len(v); i++ {
  142. v[i] = fmt.Sprintf("%v", rv[i])
  143. }
  144. return v
  145. }
  146. // GetMap will get the map for k or return the default d if not found or invalid
  147. func (c *Config) GetMap(k string, d map[interface{}]interface{}) map[interface{}]interface{} {
  148. r := c.Get(k)
  149. if r == nil {
  150. return d
  151. }
  152. v, ok := r.(map[interface{}]interface{})
  153. if !ok {
  154. return d
  155. }
  156. return v
  157. }
  158. // GetInt will get the int for k or return the default d if not found or invalid
  159. func (c *Config) GetInt(k string, d int) int {
  160. r := c.GetString(k, strconv.Itoa(d))
  161. v, err := strconv.Atoi(r)
  162. if err != nil {
  163. return d
  164. }
  165. return v
  166. }
  167. // GetBool will get the bool for k or return the default d if not found or invalid
  168. func (c *Config) GetBool(k string, d bool) bool {
  169. r := strings.ToLower(c.GetString(k, fmt.Sprintf("%v", d)))
  170. v, err := strconv.ParseBool(r)
  171. if err != nil {
  172. switch r {
  173. case "y", "yes":
  174. return true
  175. case "n", "no":
  176. return false
  177. }
  178. return d
  179. }
  180. return v
  181. }
  182. // GetDuration will get the duration for k or return the default d if not found or invalid
  183. func (c *Config) GetDuration(k string, d time.Duration) time.Duration {
  184. r := c.GetString(k, "")
  185. v, err := time.ParseDuration(r)
  186. if err != nil {
  187. return d
  188. }
  189. return v
  190. }
  191. func (c *Config) GetLocalAllowList(k string) (*LocalAllowList, error) {
  192. var nameRules []AllowListNameRule
  193. handleKey := func(key string, value interface{}) (bool, error) {
  194. if key == "interfaces" {
  195. var err error
  196. nameRules, err = c.getAllowListInterfaces(k, value)
  197. if err != nil {
  198. return false, err
  199. }
  200. return true, nil
  201. }
  202. return false, nil
  203. }
  204. al, err := c.GetAllowList(k, handleKey)
  205. if err != nil {
  206. return nil, err
  207. }
  208. return &LocalAllowList{AllowList: al, nameRules: nameRules}, nil
  209. }
  210. func (c *Config) GetRemoteAllowList(k, rangesKey string) (*RemoteAllowList, error) {
  211. al, err := c.GetAllowList(k, nil)
  212. if err != nil {
  213. return nil, err
  214. }
  215. remoteAllowRanges, err := c.getRemoteAllowRanges(rangesKey)
  216. if err != nil {
  217. return nil, err
  218. }
  219. return &RemoteAllowList{AllowList: al, insideAllowLists: remoteAllowRanges}, nil
  220. }
  221. func (c *Config) getRemoteAllowRanges(k string) (*CIDR6Tree, error) {
  222. value := c.Get(k)
  223. if value == nil {
  224. return nil, nil
  225. }
  226. remoteAllowRanges := NewCIDR6Tree()
  227. rawMap, ok := value.(map[interface{}]interface{})
  228. if !ok {
  229. return nil, fmt.Errorf("config `%s` has invalid type: %T", k, value)
  230. }
  231. for rawKey, rawValue := range rawMap {
  232. rawCIDR, ok := rawKey.(string)
  233. if !ok {
  234. return nil, fmt.Errorf("config `%s` has invalid key (type %T): %v", k, rawKey, rawKey)
  235. }
  236. allowList, err := c.getAllowList(fmt.Sprintf("%s.%s", k, rawCIDR), rawValue, nil)
  237. if err != nil {
  238. return nil, err
  239. }
  240. _, cidr, err := net.ParseCIDR(rawCIDR)
  241. if err != nil {
  242. return nil, fmt.Errorf("config `%s` has invalid CIDR: %s", k, rawCIDR)
  243. }
  244. remoteAllowRanges.AddCIDR(cidr, allowList)
  245. }
  246. return remoteAllowRanges, nil
  247. }
  248. // If the handleKey func returns true, the rest of the parsing is skipped
  249. // for this key. This allows parsing of special values like `interfaces`.
  250. func (c *Config) GetAllowList(k string, handleKey func(key string, value interface{}) (bool, error)) (*AllowList, error) {
  251. r := c.Get(k)
  252. if r == nil {
  253. return nil, nil
  254. }
  255. return c.getAllowList(k, r, handleKey)
  256. }
  257. // If the handleKey func returns true, the rest of the parsing is skipped
  258. // for this key. This allows parsing of special values like `interfaces`.
  259. func (c *Config) getAllowList(k string, raw interface{}, handleKey func(key string, value interface{}) (bool, error)) (*AllowList, error) {
  260. rawMap, ok := raw.(map[interface{}]interface{})
  261. if !ok {
  262. return nil, fmt.Errorf("config `%s` has invalid type: %T", k, raw)
  263. }
  264. tree := NewCIDR6Tree()
  265. // Keep track of the rules we have added for both ipv4 and ipv6
  266. type allowListRules struct {
  267. firstValue bool
  268. allValuesMatch bool
  269. defaultSet bool
  270. allValues bool
  271. }
  272. rules4 := allowListRules{firstValue: true, allValuesMatch: true, defaultSet: false}
  273. rules6 := allowListRules{firstValue: true, allValuesMatch: true, defaultSet: false}
  274. for rawKey, rawValue := range rawMap {
  275. rawCIDR, ok := rawKey.(string)
  276. if !ok {
  277. return nil, fmt.Errorf("config `%s` has invalid key (type %T): %v", k, rawKey, rawKey)
  278. }
  279. if handleKey != nil {
  280. handled, err := handleKey(rawCIDR, rawValue)
  281. if err != nil {
  282. return nil, err
  283. }
  284. if handled {
  285. continue
  286. }
  287. }
  288. value, ok := rawValue.(bool)
  289. if !ok {
  290. return nil, fmt.Errorf("config `%s` has invalid value (type %T): %v", k, rawValue, rawValue)
  291. }
  292. _, cidr, err := net.ParseCIDR(rawCIDR)
  293. if err != nil {
  294. return nil, fmt.Errorf("config `%s` has invalid CIDR: %s", k, rawCIDR)
  295. }
  296. // TODO: should we error on duplicate CIDRs in the config?
  297. tree.AddCIDR(cidr, value)
  298. maskBits, maskSize := cidr.Mask.Size()
  299. var rules *allowListRules
  300. if maskSize == 32 {
  301. rules = &rules4
  302. } else {
  303. rules = &rules6
  304. }
  305. if rules.firstValue {
  306. rules.allValues = value
  307. rules.firstValue = false
  308. } else {
  309. if value != rules.allValues {
  310. rules.allValuesMatch = false
  311. }
  312. }
  313. // Check if this is 0.0.0.0/0 or ::/0
  314. if maskBits == 0 {
  315. rules.defaultSet = true
  316. }
  317. }
  318. if !rules4.defaultSet {
  319. if rules4.allValuesMatch {
  320. _, zeroCIDR, _ := net.ParseCIDR("0.0.0.0/0")
  321. tree.AddCIDR(zeroCIDR, !rules4.allValues)
  322. } else {
  323. return nil, fmt.Errorf("config `%s` contains both true and false rules, but no default set for 0.0.0.0/0", k)
  324. }
  325. }
  326. if !rules6.defaultSet {
  327. if rules6.allValuesMatch {
  328. _, zeroCIDR, _ := net.ParseCIDR("::/0")
  329. tree.AddCIDR(zeroCIDR, !rules6.allValues)
  330. } else {
  331. return nil, fmt.Errorf("config `%s` contains both true and false rules, but no default set for ::/0", k)
  332. }
  333. }
  334. return &AllowList{cidrTree: tree}, nil
  335. }
  336. func (c *Config) getAllowListInterfaces(k string, v interface{}) ([]AllowListNameRule, error) {
  337. var nameRules []AllowListNameRule
  338. rawRules, ok := v.(map[interface{}]interface{})
  339. if !ok {
  340. return nil, fmt.Errorf("config `%s.interfaces` is invalid (type %T): %v", k, v, v)
  341. }
  342. firstEntry := true
  343. var allValues bool
  344. for rawName, rawAllow := range rawRules {
  345. name, ok := rawName.(string)
  346. if !ok {
  347. return nil, fmt.Errorf("config `%s.interfaces` has invalid key (type %T): %v", k, rawName, rawName)
  348. }
  349. allow, ok := rawAllow.(bool)
  350. if !ok {
  351. return nil, fmt.Errorf("config `%s.interfaces` has invalid value (type %T): %v", k, rawAllow, rawAllow)
  352. }
  353. nameRE, err := regexp.Compile("^" + name + "$")
  354. if err != nil {
  355. return nil, fmt.Errorf("config `%s.interfaces` has invalid key: %s: %v", k, name, err)
  356. }
  357. nameRules = append(nameRules, AllowListNameRule{
  358. Name: nameRE,
  359. Allow: allow,
  360. })
  361. if firstEntry {
  362. allValues = allow
  363. firstEntry = false
  364. } else {
  365. if allow != allValues {
  366. return nil, fmt.Errorf("config `%s.interfaces` values must all be the same true/false value", k)
  367. }
  368. }
  369. }
  370. return nameRules, nil
  371. }
  372. func (c *Config) Get(k string) interface{} {
  373. return c.get(k, c.Settings)
  374. }
  375. func (c *Config) IsSet(k string) bool {
  376. return c.get(k, c.Settings) != nil
  377. }
  378. func (c *Config) get(k string, v interface{}) interface{} {
  379. parts := strings.Split(k, ".")
  380. for _, p := range parts {
  381. m, ok := v.(map[interface{}]interface{})
  382. if !ok {
  383. return nil
  384. }
  385. v, ok = m[p]
  386. if !ok {
  387. return nil
  388. }
  389. }
  390. return v
  391. }
  392. // direct signifies if this is the config path directly specified by the user,
  393. // versus a file/dir found by recursing into that path
  394. func (c *Config) resolve(path string, direct bool) error {
  395. i, err := os.Stat(path)
  396. if err != nil {
  397. return nil
  398. }
  399. if !i.IsDir() {
  400. c.addFile(path, direct)
  401. return nil
  402. }
  403. paths, err := readDirNames(path)
  404. if err != nil {
  405. return fmt.Errorf("problem while reading directory %s: %s", path, err)
  406. }
  407. for _, p := range paths {
  408. err := c.resolve(filepath.Join(path, p), false)
  409. if err != nil {
  410. return err
  411. }
  412. }
  413. return nil
  414. }
  415. func (c *Config) addFile(path string, direct bool) error {
  416. ext := filepath.Ext(path)
  417. if !direct && ext != ".yaml" && ext != ".yml" {
  418. return nil
  419. }
  420. ap, err := filepath.Abs(path)
  421. if err != nil {
  422. return err
  423. }
  424. c.files = append(c.files, ap)
  425. return nil
  426. }
  427. func (c *Config) parseRaw(b []byte) error {
  428. var m map[interface{}]interface{}
  429. err := yaml.Unmarshal(b, &m)
  430. if err != nil {
  431. return err
  432. }
  433. c.Settings = m
  434. return nil
  435. }
  436. func (c *Config) parse() error {
  437. var m map[interface{}]interface{}
  438. for _, path := range c.files {
  439. b, err := ioutil.ReadFile(path)
  440. if err != nil {
  441. return err
  442. }
  443. var nm map[interface{}]interface{}
  444. err = yaml.Unmarshal(b, &nm)
  445. if err != nil {
  446. return err
  447. }
  448. // We need to use WithAppendSlice so that firewall rules in separate
  449. // files are appended together
  450. err = mergo.Merge(&nm, m, mergo.WithAppendSlice)
  451. m = nm
  452. if err != nil {
  453. return err
  454. }
  455. }
  456. c.Settings = m
  457. return nil
  458. }
  459. func readDirNames(path string) ([]string, error) {
  460. f, err := os.Open(path)
  461. if err != nil {
  462. return nil, err
  463. }
  464. paths, err := f.Readdirnames(-1)
  465. f.Close()
  466. if err != nil {
  467. return nil, err
  468. }
  469. sort.Strings(paths)
  470. return paths, nil
  471. }
  472. func configLogger(c *Config) error {
  473. // set up our logging level
  474. logLevel, err := logrus.ParseLevel(strings.ToLower(c.GetString("logging.level", "info")))
  475. if err != nil {
  476. return fmt.Errorf("%s; possible levels: %s", err, logrus.AllLevels)
  477. }
  478. c.l.SetLevel(logLevel)
  479. disableTimestamp := c.GetBool("logging.disable_timestamp", false)
  480. timestampFormat := c.GetString("logging.timestamp_format", "")
  481. fullTimestamp := (timestampFormat != "")
  482. if timestampFormat == "" {
  483. timestampFormat = time.RFC3339
  484. }
  485. logFormat := strings.ToLower(c.GetString("logging.format", "text"))
  486. switch logFormat {
  487. case "text":
  488. c.l.Formatter = &logrus.TextFormatter{
  489. TimestampFormat: timestampFormat,
  490. FullTimestamp: fullTimestamp,
  491. DisableTimestamp: disableTimestamp,
  492. }
  493. case "json":
  494. c.l.Formatter = &logrus.JSONFormatter{
  495. TimestampFormat: timestampFormat,
  496. DisableTimestamp: disableTimestamp,
  497. }
  498. default:
  499. return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
  500. }
  501. return nil
  502. }