rules.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package models
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "yunion.io/x/jsonutils"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/util/rand"
  22. "yunion.io/x/sqlchemy"
  23. "yunion.io/x/onecloud/pkg/apis"
  24. api "yunion.io/x/onecloud/pkg/apis/cloudnet"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  26. "yunion.io/x/onecloud/pkg/cloudcommon/validators"
  27. "yunion.io/x/onecloud/pkg/httperrors"
  28. "yunion.io/x/onecloud/pkg/mcclient"
  29. "yunion.io/x/onecloud/pkg/util/choices"
  30. "yunion.io/x/onecloud/pkg/util/firewalld"
  31. )
  32. type SRule struct {
  33. db.SStandaloneResourceBase
  34. Prio int `nullable:"false" list:"user" update:"user" create:"optional"`
  35. MatchSrcNet string `length:"32" nullable:"false" list:"user" update:"user" create:"optional"`
  36. MatchDestNet string `length:"32" nullable:"false" list:"user" update:"user" create:"optional"`
  37. MatchProto string `length:"8" nullable:"false" list:"user" update:"user" create:"optional"`
  38. MatchSrcPort int `nullable:"false" list:"user" update:"user" create:"optional"`
  39. MatchDestPort int `nullable:"false" list:"user" update:"user" create:"optional"`
  40. MatchInIfname string `length:"32" nullable:"false" list:"user" update:"user" create:"optional"`
  41. MatchOutIfname string `length:"32" nullable:"false" list:"user" update:"user" create:"optional"`
  42. Action string `length:"32" nullable:"false" list:"user" update:"user" create:"required"`
  43. ActionOptions string `length:"32" nullable:"false" list:"user" update:"user" create:"optional"`
  44. RouterId string `length:"32" nullable:"false" list:"user" create:"optional"`
  45. IsSystem bool `nullable:"false" list:"user" create:"optional"`
  46. }
  47. const (
  48. MIN_PRIO = 0
  49. MAX_PRIO = 2000
  50. DEF_PRIO = 0
  51. DEF_PRIO_ROUTER_FORWARD = 1000
  52. DEF_PRIO_MASQUERADE = 1000
  53. ACT_SNAT = "SNAT"
  54. ACT_DNAT = "DNAT"
  55. ACT_MASQUERADE = "MASQUERADE"
  56. ACT_TCPMSS = "TCPMSS" // FORWARD chain for now
  57. ACT_INPUT_ACCEPT = "INPUT_ACCEPT"
  58. ACT_FORWARD_ACCEPT = "FORWARD_ACCEPT"
  59. PROTO_TCP = "tcp"
  60. PROTO_UDP = "udp"
  61. )
  62. var (
  63. actionChoices = choices.NewChoices(
  64. ACT_SNAT,
  65. ACT_DNAT,
  66. ACT_MASQUERADE,
  67. ACT_TCPMSS,
  68. //"DROP",
  69. ACT_INPUT_ACCEPT,
  70. ACT_FORWARD_ACCEPT,
  71. //"REJECT",
  72. )
  73. protoChoices = choices.NewChoices(
  74. PROTO_TCP,
  75. PROTO_UDP,
  76. )
  77. )
  78. type SRuleManager struct {
  79. db.SStandaloneResourceBaseManager
  80. }
  81. var RuleManager *SRuleManager
  82. func init() {
  83. RuleManager = &SRuleManager{
  84. SStandaloneResourceBaseManager: db.NewStandaloneResourceBaseManager(
  85. SRule{},
  86. "rules_tbl",
  87. "rule",
  88. "rules",
  89. ),
  90. }
  91. RuleManager.SetVirtualObject(RuleManager)
  92. }
  93. func (man *SRuleManager) validateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict, rule *SRule) error {
  94. isUpdate := rule != nil
  95. routerV := validators.NewModelIdOrNameValidator("router", "router", ownerId)
  96. inIfnameV := validators.NewRegexpValidator("match_in_ifname", regexpIfname)
  97. outIfnameV := validators.NewRegexpValidator("match_out_ifname", regexpIfname)
  98. protoV := validators.NewStringChoicesValidator("match_proto", protoChoices)
  99. srcPortV := validators.NewPortValidator("match_src_port")
  100. destPortV := validators.NewPortValidator("match_dest_port")
  101. actionV := validators.NewStringChoicesValidator("action", actionChoices)
  102. actionOptsV := validators.NewStringLenRangeValidator("action_options", 0, 256)
  103. if isUpdate {
  104. inIfnameV.Default(rule.MatchInIfname)
  105. outIfnameV.Default(rule.MatchOutIfname)
  106. protoV.Default(rule.MatchProto)
  107. srcPortV.Default(int64(rule.MatchSrcPort))
  108. destPortV.Default(int64(rule.MatchDestPort))
  109. actionV.Default(rule.Action)
  110. actionOptsV.Default(rule.ActionOptions)
  111. }
  112. vs := []validators.IValidator{
  113. inIfnameV.Optional(true),
  114. outIfnameV.Optional(true),
  115. validators.NewIPv4PrefixValidator("match_src_net").Optional(true),
  116. validators.NewIPv4PrefixValidator("match_dest_net").Optional(true),
  117. protoV.Optional(true),
  118. srcPortV.Optional(true),
  119. destPortV.Optional(true),
  120. actionV,
  121. actionOptsV.Optional(true),
  122. routerV,
  123. }
  124. for _, v := range vs {
  125. if isUpdate {
  126. v.Optional(true)
  127. }
  128. if err := v.Validate(ctx, data); err != nil {
  129. return err
  130. }
  131. }
  132. if actionV.Value == ACT_TCPMSS {
  133. if protoV.Value != "" && protoV.Value != PROTO_TCP {
  134. return httperrors.NewBadRequestError("TCPMSS only works for proto tcp")
  135. }
  136. if protoV.Value == "" {
  137. data.Set("match_proto", jsonutils.NewString(PROTO_TCP))
  138. }
  139. } else if actionV.Value == ACT_DNAT {
  140. if outIfnameV.Value != "" {
  141. return httperrors.NewBadRequestError("cannot match out interface for DNAT")
  142. }
  143. } else if actionV.Value == ACT_SNAT {
  144. if inIfnameV.Value != "" {
  145. return httperrors.NewBadRequestError("cannot match in interface for SNAT")
  146. }
  147. }
  148. if (srcPortV.Value > 0 || destPortV.Value > 0) && protoV.Value == "" {
  149. return httperrors.NewBadRequestError("protocol must be specified when matching port")
  150. }
  151. {
  152. prioDefault := int64(0)
  153. if !isUpdate && actionV.Value == ACT_MASQUERADE && !data.Contains("prio") {
  154. prioDefault = DEF_PRIO_MASQUERADE
  155. }
  156. prioV := validators.NewRangeValidator("prio", MIN_PRIO, MAX_PRIO)
  157. if !isUpdate {
  158. prioV.Default(prioDefault)
  159. }
  160. if err := prioV.Validate(ctx, data); err != nil {
  161. return err
  162. }
  163. }
  164. // XXX validate interface against db
  165. // XXX validate action options
  166. if !isUpdate && !data.Contains("name") {
  167. router := routerV.Model.(*SRouter)
  168. data.Set("name", jsonutils.NewString(
  169. router.Name+"-"+rand.String(4),
  170. ))
  171. }
  172. return nil
  173. }
  174. func (man *SRuleManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
  175. input := apis.StandaloneResourceCreateInput{}
  176. err := data.Unmarshal(&input)
  177. if err != nil {
  178. return nil, httperrors.NewInternalServerError("unmarshal StandaloneResourceCreateInput fail %s", err)
  179. }
  180. input, err = man.SStandaloneResourceBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input)
  181. if err != nil {
  182. return nil, err
  183. }
  184. data.Update(jsonutils.Marshal(input))
  185. if err := man.validateData(ctx, userCred, ownerId, query, data, nil); err != nil {
  186. return nil, err
  187. }
  188. return data, nil
  189. }
  190. // 虚拟路由器路由规则列表
  191. func (man *SRuleManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
  192. input := apis.StandaloneResourceListInput{}
  193. err := query.Unmarshal(&input)
  194. if err != nil {
  195. return nil, errors.Wrap(err, "query.Unmarshal")
  196. }
  197. q, err = man.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, input)
  198. if err != nil {
  199. return nil, errors.Wrap(err, "SStandaloneResourceBaseManager.ListItemFilter")
  200. }
  201. data := query.(*jsonutils.JSONDict)
  202. q, err = validators.ApplyModelFilters(ctx, q, data, []*validators.ModelFilterOptions{
  203. {Key: "router", ModelKeyword: "router", OwnerId: userCred},
  204. })
  205. if err != nil {
  206. return nil, err
  207. }
  208. return q, nil
  209. }
  210. func (rule *SRule) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.RuleUpdateInput) (api.RuleUpdateInput, error) {
  211. var err error
  212. input.StandaloneResourceBaseUpdateInput, err = rule.SStandaloneResourceBase.ValidateUpdateData(ctx, userCred, query, input.StandaloneResourceBaseUpdateInput)
  213. if err != nil {
  214. return input, errors.Wrap(err, "SStandaloneResourceBase.ValidateUpdateData")
  215. }
  216. data := jsonutils.Marshal(input).(*jsonutils.JSONDict)
  217. if err := RuleManager.validateData(ctx, userCred, rule.GetOwnerId(), query, data, rule); err != nil {
  218. return input, errors.Wrap(err, "validateData")
  219. }
  220. return input, nil
  221. }
  222. func (man *SRuleManager) removeByRouter(ctx context.Context, userCred mcclient.TokenCredential, router *SRouter) error {
  223. rules, err := man.getByFilter(map[string]string{
  224. "router_id": router.Id,
  225. })
  226. if err != nil {
  227. return err
  228. }
  229. var errs []error
  230. for j := range rules {
  231. if err := rules[j].Delete(ctx, userCred); err != nil {
  232. errs = append(errs, err)
  233. }
  234. }
  235. return errors.NewAggregate(errs)
  236. }
  237. func (man *SRuleManager) getByFilter(filter map[string]string) ([]SRule, error) {
  238. rules := []SRule{}
  239. q := man.Query()
  240. for key, val := range filter {
  241. q = q.Equals(key, val)
  242. }
  243. if err := db.FetchModelObjects(RuleManager, q, &rules); err != nil {
  244. return nil, err
  245. }
  246. return rules, nil
  247. }
  248. func (man *SRuleManager) getOneByFilter(filter map[string]string) (*SRule, error) {
  249. rules, err := man.getByFilter(filter)
  250. if err != nil {
  251. return nil, err
  252. }
  253. if len(rules) == 0 {
  254. return nil, errNotFound(fmt.Errorf("cannot find rule: %#v", filter))
  255. }
  256. if len(rules) > 1 {
  257. return nil, errMoreThanOne(fmt.Errorf("found more than 1 rules: %#v", filter))
  258. }
  259. return &rules[0], nil
  260. }
  261. func (man *SRuleManager) checkExistenceByFilter(filter map[string]string) error {
  262. rules, err := man.getByFilter(filter)
  263. if err != nil {
  264. return err
  265. }
  266. if len(rules) > 0 {
  267. return fmt.Errorf("rule exist: %s(%s)", rules[0].Name, rules[0].Id)
  268. }
  269. return nil
  270. }
  271. func (man *SRuleManager) getByRouter(router *SRouter) ([]SRule, error) {
  272. filter := map[string]string{
  273. "router_id": router.Id,
  274. }
  275. rules, err := man.getByFilter(filter)
  276. if err != nil {
  277. return nil, err
  278. }
  279. return rules, nil
  280. }
  281. func (man *SRuleManager) addRouterRules(ctx context.Context, userCred mcclient.TokenCredential, router *SRouter) error {
  282. r := &SRule{
  283. Prio: DEF_PRIO_ROUTER_FORWARD,
  284. RouterId: router.Id,
  285. Action: ACT_FORWARD_ACCEPT,
  286. }
  287. r.IsSystem = true
  288. r.Name = router.Name + "-allow-forward-" + rand.String(4)
  289. r.SetModelManager(man, r)
  290. err := man.addRule(ctx, userCred, r)
  291. return err
  292. }
  293. func (man *SRuleManager) addWireguardIfaceRules(ctx context.Context, userCred mcclient.TokenCredential, iface *SIface) error {
  294. r := &SRule{
  295. RouterId: iface.RouterId,
  296. MatchProto: PROTO_UDP,
  297. MatchDestPort: iface.ListenPort,
  298. Action: ACT_INPUT_ACCEPT,
  299. }
  300. r.IsSystem = true
  301. r.Name = iface.Name + "-allow-" + fmt.Sprintf("%d-", iface.ListenPort) + rand.String(4)
  302. r.SetModelManager(man, r)
  303. rules := man.ifaceTCPMSSRules(ctx, userCred, iface)
  304. rules = append(rules, r)
  305. err := man.addRules(ctx, userCred, rules)
  306. return err
  307. }
  308. func (man *SRuleManager) ifaceTCPMSSRules(ctx context.Context, userCred mcclient.TokenCredential, iface *SIface) []*SRule {
  309. rules := []*SRule{
  310. &SRule{
  311. RouterId: iface.RouterId,
  312. MatchInIfname: iface.Ifname,
  313. MatchProto: PROTO_TCP,
  314. Action: ACT_TCPMSS,
  315. ActionOptions: "--clamp-mss-to-pmtu",
  316. },
  317. &SRule{
  318. RouterId: iface.RouterId,
  319. MatchProto: PROTO_TCP,
  320. MatchOutIfname: iface.Ifname,
  321. Action: ACT_TCPMSS,
  322. ActionOptions: "--clamp-mss-to-pmtu",
  323. },
  324. }
  325. for _, r := range rules {
  326. r.IsSystem = true
  327. r.Name = iface.Name + "-tcpmss-" + rand.String(4)
  328. r.SetModelManager(man, r)
  329. }
  330. return rules
  331. }
  332. func (man *SRuleManager) addRules(ctx context.Context, userCred mcclient.TokenCredential, rules []*SRule) error {
  333. errs := []error{}
  334. for _, r := range rules {
  335. err := man.addRule(ctx, userCred, r)
  336. if err != nil {
  337. errs = append(errs, err)
  338. continue
  339. }
  340. }
  341. return errors.NewAggregate(errs)
  342. }
  343. func (man *SRuleManager) addRule(ctx context.Context, userCred mcclient.TokenCredential, rule *SRule) error {
  344. return man.TableSpec().Insert(ctx, rule)
  345. }
  346. func (rule *SRule) firewalldRule() (*firewalld.Rule, error) {
  347. var (
  348. prio int
  349. table string
  350. chain string
  351. action string
  352. body string
  353. matchOthers []string
  354. actionOthers []string
  355. )
  356. prio = rule.Prio
  357. switch rule.Action {
  358. case ACT_SNAT, ACT_DNAT, ACT_MASQUERADE:
  359. table = "nat"
  360. if rule.Action == ACT_DNAT {
  361. chain = "PREROUTING"
  362. } else {
  363. chain = "POSTROUTING"
  364. }
  365. action = rule.Action
  366. case ACT_TCPMSS:
  367. table = "mangle"
  368. chain = "FORWARD" // save INPUT, OUTPUT for future occasions
  369. action = rule.Action
  370. matchOthers = []string{"-m", "tcp", "--tcp-flags", "SYN,RST", "SYN"}
  371. if rule.ActionOptions == "" {
  372. actionOthers = []string{"--clamp-mss-to-pmtu"}
  373. }
  374. case ACT_INPUT_ACCEPT:
  375. table = "filter"
  376. chain = "INPUT"
  377. action = "ACCEPT"
  378. case ACT_FORWARD_ACCEPT:
  379. table = "filter"
  380. chain = "FORWARD"
  381. action = "ACCEPT"
  382. default:
  383. return nil, fmt.Errorf("unknown rule action: %s", rule.Action)
  384. }
  385. {
  386. elms := []string{}
  387. if rule.MatchInIfname != "" {
  388. elms = append(elms, "-i", rule.MatchInIfname)
  389. }
  390. if rule.MatchOutIfname != "" {
  391. elms = append(elms, "-o", rule.MatchOutIfname)
  392. }
  393. if rule.MatchSrcNet != "" {
  394. elms = append(elms, "-s", rule.MatchSrcNet)
  395. }
  396. if rule.MatchDestNet != "" {
  397. elms = append(elms, "-d", rule.MatchDestNet)
  398. }
  399. if rule.MatchProto != "" {
  400. elms = append(elms, "-p", rule.MatchProto)
  401. }
  402. if rule.MatchSrcPort > 0 {
  403. elms = append(elms, "--sport", fmt.Sprintf("%d", rule.MatchSrcPort))
  404. }
  405. if rule.MatchDestPort > 0 {
  406. elms = append(elms, "--dport", fmt.Sprintf("%d", rule.MatchDestPort))
  407. }
  408. elms = append(elms, matchOthers...) // XXX empty elm
  409. elms = append(elms, "-j", action)
  410. if rule.ActionOptions != "" {
  411. elms = append(elms, rule.ActionOptions)
  412. }
  413. elms = append(elms, actionOthers...)
  414. body = strings.Join(elms, " ")
  415. }
  416. r := firewalld.NewIP4Rule(prio, table, chain, body)
  417. return r, nil
  418. }
  419. func (man *SRuleManager) firewalldDirectByRouter(router *SRouter) (*firewalld.Direct, error) {
  420. rules, err := man.getByRouter(router)
  421. if err != nil {
  422. return nil, err
  423. }
  424. rs := []*firewalld.Rule{}
  425. errs := []error{}
  426. for i := range rules {
  427. rule := &rules[i]
  428. r, err := rule.firewalldRule()
  429. if err != nil {
  430. errs = append(errs, err)
  431. continue
  432. }
  433. rs = append(rs, r)
  434. }
  435. return firewalld.NewDirect(rs...), errors.NewAggregate(errs)
  436. }