config.go 12 KB

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