OpenStack Networking (Neutron)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

896 lines
39KB

  1. # Copyright 2012 VMware, Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # 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, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. import netaddr
  15. from neutron_lib.api.definitions import port as port_def
  16. from neutron_lib.api import validators
  17. from neutron_lib.callbacks import events
  18. from neutron_lib.callbacks import exceptions
  19. from neutron_lib.callbacks import registry
  20. from neutron_lib.callbacks import resources
  21. from neutron_lib import constants
  22. from neutron_lib import context as context_lib
  23. from neutron_lib.db import api as db_api
  24. from neutron_lib.db import model_query
  25. from neutron_lib.db import resource_extend
  26. from neutron_lib.db import utils as db_utils
  27. from neutron_lib import exceptions as n_exc
  28. from neutron_lib.utils import helpers
  29. from neutron_lib.utils import net
  30. from oslo_utils import uuidutils
  31. import six
  32. from sqlalchemy.orm import scoped_session
  33. from neutron._i18n import _
  34. from neutron.common import constants as n_const
  35. from neutron.common import utils
  36. from neutron.db.models import securitygroup as sg_models
  37. from neutron.db import rbac_db_mixin as rbac_mixin
  38. from neutron.extensions import securitygroup as ext_sg
  39. from neutron.objects import base as base_obj
  40. from neutron.objects import ports as port_obj
  41. from neutron.objects import securitygroup as sg_obj
  42. @resource_extend.has_resource_extenders
  43. @registry.has_registry_receivers
  44. class SecurityGroupDbMixin(ext_sg.SecurityGroupPluginBase,
  45. rbac_mixin.RbacPluginMixin):
  46. """Mixin class to add security group to db_base_plugin_v2."""
  47. __native_bulk_support = True
  48. def create_security_group_bulk(self, context, security_groups):
  49. return self._create_bulk('security_group', context,
  50. security_groups)
  51. def _registry_notify(self, res, event, id=None, exc_cls=None, **kwargs):
  52. # NOTE(armax): a callback exception here will prevent the request
  53. # from being processed. This is a hook point for backend's validation;
  54. # we raise to propagate the reason for the failure.
  55. try:
  56. if 'payload' in kwargs:
  57. # TODO(boden): remove shim once all callbacks use payloads
  58. registry.publish(res, event, self, payload=kwargs['payload'])
  59. else:
  60. registry.notify(res, event, self, **kwargs)
  61. except exceptions.CallbackFailure as e:
  62. if exc_cls:
  63. reason = (_('cannot perform %(event)s due to %(reason)s') %
  64. {'event': event, 'reason': e})
  65. raise exc_cls(reason=reason, id=id)
  66. @db_api.retry_if_session_inactive()
  67. def create_security_group(self, context, security_group, default_sg=False):
  68. """Create security group.
  69. If default_sg is true that means we are a default security group for
  70. a given tenant if it does not exist.
  71. """
  72. s = security_group['security_group']
  73. kwargs = {
  74. 'context': context,
  75. 'security_group': s,
  76. 'is_default': default_sg,
  77. }
  78. self._registry_notify(resources.SECURITY_GROUP, events.BEFORE_CREATE,
  79. exc_cls=ext_sg.SecurityGroupConflict,
  80. payload=events.DBEventPayload(
  81. context, metadata={'is_default': default_sg},
  82. request_body=security_group,
  83. desired_state=s))
  84. tenant_id = s['tenant_id']
  85. if not default_sg:
  86. self._ensure_default_security_group(context, tenant_id)
  87. else:
  88. existing_def_sg_id = self._get_default_sg_id(context, tenant_id)
  89. if existing_def_sg_id is not None:
  90. # default already exists, return it
  91. return self.get_security_group(context, existing_def_sg_id)
  92. with db_api.CONTEXT_WRITER.using(context):
  93. sg = sg_obj.SecurityGroup(
  94. context, id=s.get('id') or uuidutils.generate_uuid(),
  95. description=s['description'], project_id=tenant_id,
  96. name=s['name'], is_default=default_sg)
  97. sg.create()
  98. for ethertype in ext_sg.sg_supported_ethertypes:
  99. if default_sg:
  100. # Allow intercommunication
  101. ingress_rule = sg_obj.SecurityGroupRule(
  102. context, id=uuidutils.generate_uuid(),
  103. project_id=tenant_id, security_group_id=sg.id,
  104. direction='ingress', ethertype=ethertype,
  105. remote_group_id=sg.id)
  106. ingress_rule.create()
  107. sg.rules.append(ingress_rule)
  108. egress_rule = sg_obj.SecurityGroupRule(
  109. context, id=uuidutils.generate_uuid(),
  110. project_id=tenant_id, security_group_id=sg.id,
  111. direction='egress', ethertype=ethertype)
  112. egress_rule.create()
  113. sg.rules.append(egress_rule)
  114. sg.obj_reset_changes(['rules'])
  115. # fetch sg from db to load the sg rules with sg model.
  116. sg = sg_obj.SecurityGroup.get_object(context, id=sg.id)
  117. secgroup_dict = self._make_security_group_dict(sg)
  118. kwargs['security_group'] = secgroup_dict
  119. self._registry_notify(resources.SECURITY_GROUP,
  120. events.PRECOMMIT_CREATE,
  121. exc_cls=ext_sg.SecurityGroupConflict,
  122. **kwargs)
  123. registry.notify(resources.SECURITY_GROUP, events.AFTER_CREATE, self,
  124. **kwargs)
  125. return secgroup_dict
  126. @db_api.retry_if_session_inactive()
  127. def get_security_groups(self, context, filters=None, fields=None,
  128. sorts=None, limit=None,
  129. marker=None, page_reverse=False, default_sg=False):
  130. # If default_sg is True do not call _ensure_default_security_group()
  131. # so this can be done recursively. Context.tenant_id is checked
  132. # because all the unit tests do not explicitly set the context on
  133. # GETS. TODO(arosen) context handling can probably be improved here.
  134. filters = filters or {}
  135. if not default_sg and context.tenant_id:
  136. tenant_id = filters.get('tenant_id')
  137. if tenant_id:
  138. tenant_id = tenant_id[0]
  139. else:
  140. tenant_id = context.tenant_id
  141. self._ensure_default_security_group(context, tenant_id)
  142. pager = base_obj.Pager(
  143. sorts=sorts, limit=limit, marker=marker, page_reverse=page_reverse)
  144. sg_objs = sg_obj.SecurityGroup.get_objects(
  145. context, _pager=pager, validate_filters=False,
  146. fields=fields, **filters)
  147. return [self._make_security_group_dict(obj, fields) for obj in sg_objs]
  148. @db_api.retry_if_session_inactive()
  149. def get_security_groups_count(self, context, filters=None):
  150. filters = filters or {}
  151. return sg_obj.SecurityGroup.count(
  152. context, validate_filters=False, **filters)
  153. @db_api.retry_if_session_inactive()
  154. def get_security_group(self, context, id, fields=None, tenant_id=None):
  155. """Tenant id is given to handle the case when creating a security
  156. group rule on behalf of another use.
  157. """
  158. if tenant_id:
  159. tmp_context_tenant_id = context.tenant_id
  160. context.tenant_id = tenant_id
  161. try:
  162. with db_api.CONTEXT_READER.using(context):
  163. ret = self._make_security_group_dict(self._get_security_group(
  164. context, id,
  165. fields=fields),
  166. fields)
  167. if (fields is None or len(fields) == 0 or
  168. 'security_group_rules' in fields):
  169. rules = self.get_security_group_rules(
  170. context_lib.get_admin_context(),
  171. {'security_group_id': [id]})
  172. ret['security_group_rules'] = rules
  173. finally:
  174. if tenant_id:
  175. context.tenant_id = tmp_context_tenant_id
  176. return ret
  177. def _get_security_group(self, context, id, fields=None):
  178. sg = sg_obj.SecurityGroup.get_object(context, fields=fields, id=id)
  179. if sg is None:
  180. raise ext_sg.SecurityGroupNotFound(id=id)
  181. return sg
  182. def _check_security_group(self, context, id, tenant_id=None):
  183. if tenant_id:
  184. tmp_context_tenant_id = context.tenant_id
  185. context.tenant_id = tenant_id
  186. try:
  187. if not sg_obj.SecurityGroup.objects_exist(context, id=id):
  188. raise ext_sg.SecurityGroupNotFound(id=id)
  189. finally:
  190. if tenant_id:
  191. context.tenant_id = tmp_context_tenant_id
  192. @db_api.retry_if_session_inactive()
  193. def delete_security_group(self, context, id):
  194. filters = {'security_group_id': [id]}
  195. with db_api.CONTEXT_READER.using(context):
  196. ports = self._get_port_security_group_bindings(context, filters)
  197. if ports:
  198. raise ext_sg.SecurityGroupInUse(id=id)
  199. # confirm security group exists
  200. sg = self._get_security_group(context, id, fields=['id', 'name'])
  201. if sg['name'] == 'default' and not context.is_admin:
  202. raise ext_sg.SecurityGroupCannotRemoveDefault()
  203. kwargs = {
  204. 'context': context,
  205. 'security_group_id': id,
  206. 'security_group': sg,
  207. }
  208. self._registry_notify(resources.SECURITY_GROUP,
  209. events.BEFORE_DELETE,
  210. exc_cls=ext_sg.SecurityGroupInUse, id=id,
  211. payload=events.DBEventPayload(
  212. context, states=(sg,), resource_id=id))
  213. with db_api.CONTEXT_WRITER.using(context):
  214. # pass security_group_rule_ids to ensure
  215. # consistency with deleted rules
  216. # get security_group_bindings and security_group one more time
  217. # so that they will be attached for session where sg will be
  218. # deleted
  219. ports = self._get_port_security_group_bindings(context, filters)
  220. sg = self._get_security_group(context, id)
  221. kwargs['security_group_rule_ids'] = [r['id'] for r in sg.rules]
  222. kwargs['security_group'] = self._make_security_group_dict(sg)
  223. self._registry_notify(resources.SECURITY_GROUP,
  224. events.PRECOMMIT_DELETE,
  225. exc_cls=ext_sg.SecurityGroupInUse, id=id,
  226. **kwargs)
  227. sg.delete()
  228. kwargs.pop('security_group')
  229. registry.notify(resources.SECURITY_GROUP, events.AFTER_DELETE,
  230. self, **kwargs)
  231. @db_api.retry_if_session_inactive()
  232. def update_security_group(self, context, id, security_group):
  233. s = security_group['security_group']
  234. kwargs = {
  235. 'context': context,
  236. 'security_group_id': id,
  237. 'security_group': s,
  238. }
  239. self._registry_notify(resources.SECURITY_GROUP, events.BEFORE_UPDATE,
  240. exc_cls=ext_sg.SecurityGroupConflict, **kwargs)
  241. with db_api.CONTEXT_WRITER.using(context):
  242. sg = self._get_security_group(context, id)
  243. if sg.name == 'default' and 'name' in s:
  244. raise ext_sg.SecurityGroupCannotUpdateDefault()
  245. sg_dict = self._make_security_group_dict(sg)
  246. kwargs['original_security_group'] = sg_dict
  247. sg.update_fields(s)
  248. sg.update()
  249. sg_dict = self._make_security_group_dict(sg)
  250. kwargs['security_group'] = sg_dict
  251. self._registry_notify(
  252. resources.SECURITY_GROUP,
  253. events.PRECOMMIT_UPDATE,
  254. exc_cls=ext_sg.SecurityGroupConflict,
  255. payload=events.DBEventPayload(
  256. context, request_body=s,
  257. states=(kwargs['original_security_group'],),
  258. resource_id=id, desired_state=sg_dict))
  259. registry.notify(resources.SECURITY_GROUP, events.AFTER_UPDATE, self,
  260. **kwargs)
  261. return sg_dict
  262. def _make_security_group_dict(self, security_group, fields=None):
  263. res = {'id': security_group['id'],
  264. 'name': security_group['name'],
  265. 'tenant_id': security_group['tenant_id'],
  266. 'description': security_group['description']}
  267. if security_group.rules:
  268. res['security_group_rules'] = [
  269. self._make_security_group_rule_dict(r.db_obj)
  270. for r in security_group.rules
  271. ]
  272. else:
  273. res['security_group_rules'] = []
  274. resource_extend.apply_funcs(ext_sg.SECURITYGROUPS, res,
  275. security_group.db_obj)
  276. return db_utils.resource_fields(res, fields)
  277. @staticmethod
  278. def _make_security_group_binding_dict(security_group, fields=None):
  279. res = {'port_id': security_group['port_id'],
  280. 'security_group_id': security_group['security_group_id']}
  281. return db_utils.resource_fields(res, fields)
  282. @db_api.retry_if_session_inactive()
  283. def _create_port_security_group_binding(self, context, port_id,
  284. security_group_id):
  285. with db_api.CONTEXT_WRITER.using(context):
  286. db = sg_models.SecurityGroupPortBinding(
  287. port_id=port_id, security_group_id=security_group_id)
  288. context.session.add(db)
  289. def _get_port_security_group_bindings(self, context,
  290. filters=None, fields=None):
  291. return model_query.get_collection(
  292. context, sg_models.SecurityGroupPortBinding,
  293. self._make_security_group_binding_dict,
  294. filters=filters, fields=fields)
  295. @db_api.retry_if_session_inactive()
  296. def _delete_port_security_group_bindings(self, context, port_id):
  297. with db_api.CONTEXT_WRITER.using(context):
  298. query = model_query.query_with_hooks(
  299. context, sg_models.SecurityGroupPortBinding)
  300. bindings = query.filter(
  301. sg_models.SecurityGroupPortBinding.port_id == port_id)
  302. for binding in bindings:
  303. context.session.delete(binding)
  304. @db_api.retry_if_session_inactive()
  305. def create_security_group_rule_bulk(self, context, security_group_rules):
  306. return self._create_bulk('security_group_rule', context,
  307. security_group_rules)
  308. @db_api.retry_if_session_inactive()
  309. def create_security_group_rule_bulk_native(self, context,
  310. security_group_rules):
  311. rules = security_group_rules['security_group_rules']
  312. scoped_session(context.session)
  313. security_group_id = self._validate_security_group_rules(
  314. context, security_group_rules)
  315. with db_api.CONTEXT_WRITER.using(context):
  316. self._check_for_duplicate_rules(context, security_group_id, rules)
  317. ret = []
  318. for rule_dict in rules:
  319. res_rule_dict = self._create_security_group_rule(
  320. context, rule_dict, validate=False)
  321. ret.append(res_rule_dict)
  322. for rdict in ret:
  323. registry.notify(
  324. resources.SECURITY_GROUP_RULE, events.AFTER_CREATE, self,
  325. context=context, security_group_rule=rdict)
  326. return ret
  327. @db_api.retry_if_session_inactive()
  328. def create_security_group_rule(self, context, security_group_rule):
  329. res = self._create_security_group_rule(context, security_group_rule)
  330. registry.notify(
  331. resources.SECURITY_GROUP_RULE, events.AFTER_CREATE, self,
  332. context=context, security_group_rule=res)
  333. return res
  334. def _create_security_group_rule(self, context, security_group_rule,
  335. validate=True):
  336. if validate:
  337. sg_id = self._validate_security_group_rule(context,
  338. security_group_rule)
  339. rule_dict = security_group_rule['security_group_rule']
  340. remote_ip_prefix = rule_dict.get('remote_ip_prefix')
  341. if remote_ip_prefix:
  342. remote_ip_prefix = utils.AuthenticIPNetwork(remote_ip_prefix)
  343. protocol = rule_dict.get('protocol')
  344. if protocol:
  345. # object expects strings only
  346. protocol = six.text_type(protocol)
  347. args = {
  348. 'id': (rule_dict.get('id') or uuidutils.generate_uuid()),
  349. 'project_id': rule_dict['tenant_id'],
  350. 'security_group_id': rule_dict['security_group_id'],
  351. 'direction': rule_dict['direction'],
  352. 'remote_group_id': rule_dict.get('remote_group_id'),
  353. 'ethertype': rule_dict['ethertype'],
  354. 'protocol': protocol,
  355. 'remote_ip_prefix': remote_ip_prefix,
  356. 'description': rule_dict.get('description'),
  357. }
  358. port_range_min = self._safe_int(rule_dict['port_range_min'])
  359. if port_range_min is not None:
  360. args['port_range_min'] = port_range_min
  361. port_range_max = self._safe_int(rule_dict['port_range_max'])
  362. if port_range_max is not None:
  363. args['port_range_max'] = port_range_max
  364. kwargs = {
  365. 'context': context,
  366. 'security_group_rule': args
  367. }
  368. self._registry_notify(resources.SECURITY_GROUP_RULE,
  369. events.BEFORE_CREATE,
  370. exc_cls=ext_sg.SecurityGroupConflict, **kwargs)
  371. with db_api.CONTEXT_WRITER.using(context):
  372. if validate:
  373. self._check_for_duplicate_rules(context, sg_id,
  374. [security_group_rule])
  375. sg_rule = sg_obj.SecurityGroupRule(context, **args)
  376. sg_rule.create()
  377. # fetch sg_rule from db to load the sg rules with sg model
  378. # otherwise a DetachedInstanceError can occur for model extensions
  379. sg_rule = sg_obj.SecurityGroupRule.get_object(context,
  380. id=sg_rule.id)
  381. res_rule_dict = self._make_security_group_rule_dict(sg_rule.db_obj)
  382. kwargs['security_group_rule'] = res_rule_dict
  383. self._registry_notify(
  384. resources.SECURITY_GROUP_RULE,
  385. events.PRECOMMIT_CREATE,
  386. exc_cls=ext_sg.SecurityGroupConflict, **kwargs)
  387. return res_rule_dict
  388. def _get_ip_proto_number(self, protocol):
  389. if protocol is None:
  390. return
  391. # According to bug 1381379, protocol is always set to string to avoid
  392. # problems with comparing int and string in PostgreSQL. Here this
  393. # string is converted to int to give an opportunity to use it as
  394. # before.
  395. if protocol in n_const.IP_PROTOCOL_NAME_ALIASES:
  396. protocol = n_const.IP_PROTOCOL_NAME_ALIASES[protocol]
  397. return int(constants.IP_PROTOCOL_MAP.get(protocol, protocol))
  398. def _get_ip_proto_name_and_num(self, protocol):
  399. if protocol is None:
  400. return
  401. protocol = str(protocol)
  402. if protocol in constants.IP_PROTOCOL_MAP:
  403. return [protocol, str(constants.IP_PROTOCOL_MAP.get(protocol))]
  404. elif protocol in n_const.IP_PROTOCOL_NUM_TO_NAME_MAP:
  405. return [n_const.IP_PROTOCOL_NUM_TO_NAME_MAP.get(protocol),
  406. protocol]
  407. return [protocol, protocol]
  408. def _safe_int(self, port_range):
  409. if port_range is None:
  410. return
  411. try:
  412. return int(port_range)
  413. except (ValueError, TypeError):
  414. msg = "port range must be an integer"
  415. raise n_exc.InvalidInput(error_message=msg)
  416. def _validate_port_range(self, rule):
  417. """Check that port_range is valid."""
  418. if rule['port_range_min'] is None and rule['port_range_max'] is None:
  419. return
  420. if not rule['protocol']:
  421. raise ext_sg.SecurityGroupProtocolRequiredWithPorts()
  422. ip_proto = self._get_ip_proto_number(rule['protocol'])
  423. # Not all firewall_driver support all these protocols,
  424. # but being strict here doesn't hurt.
  425. if (ip_proto in n_const.SG_PORT_PROTO_NUMS or
  426. ip_proto in n_const.SG_PORT_PROTO_NAMES):
  427. if rule['port_range_min'] == 0 or rule['port_range_max'] == 0:
  428. raise ext_sg.SecurityGroupInvalidPortValue(port=0)
  429. elif (rule['port_range_min'] is not None and
  430. rule['port_range_max'] is not None and
  431. rule['port_range_min'] <= rule['port_range_max']):
  432. # When min/max are the same it is just a single port
  433. pass
  434. else:
  435. raise ext_sg.SecurityGroupInvalidPortRange()
  436. elif ip_proto in [constants.PROTO_NUM_ICMP,
  437. constants.PROTO_NUM_IPV6_ICMP]:
  438. for attr, field in [('port_range_min', 'type'),
  439. ('port_range_max', 'code')]:
  440. if rule[attr] is not None and not (0 <= rule[attr] <= 255):
  441. raise ext_sg.SecurityGroupInvalidIcmpValue(
  442. field=field, attr=attr, value=rule[attr])
  443. if (rule['port_range_min'] is None and
  444. rule['port_range_max'] is not None):
  445. raise ext_sg.SecurityGroupMissingIcmpType(
  446. value=rule['port_range_max'])
  447. else:
  448. # Only the protocols above support ports, raise otherwise.
  449. if (rule['port_range_min'] is not None or
  450. rule['port_range_max'] is not None):
  451. port_protocols = (
  452. ', '.join(s.upper() for s in n_const.SG_PORT_PROTO_NAMES))
  453. raise ext_sg.SecurityGroupInvalidProtocolForPort(
  454. protocol=ip_proto, valid_port_protocols=port_protocols)
  455. def _validate_ethertype_and_protocol(self, rule):
  456. """Check if given ethertype and protocol are valid or not"""
  457. if rule['protocol'] in [constants.PROTO_NAME_IPV6_ENCAP,
  458. constants.PROTO_NAME_IPV6_FRAG,
  459. constants.PROTO_NAME_IPV6_ICMP,
  460. constants.PROTO_NAME_IPV6_ICMP_LEGACY,
  461. constants.PROTO_NAME_IPV6_NONXT,
  462. constants.PROTO_NAME_IPV6_OPTS,
  463. constants.PROTO_NAME_IPV6_ROUTE,
  464. str(constants.PROTO_NUM_IPV6_ENCAP),
  465. str(constants.PROTO_NUM_IPV6_FRAG),
  466. str(constants.PROTO_NUM_IPV6_ICMP),
  467. str(constants.PROTO_NUM_IPV6_NONXT),
  468. str(constants.PROTO_NUM_IPV6_OPTS),
  469. str(constants.PROTO_NUM_IPV6_ROUTE)]:
  470. if rule['ethertype'] == constants.IPv4:
  471. raise ext_sg.SecurityGroupEthertypeConflictWithProtocol(
  472. ethertype=rule['ethertype'], protocol=rule['protocol'])
  473. def _validate_single_tenant_and_group(self, security_group_rules):
  474. """Check that all rules belong to the same security group and tenant
  475. """
  476. sg_groups = set()
  477. tenants = set()
  478. for rule_dict in security_group_rules['security_group_rules']:
  479. rule = rule_dict['security_group_rule']
  480. sg_groups.add(rule['security_group_id'])
  481. if len(sg_groups) > 1:
  482. raise ext_sg.SecurityGroupNotSingleGroupRules()
  483. tenants.add(rule['tenant_id'])
  484. if len(tenants) > 1:
  485. raise ext_sg.SecurityGroupRulesNotSingleTenant()
  486. return sg_groups.pop()
  487. def _validate_security_group_rule(self, context, security_group_rule):
  488. rule = security_group_rule['security_group_rule']
  489. self._validate_port_range(rule)
  490. self._validate_ip_prefix(rule)
  491. self._validate_ethertype_and_protocol(rule)
  492. if rule['remote_ip_prefix'] and rule['remote_group_id']:
  493. raise ext_sg.SecurityGroupRemoteGroupAndRemoteIpPrefix()
  494. remote_group_id = rule['remote_group_id']
  495. # Check that remote_group_id exists for tenant
  496. if remote_group_id:
  497. self._check_security_group(context, remote_group_id,
  498. tenant_id=rule['tenant_id'])
  499. security_group_id = rule['security_group_id']
  500. # Confirm that the tenant has permission
  501. # to add rules to this security group.
  502. self._check_security_group(context, security_group_id,
  503. tenant_id=rule['tenant_id'])
  504. return security_group_id
  505. def _validate_security_group_rules(self, context, security_group_rules):
  506. sg_id = self._validate_single_tenant_and_group(security_group_rules)
  507. for rule in security_group_rules['security_group_rules']:
  508. self._validate_security_group_rule(context, rule)
  509. return sg_id
  510. def _make_security_group_rule_dict(self, security_group_rule, fields=None):
  511. res = {'id': security_group_rule['id'],
  512. 'tenant_id': security_group_rule['tenant_id'],
  513. 'security_group_id': security_group_rule['security_group_id'],
  514. 'ethertype': security_group_rule['ethertype'],
  515. 'direction': security_group_rule['direction'],
  516. 'protocol': security_group_rule['protocol'],
  517. 'port_range_min': security_group_rule['port_range_min'],
  518. 'port_range_max': security_group_rule['port_range_max'],
  519. 'remote_ip_prefix': security_group_rule['remote_ip_prefix'],
  520. 'remote_group_id': security_group_rule['remote_group_id']}
  521. resource_extend.apply_funcs(ext_sg.SECURITYGROUPRULES, res,
  522. security_group_rule)
  523. return db_utils.resource_fields(res, fields)
  524. def _make_security_group_rule_filter_dict(self, security_group_rule):
  525. sgr = security_group_rule['security_group_rule']
  526. res = {'tenant_id': [sgr['tenant_id']],
  527. 'security_group_id': [sgr['security_group_id']],
  528. 'direction': [sgr['direction']]}
  529. include_if_present = ['protocol', 'port_range_max', 'port_range_min',
  530. 'ethertype', 'remote_group_id']
  531. for key in include_if_present:
  532. value = sgr.get(key)
  533. if value:
  534. res[key] = [value]
  535. # protocol field will get corresponding name and number
  536. value = sgr.get('protocol')
  537. if value:
  538. res['protocol'] = self._get_ip_proto_name_and_num(value)
  539. return res
  540. def _rule_to_key(self, rule):
  541. def _normalize_rule_value(key, value):
  542. # This string is used as a placeholder for str(None), but shorter.
  543. none_char = '+'
  544. if key == 'remote_ip_prefix':
  545. all_address = ['0.0.0.0/0', '::/0', None]
  546. if value in all_address:
  547. return none_char
  548. elif value is None:
  549. return none_char
  550. elif key == 'protocol':
  551. return str(self._get_ip_proto_name_and_num(value))
  552. return str(value)
  553. comparison_keys = [
  554. 'direction',
  555. 'ethertype',
  556. 'port_range_max',
  557. 'port_range_min',
  558. 'protocol',
  559. 'remote_group_id',
  560. 'remote_ip_prefix',
  561. 'security_group_id'
  562. ]
  563. return '_'.join([_normalize_rule_value(x, rule.get(x))
  564. for x in comparison_keys])
  565. def _check_for_duplicate_rules(self, context, security_group_id,
  566. new_security_group_rules):
  567. # First up, check for any duplicates in the new rules.
  568. new_rules_set = set()
  569. for i in new_security_group_rules:
  570. rule_key = self._rule_to_key(i['security_group_rule'])
  571. if rule_key in new_rules_set:
  572. raise ext_sg.DuplicateSecurityGroupRuleInPost(rule=i)
  573. new_rules_set.add(rule_key)
  574. # Now, let's make sure none of the new rules conflict with
  575. # existing rules; note that we do *not* store the db rules
  576. # in the set, as we assume they were already checked,
  577. # when added.
  578. sg = self.get_security_group(context, security_group_id)
  579. if sg:
  580. for i in sg['security_group_rules']:
  581. rule_key = self._rule_to_key(i)
  582. if rule_key in new_rules_set:
  583. raise ext_sg.SecurityGroupRuleExists(rule_id=i.get('id'))
  584. def _validate_ip_prefix(self, rule):
  585. """Check that a valid cidr was specified as remote_ip_prefix
  586. No need to check that it is in fact an IP address as this is already
  587. validated by attribute validators.
  588. Check that rule ethertype is consistent with remote_ip_prefix ip type.
  589. Add mask to ip_prefix if absent (192.168.1.10 -> 192.168.1.10/32).
  590. """
  591. input_prefix = rule['remote_ip_prefix']
  592. if input_prefix:
  593. addr = netaddr.IPNetwork(input_prefix)
  594. # set input_prefix to always include the netmask:
  595. rule['remote_ip_prefix'] = str(addr)
  596. # check consistency of ethertype with addr version
  597. if rule['ethertype'] != "IPv%d" % (addr.version):
  598. raise ext_sg.SecurityGroupRuleParameterConflict(
  599. ethertype=rule['ethertype'], cidr=input_prefix)
  600. @db_api.retry_if_session_inactive()
  601. def get_security_group_rules(self, context, filters=None, fields=None,
  602. sorts=None, limit=None, marker=None,
  603. page_reverse=False):
  604. filters = filters or {}
  605. pager = base_obj.Pager(
  606. sorts=sorts, marker=marker, limit=limit, page_reverse=page_reverse)
  607. # NOTE(slaweq): use admin context here to be able to get all rules
  608. # which fits filters' criteria. Later in policy engine rules will be
  609. # filtered and only those which are allowed according to policy will
  610. # be returned
  611. rule_objs = sg_obj.SecurityGroupRule.get_objects(
  612. context_lib.get_admin_context(), _pager=pager,
  613. validate_filters=False, **filters
  614. )
  615. return [
  616. self._make_security_group_rule_dict(obj.db_obj, fields)
  617. for obj in rule_objs
  618. ]
  619. @db_api.retry_if_session_inactive()
  620. def get_security_group_rules_count(self, context, filters=None):
  621. filters = filters or {}
  622. return sg_obj.SecurityGroupRule.count(
  623. context, validate_filters=False, **filters)
  624. @db_api.retry_if_session_inactive()
  625. def get_security_group_rule(self, context, id, fields=None):
  626. # NOTE(slaweq): use admin context here to be able to get all rules
  627. # which fits filters' criteria. Later in policy engine rules will be
  628. # filtered and only those which are allowed according to policy will
  629. # be returned
  630. security_group_rule = self._get_security_group_rule(
  631. context_lib.get_admin_context(), id)
  632. return self._make_security_group_rule_dict(
  633. security_group_rule.db_obj, fields)
  634. def _get_security_group_rule(self, context, id):
  635. sgr = sg_obj.SecurityGroupRule.get_object(context, id=id)
  636. if sgr is None:
  637. raise ext_sg.SecurityGroupRuleNotFound(id=id)
  638. return sgr
  639. @db_api.retry_if_session_inactive()
  640. def delete_security_group_rule(self, context, id):
  641. kwargs = {
  642. 'context': context,
  643. 'security_group_rule_id': id
  644. }
  645. self._registry_notify(resources.SECURITY_GROUP_RULE,
  646. events.BEFORE_DELETE, id=id,
  647. exc_cls=ext_sg.SecurityGroupRuleInUse, **kwargs)
  648. with db_api.CONTEXT_WRITER.using(context):
  649. sgr = self._get_security_group_rule(context, id)
  650. kwargs['security_group_id'] = sgr['security_group_id']
  651. self._registry_notify(resources.SECURITY_GROUP_RULE,
  652. events.PRECOMMIT_DELETE,
  653. exc_cls=ext_sg.SecurityGroupRuleInUse, id=id,
  654. **kwargs)
  655. sgr.delete()
  656. registry.notify(
  657. resources.SECURITY_GROUP_RULE, events.AFTER_DELETE, self,
  658. **kwargs)
  659. @staticmethod
  660. @resource_extend.extends([port_def.COLLECTION_NAME])
  661. def _extend_port_dict_security_group(port_res, port_db):
  662. # Security group bindings will be retrieved from the SQLAlchemy
  663. # model. As they're loaded eagerly with ports because of the
  664. # joined load they will not cause an extra query.
  665. if isinstance(port_db, port_obj.Port):
  666. port_res[ext_sg.SECURITYGROUPS] = port_db.security_group_ids
  667. else:
  668. security_group_ids = [sec_group_mapping['security_group_id'] for
  669. sec_group_mapping in port_db.security_groups]
  670. port_res[ext_sg.SECURITYGROUPS] = security_group_ids
  671. return port_res
  672. def _process_port_create_security_group(self, context, port,
  673. security_group_ids):
  674. if validators.is_attr_set(security_group_ids):
  675. for security_group_id in security_group_ids:
  676. self._create_port_security_group_binding(context, port['id'],
  677. security_group_id)
  678. # Convert to list as a set might be passed here and
  679. # this has to be serialized
  680. port[ext_sg.SECURITYGROUPS] = (security_group_ids and
  681. list(security_group_ids) or [])
  682. def _get_default_sg_id(self, context, tenant_id):
  683. default_group = sg_obj.DefaultSecurityGroup.get_object(
  684. context,
  685. project_id=tenant_id,
  686. )
  687. if default_group:
  688. return default_group.security_group_id
  689. @registry.receives(resources.PORT, [events.BEFORE_CREATE,
  690. events.BEFORE_UPDATE])
  691. @registry.receives(resources.NETWORK, [events.BEFORE_CREATE])
  692. def _ensure_default_security_group_handler(self, resource, event, trigger,
  693. context, **kwargs):
  694. if event == events.BEFORE_UPDATE:
  695. tenant_id = kwargs['original_' + resource]['tenant_id']
  696. else:
  697. tenant_id = kwargs[resource]['tenant_id']
  698. if tenant_id:
  699. self._ensure_default_security_group(context, tenant_id)
  700. def _ensure_default_security_group(self, context, tenant_id):
  701. """Create a default security group if one doesn't exist.
  702. :returns: the default security group id for given tenant.
  703. """
  704. default_group_id = self._get_default_sg_id(context, tenant_id)
  705. if default_group_id:
  706. return default_group_id
  707. security_group = {
  708. 'security_group':
  709. {'name': 'default',
  710. 'tenant_id': tenant_id,
  711. 'description': _('Default security group')}
  712. }
  713. return self.create_security_group(context, security_group,
  714. default_sg=True)['id']
  715. def _get_security_groups_on_port(self, context, port):
  716. """Check that all security groups on port belong to tenant.
  717. :returns: all security groups IDs on port belonging to tenant.
  718. """
  719. port = port['port']
  720. if not validators.is_attr_set(port.get(ext_sg.SECURITYGROUPS)):
  721. return
  722. if port.get('device_owner') and net.is_port_trusted(port):
  723. return
  724. port_sg = port.get(ext_sg.SECURITYGROUPS, [])
  725. tenant_id = port.get('tenant_id')
  726. sg_objs = sg_obj.SecurityGroup.get_objects(context, id=port_sg)
  727. valid_groups = set(
  728. g.id for g in sg_objs
  729. if (not tenant_id or g.tenant_id == tenant_id or
  730. sg_obj.SecurityGroup.is_shared_with_tenant(
  731. context, g.id, tenant_id))
  732. )
  733. requested_groups = set(port_sg)
  734. port_sg_missing = requested_groups - valid_groups
  735. if port_sg_missing:
  736. raise ext_sg.SecurityGroupNotFound(id=', '.join(port_sg_missing))
  737. return list(requested_groups)
  738. def _ensure_default_security_group_on_port(self, context, port):
  739. # we don't apply security groups for dhcp, router
  740. port = port['port']
  741. if port.get('device_owner') and net.is_port_trusted(port):
  742. return
  743. port_sg = port.get(ext_sg.SECURITYGROUPS)
  744. if port_sg is None or not validators.is_attr_set(port_sg):
  745. port_project = port.get('tenant_id')
  746. default_sg = self._ensure_default_security_group(context,
  747. port_project)
  748. port[ext_sg.SECURITYGROUPS] = [default_sg]
  749. def _check_update_deletes_security_groups(self, port):
  750. """Return True if port has as a security group and it's value
  751. is either [] or not is_attr_set, otherwise return False
  752. """
  753. if (ext_sg.SECURITYGROUPS in port['port'] and
  754. not (validators.is_attr_set(
  755. port['port'][ext_sg.SECURITYGROUPS]) and
  756. port['port'][ext_sg.SECURITYGROUPS] != [])):
  757. return True
  758. return False
  759. def _check_update_has_security_groups(self, port):
  760. """Return True if port has security_groups attribute set and
  761. its not empty, or False otherwise.
  762. This method is called both for port create and port update.
  763. """
  764. if (ext_sg.SECURITYGROUPS in port['port'] and
  765. (validators.is_attr_set(port['port'][ext_sg.SECURITYGROUPS]) and
  766. port['port'][ext_sg.SECURITYGROUPS] != [])):
  767. return True
  768. return False
  769. def update_security_group_on_port(self, context, id, port,
  770. original_port, updated_port):
  771. """Update security groups on port.
  772. This method returns a flag which indicates request notification
  773. is required and does not perform notification itself.
  774. It is because another changes for the port may require notification.
  775. """
  776. need_notify = False
  777. port_updates = port['port']
  778. if (ext_sg.SECURITYGROUPS in port_updates and
  779. not helpers.compare_elements(
  780. original_port.get(ext_sg.SECURITYGROUPS),
  781. port_updates[ext_sg.SECURITYGROUPS])):
  782. # delete the port binding and read it with the new rules
  783. port_updates[ext_sg.SECURITYGROUPS] = (
  784. self._get_security_groups_on_port(context, port))
  785. self._delete_port_security_group_bindings(context, id)
  786. self._process_port_create_security_group(
  787. context,
  788. updated_port,
  789. port_updates[ext_sg.SECURITYGROUPS])
  790. need_notify = True
  791. else:
  792. updated_port[ext_sg.SECURITYGROUPS] = (
  793. original_port[ext_sg.SECURITYGROUPS])
  794. return need_notify