Debian Codegraph @

neutron_fwaas/services/firewall/fwaas_plugin_v2.py

raw symbols SCIP
1 # 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
15 from neutron.db import servicetype_db as st_db
16 from neutron import service
17 from neutron.services import provider_configuration as provider_conf
18 from neutron.services import service_base
19 from neutron_lib.api.definitions import firewall_v2
20 from neutron_lib.api.definitions import portbindings as pb_def
21 from neutron_lib.api import validators
22 from neutron_lib.callbacks import events
23 from neutron_lib.callbacks import registry
24 from neutron_lib.callbacks import resources
25 from neutron_lib import constants as nl_constants
26 from neutron_lib.db import api as db_api
27 from neutron_lib.exceptions import firewall_v2 as f_exc
28 from neutron_lib.plugins import directory
29 from oslo_log import helpers as log_helpers
30 from oslo_log import log as logging
31
32 from neutron_fwaas.common import exceptions
33 from neutron_fwaas.common import fwaas_constants
34 from neutron_fwaas.extensions.firewall_v2 import Firewallv2PluginBase
35 from neutron_fwaas.services.firewall.service_drivers import driver_api
36
37 LOG = logging.getLogger(__name__)
38
39
40 @registry.has_registry_receivers
41 class FirewallPluginV2(Firewallv2PluginBase):
42 """Firewall v2 Neutron service plugin class"""
43
44 supported_extension_aliases = [firewall_v2.ALIAS]
45 path_prefix = firewall_v2.API_PREFIX
46
47 def __init__(self):
48 super().__init__()
49 """Do the initialization for the firewall service plugin here."""
50 # Initialize the Firewall v2 service plugin
51 service_type_manager = st_db.ServiceTypeManager.get_instance()
52 service_type_manager.add_provider_configuration(
53 fwaas_constants.FIREWALL_V2,
54 provider_conf.ProviderConfiguration('neutron_fwaas',
55 fwaas_constants.FIREWALL_V2))
56
57 # Load the default driver
58 drivers, default_provider = service_base.load_drivers(
59 fwaas_constants.FIREWALL_V2, self)
60 LOG.info("Firewall v2 Service Plugin using Service Driver: %s",
61 default_provider)
62
63 if len(drivers) > 1:
64 LOG.warning("Multiple drivers configured for Firewall v2, "
65 "although running multiple drivers in parallel is "
66 "not yet supported")
67
68 self.driver_name = default_provider
69 self.driver = drivers[default_provider]
70
71 # start rpc listener if driver required
72 if isinstance(self.driver, driver_api.FirewallDriverRPCMixin):
73 rpc_worker = service.RpcWorker([self], worker_process_count=0)
74 self.add_worker(rpc_worker)
75
76 def start_rpc_listeners(self):
77 return self.driver.start_rpc_listener()
78
79 @property
80 def _core_plugin(self):
81 return directory.get_plugin()
82
83 def _ensure_update_firewall_group(self, context, fwg_id):
84 """Checks if the firewall group can be updated
85
86 Raises FirewallGroupInPendingState if the firewall group is in pending
87 state.
88 :param context: neutron context
89 :param fwg_id: firewall group ID to check
90 :return: Firewall group dict
91 """
92 fwg = self.get_firewall_group(context, fwg_id)
93 if fwg['status'] in [nl_constants.PENDING_CREATE,
94 nl_constants.PENDING_UPDATE,
95 nl_constants.PENDING_DELETE]:
96 raise f_exc.FirewallGroupInPendingState(
97 firewall_id=fwg_id, pending_state=fwg['status'])
98 return fwg
99
100 def _ensure_update_firewall_policy(self, context, fwp_id):
101 """Checks if the firewall policy can be updated
102
103 Fetch firewall group associated to the policy and checks if they can be
104 updated.
105 :param context: neutron context
106 :param fwp_id: firewall policy ID to check
107 """
108 fwp = self.get_firewall_policy(context, fwp_id)
109 ing_fwg_ids, eg_fwg_ids = self._get_fwgs_with_policy(context, fwp)
110 for fwg_id in list(set(ing_fwg_ids + eg_fwg_ids)):
111 self._ensure_update_firewall_group(context, fwg_id)
112
113 def _ensure_update_firewall_rule(self, context, fwr_id):
114 """Checks if the firewall rule can be updated
115
116 Fetch firewall policy associated to the rule and checks if they can be
117 updated.
118 :param context: neutron context
119 :param fwr_id: firewall policy ID to check
120 """
121 fwr = self.get_firewall_rule(context, fwr_id)
122 fwp_ids = self._get_policies_with_rule(context, fwr)
123 for fwp_id in fwp_ids:
124 self._ensure_update_firewall_policy(context, fwp_id)
125
126 def _validate_firewall_policies_for_firewall_group(self, context, fwg):
127 """Validate firewall group and policy owner
128
129 Check if the firewall policy is not shared, it have the same project
130 owner than the friewall group.
131 :param context: neutron context
132 :param fwg: firewall group to validate
133 """
134 for policy_type in ['ingress_firewall_policy_id',
135 'egress_firewall_policy_id']:
136 if fwg.get(policy_type):
137 fwp = self.get_firewall_policy(context, fwg[policy_type])
138 if fwg['tenant_id'] != fwp['tenant_id'] and not fwp['shared']:
139 raise f_exc.FirewallPolicyConflict(
140 firewall_policy_id=fwg[policy_type])
141
142 def _validate_ports_for_firewall_group(self, context, tenant_id,
143 fwg_ports):
144 """Validate firewall group associated ports
145
146 Check if the firewall group associated ports have the same project
147 owner and is router interface type or a compute layer 2 and supported
148 by the firewall driver
149 :param context: neutron context
150 :param tenant_id: firewall group project ID
151 :param fwg_ports: firewall group associated ports
152 """
153 # TODO(sridar): elevated context and do we want to use public ?
154 for port_id in fwg_ports:
155 port = self._core_plugin.get_port(context, port_id)
156 device_owner = port.get('device_owner', '')
157 if device_owner in nl_constants.ROUTER_INTERFACE_OWNERS:
158 if not self.driver.is_supported_l3_port(port):
159 raise exceptions.FirewallGroupPortNotSupported(
160 driver_name=self.driver_name, port_id=port_id)
161 elif device_owner.startswith(
162 nl_constants.DEVICE_OWNER_COMPUTE_PREFIX):
163 if not self._is_supported_l2_port(context, port_id):
164 raise exceptions.FirewallGroupPortNotSupported(
165 driver_name=self.driver_name, port_id=port_id)
166 else:
167 raise f_exc.FirewallGroupPortInvalid(port_id=port_id)
168
169 def _is_supported_l2_port(self, context, port_id):
170 """Whether this l2 port is supported"""
171
172 # Re-fetch to get up-to-date data from db
173 port = self._core_plugin.get_port(context, id=port_id)
174
175 # Skip port binding is unbound or failed
176 if port[pb_def.VIF_TYPE] in [pb_def.VIF_TYPE_UNBOUND,
177 pb_def.VIF_TYPE_BINDING_FAILED]:
178 return False
179
180 return self.driver.is_supported_l2_port(port)
181
182 def _validate_if_firewall_group_on_ports(self, context, firewall_group,
183 id=None):
184 """Validate if ports are not associated with any firewall_group.
185
186 If any of the ports in the list is already associated with
187 a firewall group, raise an exception else just return.
188 :param context: neutron context
189 :param fwg: firewall group to validate
190 """
191 if 'ports' not in firewall_group or not firewall_group['ports']:
192 return
193
194 filters = {
195 'tenant_id': [firewall_group['tenant_id']],
196 'ports': firewall_group['ports'],
197 }
198 ports_in_use = set()
199 for fwg in self.get_firewall_groups(context, filters=filters):
200 if id is not None and fwg['id'] == id:
201 continue
202 ports_in_use |= set(fwg.get('ports', [])) & \
203 set(firewall_group['ports'])
204 if ports_in_use:
205 raise f_exc.FirewallGroupPortInUse(port_ids=list(ports_in_use))
206
207 def _get_fwgs_with_policy(self, context, firewall_policy):
208 """List firewall group IDs which use a firewall policy
209
210 List all firewall group IDs which have the given firewall policy as
211 ingress or egress.
212 :param context: neutron context
213 :param firewall_policy: firewall policy to filter
214 """
215 filters = {
216 'tenant_id': [firewall_policy['tenant_id']],
217 'ingress_firewall_policy_id': [firewall_policy['id']],
218 }
219 ingress_fwp_ids = [fwg['id']
220 for fwg in self.get_firewall_groups(
221 context, filters=filters)]
222
223 filters = {
224 'tenant_id': [firewall_policy['tenant_id']],
225 'egress_firewall_policy_id': [firewall_policy['id']],
226 }
227 egress_fwp_ids = [fwg['id']
228 for fwg in self.get_firewall_groups(
229 context, filters=filters)]
230
231 return ingress_fwp_ids, egress_fwp_ids
232
233 def _get_policies_with_rule(self, context, firewall_rule):
234 filters = {
235 'tenant_id': [firewall_rule['tenant_id']],
236 'firewall_rules': [firewall_rule['id']],
237 }
238 return [fwp['id'] for fwp in self.get_firewall_policies(
239 context, filters=filters)]
240
241 def _validate_insert_remove_rule_request(self, rule_info):
242 """Validate rule_info dict
243
244 Check that all mandatory fields are present, otherwise raise
245 proper exception.
246 """
247 if not rule_info or 'firewall_rule_id' not in rule_info:
248 raise f_exc.FirewallRuleInfoMissing()
249 # Validator doesn't return anything if the check passes
250 if validators.validate_uuid(rule_info['firewall_rule_id']):
251 raise f_exc.FirewallRuleNotFound(
252 firewall_rule_id=rule_info['firewall_rule_id'])
253
254 @registry.receives(resources.PORT, [events.AFTER_UPDATE])
255 def handle_update_port(self, resource, event, trigger, payload):
256 context = payload.context
257 original_port = payload.states[0]
258 updated_port = payload.states[1]
259 if not updated_port['device_owner'].startswith(
260 nl_constants.DEVICE_OWNER_COMPUTE_PREFIX):
261 return
262
263 if (original_port[pb_def.VIF_TYPE] != pb_def.VIF_TYPE_UNBOUND):
264 # Checking newly vm port binding allows us to avoid call to DB
265 # when a port update_event like restart, setting name, etc...
266 # Moreover, that will help us in case of tenant admin wants to
267 # only attach security group to vm port.
268 return
269
270 port_id = updated_port['id']
271 # Check port is supported by firewall driver
272 if not self._is_supported_l2_port(context, port_id):
273 return
274
275 project_id = updated_port['project_id']
276 fwgs = self.get_firewall_groups(
277 context,
278 filters={
279 'tenant_id': [project_id],
280 'name': [fwaas_constants.DEFAULT_FWG],
281 },
282 fields=['id', 'ports'],
283 )
284 if len(fwgs) != 1:
285 # Cannot found default Firewall Group, abandon
286 LOG.warning("Cannot found default firewall group of project %s",
287 project_id)
288 return
289 default_fwg = fwgs[0]
290
291 # Add default firewall group to the port
292 port_ids = default_fwg.get('ports', []) + [port_id]
293 try:
294 self.update_firewall_group(context, default_fwg['id'],
295 {'firewall_group': {'ports': port_ids}})
296 except f_exc.FirewallGroupPortInUse:
297 LOG.warning("Port %s has been already associated with default "
298 "firewall group %s and skip association", port_id,
299 default_fwg['id'])
300
301 # Firewall Group
302 @log_helpers.log_method_call
303 @db_api.CONTEXT_WRITER
304 def create_firewall_group(self, context, firewall_group):
305 firewall_group = firewall_group['firewall_group']
306 ports = firewall_group.get('ports', [])
307
308 self._validate_firewall_policies_for_firewall_group(context,
309 firewall_group)
310 # Validate ports owner type and project
311 self._validate_ports_for_firewall_group(context,
312 firewall_group['tenant_id'],
313 ports)
314
315 self._validate_if_firewall_group_on_ports(context, firewall_group)
316
317 return self.driver.create_firewall_group(context, firewall_group)
318
319 @log_helpers.log_method_call
320 @db_api.CONTEXT_WRITER
321 def delete_firewall_group(self, context, id):
322 # if no such group exists -> don't raise an exception according to
323 # 80fe2ba1, return None
324 try:
325 fwg = self.get_firewall_group(context, id)
326 except f_exc.FirewallGroupNotFound:
327 return
328
329 if fwg['ports']:
330 raise f_exc.FirewallGroupInUse(firewall_id=id)
331
332 self.driver.delete_firewall_group(context, id)
333
334 @log_helpers.log_method_call
335 @db_api.CONTEXT_READER
336 def get_firewall_group(self, context, id, fields=None):
337 return self.driver.get_firewall_group(context, id, fields=fields)
338
339 @log_helpers.log_method_call
340 @db_api.CONTEXT_READER
341 def get_firewall_groups(self, context, filters=None, fields=None):
342 return self.driver.get_firewall_groups(context, filters, fields)
343
344 @log_helpers.log_method_call
345 def get_firewall_groups_count(self, context, filters=None):
346 filters = filters or {}
347 return len(self.get_firewall_groups(context=context, filters=filters))
348
349 @log_helpers.log_method_call
350 @db_api.CONTEXT_WRITER
351 def update_firewall_group(self, context, id, firewall_group):
352 firewall_group = firewall_group['firewall_group']
353 ports = firewall_group.get('ports', [])
354
355 old_firewall_group = self._ensure_update_firewall_group(context, id)
356 firewall_group['tenant_id'] = old_firewall_group['tenant_id']
357
358 self._validate_firewall_policies_for_firewall_group(context,
359 firewall_group)
360 # Validate ports owner type and project
361 self._validate_ports_for_firewall_group(context,
362 firewall_group['tenant_id'],
363 ports)
364 self._validate_if_firewall_group_on_ports(context, firewall_group,
365 id=id)
366
367 return self.driver.update_firewall_group(context, id, firewall_group)
368
369 # Firewall Policy
370 @log_helpers.log_method_call
371 @db_api.CONTEXT_WRITER
372 def create_firewall_policy(self, context, firewall_policy):
373 firewall_policy = firewall_policy['firewall_policy']
374 return self.driver.create_firewall_policy(context, firewall_policy)
375
376 @log_helpers.log_method_call
377 @db_api.CONTEXT_WRITER
378 def delete_firewall_policy(self, context, id):
379 self.driver.delete_firewall_policy(context, id)
380
381 @log_helpers.log_method_call
382 @db_api.CONTEXT_READER
383 def get_firewall_policy(self, context, id, fields=None):
384 return self.driver.get_firewall_policy(context, id, fields)
385
386 @log_helpers.log_method_call
387 @db_api.CONTEXT_READER
388 def get_firewall_policies(self, context, filters=None, fields=None):
389 return self.driver.get_firewall_policies(context, filters, fields)
390
391 @log_helpers.log_method_call
392 @db_api.CONTEXT_WRITER
393 def update_firewall_policy(self, context, id, firewall_policy):
394 firewall_policy = firewall_policy['firewall_policy']
395 self._ensure_update_firewall_policy(context, id)
396 return self.driver.update_firewall_policy(context, id, firewall_policy)
397
398 # Firewall Rule
399 @log_helpers.log_method_call
400 @db_api.CONTEXT_WRITER
401 def create_firewall_rule(self, context, firewall_rule):
402 firewall_rule = firewall_rule['firewall_rule']
403 return self.driver.create_firewall_rule(context, firewall_rule)
404
405 @log_helpers.log_method_call
406 @db_api.CONTEXT_WRITER
407 def delete_firewall_rule(self, context, id):
408 self.driver.delete_firewall_rule(context, id)
409
410 @log_helpers.log_method_call
411 @db_api.CONTEXT_READER
412 def get_firewall_rule(self, context, id, fields=None):
413 return self.driver.get_firewall_rule(context, id, fields)
414
415 @log_helpers.log_method_call
416 @db_api.CONTEXT_READER
417 def get_firewall_rules(self, context, filters=None, fields=None):
418 return self.driver.get_firewall_rules(context, filters, fields)
419
420 @log_helpers.log_method_call
421 @db_api.CONTEXT_WRITER
422 def update_firewall_rule(self, context, id, firewall_rule):
423 firewall_rule = firewall_rule['firewall_rule']
424 self._ensure_update_firewall_rule(context, id)
425 return self.driver.update_firewall_rule(context, id, firewall_rule)
426
427 @log_helpers.log_method_call
428 @db_api.CONTEXT_WRITER
429 def insert_rule(self, context, policy_id, rule_info):
430 self._ensure_update_firewall_policy(context, policy_id)
431 self._validate_insert_remove_rule_request(rule_info)
432 return self.driver.insert_rule(context, policy_id, rule_info)
433
434 @log_helpers.log_method_call
435 @db_api.CONTEXT_WRITER
436 def remove_rule(self, context, policy_id, rule_info):
437 self._ensure_update_firewall_policy(context, policy_id)
438 self._validate_insert_remove_rule_request(rule_info)
439 return self.driver.remove_rule(context, policy_id, rule_info)