Debian Codegraph @

neutron_fwaas/services/logapi/agents/drivers/iptables/log.py

raw symbols SCIP
1 # Copyright (c) 2018 Fujitsu Limited.
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 from collections import defaultdict
17 import signal
18 import uuid
19
20 from neutron.agent.linux import utils
21 from neutron.services.logapi.agent import log_extension as log_ext
22 from neutron_lib import constants
23 from neutron_lib.services.logapi import constants as log_const
24 from oslo_config import cfg
25 from oslo_log import formatters
26 from oslo_log import handlers
27 from oslo_log import log as logging
28
29 from neutron_fwaas.privileged.netfilter_log import libnetfilter_log as libnflog
30
31 LOG = logging.getLogger(__name__)
32
33 UINT64_BITMASK = (1 << 64) - 1
34
35 MAX_INTF_NAME_LEN = 14
36 INTERNAL_DEV_PREFIX = 'qr-'
37 SNAT_INT_DEV_PREFIX = 'sg-'
38 ROUTER_2_FIP_DEV_PREFIX = 'rfp-'
39
40 IPTABLES_DIRECTION_DEVICE = {
41 constants.INGRESS_DIRECTION: 'i',
42 constants.EGRESS_DIRECTION: 'o'
43 }
44
45
46 def setup_logging():
47
48 log_file = cfg.CONF.network_log.local_output_log_base
49 if log_file:
50 from logging import handlers as watch_handler
51 log_file_handler = watch_handler.WatchedFileHandler(log_file)
52 log_file_handler.setLevel(
53 logging.DEBUG if cfg.CONF.debug else logging.INFO)
54 LOG.logger.addHandler(log_file_handler)
55 log_file_handler.setFormatter(
56 formatters.ContextFormatter(
57 fmt=cfg.CONF.logging_default_format_string,
58 datefmt=cfg.CONF.log_date_format))
59
60 # Prevent propagating flow logs into neutron_l3_agent's logs
61 LOG.logger.propagate = False
62
63 elif cfg.CONF.use_journal:
64 journal_handler = handlers.OSJournalHandler()
65 LOG.logger.addHandler(journal_handler)
66 else:
67 syslog_handler = handlers.OSSysLogHandler()
68 LOG.logger.addHandler(syslog_handler)
69
70
71 class LogPrefix:
72 """LogPrefix could be used as prefix in NFLOG rules
73 Each of a couple (port_id, event) has its own LogPrefix object
74 """
75
76 def __init__(self, port_id, event, project_id):
77 self.id = self._generate_prefix_id()
78 self.port_id = port_id
79 self.action = event
80 # A list of log objects that referenced to this prefix
81 self.log_object_refs = set()
82 self.project_id = project_id
83
84 def __eq__(self, other):
85 return (self.id == other.id and
86 self.action == other.action and
87 self.port_id == other.port_id)
88
89 def __hash__(self):
90 return hash(self.id)
91
92 def _generate_prefix_id(self):
93 return uuid.uuid4().int & UINT64_BITMASK
94
95 def add_log_obj_ref(self, log_id):
96 self.log_object_refs.add(log_id)
97
98 def remove_log_obj_ref(self, log_id):
99 self.log_object_refs.discard(log_id)
100
101 @property
102 def is_empty(self):
103 return not self.log_object_refs
104
105
106 class FWGPortLog:
107 """A firewall group port log per log_object"""
108
109 def __init__(self, port_id, log_info):
110 self.port_id = port_id
111 self.log_id = log_info['id']
112 self.project_id = log_info['project_id']
113 self.event = log_info['event']
114
115
116 class IptablesLoggingDriver(log_ext.LoggingDriver):
117
118 SUPPORTED_LOGGING_TYPES = ['firewall_group']
119
120 def __init__(self, agent_api):
121 self.agent_api = agent_api
122 self.conf = cfg.CONF
123 self.rate_limit = self.conf.network_log.rate_limit
124 if self.rate_limit:
125 self.burst_limit = self.conf.network_log.burst_limit
126 self.ipt_mgr_list = defaultdict(dict)
127 # A list of fwg port logs that are being logged
128 self.fwg_port_logs = defaultdict(set)
129 # A list of prefixes that are being used in iptables
130 self.prefixes_table = {}
131 self.cleanup_table = defaultdict(set)
132 # Handle NFLOG processing
133 self.nflog_proc_map = {}
134 # A list of unused ports
135 self.unused_port_ids = set()
136
137 def initialize(self, resource_rpc, **kwargs):
138 self.resource_rpc = resource_rpc
139 setup_logging()
140 self.log_app = libnflog.NFLogApp()
141 self.log_app.register_packet_handler(self.log_packet)
142 self.log_app.start()
143
144 def log_packet(self, ev):
145 prefix = ev['prefix']
146 pkt = ev['msg']
147 prefix_entry = self._get_prefix_by_id(prefix)
148 if prefix_entry:
149 logs_id = [str(id) for id in prefix_entry.log_object_refs]
150 LOG.info("action=%s, project_id=%s, log_resource_ids=%s, port=%s, "
151 "pkt=%s", prefix_entry.action,
152 prefix_entry.project_id, logs_id,
153 prefix_entry.port_id, pkt)
154 else:
155 LOG.warning("Unknown cookie packet_in pkt=%s", pkt)
156 return 0
157
158 def _get_prefix(self, port_id, action):
159 if port_id in self.prefixes_table:
160 for prefix in self.prefixes_table[port_id]:
161 if prefix.action == action:
162 return prefix
163 return None
164
165 def _get_prefix_by_id(self, prefix_id):
166 for port, prefixes in self.prefixes_table.items():
167 for prefix in prefixes:
168 if str(prefix.id) == str(prefix_id):
169 return prefix
170 return None
171
172 def _add_to_cleanup(self, port_id, prefix_id):
173 if port_id not in self.cleanup_table:
174 self.cleanup_table[port_id] = set()
175 self.cleanup_table[port_id].add(prefix_id)
176
177 def _add_to_prefixes_table(self, port_id, prefix):
178 if port_id not in self.prefixes_table:
179 self.prefixes_table[port_id] = []
180 self.prefixes_table[port_id].append(prefix)
181
182 def _cleanup_nflog_process(self, router_info):
183 LOG.debug("Delete router_info %s", router_info)
184 if router_info in self.nflog_proc_map:
185 pid = self.nflog_proc_map[router_info]
186 try:
187 # A process started by a root helper will be running as
188 # root and need to be killed via the same helper.
189 LOG.debug('Trying to kill NFLOG process %d', pid)
190 utils.kill_process(pid, signal.SIGKILL, run_as_root=True)
191 del self.nflog_proc_map[router_info]
192 except Exception:
193 LOG.exception(
194 'An error occurred while killing process %d', pid)
195
196 def _cleanup_prefix_by_router(self, router_id):
197
198 ipt_mgr_per_port = set()
199 for port_id in self.ipt_mgr_list[router_id]:
200 ipt_mgr = self.ipt_mgr_list[router_id][port_id]
201 ipt_mgr_per_port.add(ipt_mgr)
202 # Cleanup prefix
203 if port_id in self.prefixes_table:
204 for prefix in self.prefixes_table[port_id]:
205 self._add_to_cleanup(port_id, prefix.id)
206 del self.prefixes_table[port_id]
207 self.unused_port_ids.add(port_id)
208 return ipt_mgr_per_port
209
210 def _cleanup_unused_ipt_mgrs(self):
211
212 need_cleanup = set()
213 for port_id in self.unused_port_ids:
214 for router_id in self.ipt_mgr_list:
215 if port_id in self.ipt_mgr_list[router_id]:
216 del self.ipt_mgr_list[router_id][port_id]
217 if not self.ipt_mgr_list[router_id]:
218 need_cleanup.add(router_id)
219
220 for router_id in need_cleanup:
221 del self.ipt_mgr_list[router_id]
222
223 self.unused_port_ids.clear()
224
225 def start_logging(self, context, **kwargs):
226 LOG.debug("Start logging: %s", str(kwargs))
227
228 for resource_type in self.SUPPORTED_LOGGING_TYPES:
229 router_info = kwargs.get('router_info')
230 if router_info:
231 # Handle router updated or L3 agent restart
232 router_id = router_info.router_id
233 internal_ports = router_info.internal_ports
234 self._create_firewall_group_log(context, resource_type,
235 ports=internal_ports,
236 router_id=router_id)
237
238 # Start libnetfilter_log after router starting up
239 pid = libnflog.run_nflog(router_info.ns_name)
240 LOG.debug("NFLOG process ID %s for router %s has started",
241 pid, router_info.router_id)
242 self.nflog_proc_map[router_id] = pid
243 else:
244 # Handle the log request
245 self._create_firewall_group_log(context, resource_type,
246 **kwargs)
247
248 def stop_logging(self, context, **kwargs):
249 LOG.debug("Stop logging: %s", str(kwargs))
250
251 # Delete router
252 router_info = kwargs.get('router_info')
253 if router_info:
254 self._cleanup_nflog_process(router_info)
255
256 if kwargs.get('log_resources'):
257 # Handle incoming log request
258 self._delete_firewall_group_log(context, **kwargs)
259
260 def _create_firewall_group_log(self, context, resource_type, **kwargs):
261 ports = kwargs.get('ports')
262 log_resources = kwargs.get('log_resources')
263 applied_ipt_mgrs = set()
264 logs_info = []
265
266 port_ids = []
267 # Get log objects from database via RPC
268 if ports:
269 port_ids = [port['id'] for port in ports]
270 logs_info = self.resource_rpc. \
271 get_sg_log_info_for_port(context, resource_type,
272 port_id=port_ids)
273 elif log_resources:
274 logs_info = self.resource_rpc.\
275 get_sg_log_info_for_log_resources(context, resource_type,
276 log_resources=log_resources)
277 # Handle logs_info
278 for log_info in logs_info:
279 log_id = log_info['id']
280 old_fwg_port_logs = self.fwg_port_logs.get(log_id, [])
281 new_ports_log = log_info.get('ports_log')
282 self.fwg_port_logs[log_id] = set()
283 for port in new_ports_log:
284 self._add_fwg_port_log(log_id, port, log_info)
285
286 for port in old_fwg_port_logs:
287 if port.port_id not in new_ports_log:
288 # Remove port not bound by log_id
289 self._cleanup_prefixes_table(port.port_id, log_id)
290
291 for fwg_port_log in self.fwg_port_logs[log_id]:
292 self._setup_chains(applied_ipt_mgrs, fwg_port_log)
293
294 router_id = kwargs.get("router_id")
295 if router_id:
296 if not port_ids:
297 ipt_mgrs = self._cleanup_prefix_by_router(router_id)
298 applied_ipt_mgrs.update(ipt_mgrs)
299
300 for port_id in port_ids:
301 try:
302 ipt_mgr = self.ipt_mgr_list[router_id][port_id]
303 applied_ipt_mgrs.add(ipt_mgr)
304 except KeyError:
305 pass
306
307 # Clean up NFLOG rules
308 self._cleanup_nflog_rules(applied_ipt_mgrs)
309
310 # Apply NFLOG rules into iptables managers
311 for ipt_mgr in applied_ipt_mgrs:
312 LOG.debug('Apply NFLOG rules in namespace %s', ipt_mgr.namespace)
313 ipt_mgr.defer_apply_off()
314
315 # Clean up unused iptables managers from ports
316 self._cleanup_unused_ipt_mgrs()
317
318 def _cleanup_prefixes_table(self, port_id, log_id):
319
320 # Each a port has at most 2 prefix
321 for index in [1, 0]:
322 try:
323 prefix = self.prefixes_table[port_id][index]
324 prefix.remove_log_obj_ref(log_id)
325 if prefix.is_empty:
326 self._add_to_cleanup(port_id, prefix.id)
327 self.prefixes_table[port_id].remove(prefix)
328 except Exception:
329 pass
330
331 if port_id in self.prefixes_table:
332 if not self.prefixes_table[port_id]:
333 del self.prefixes_table[port_id]
334 self.unused_port_ids.add(port_id)
335
336 def _cleanup_nflog_rules(self, applied_ipt_mgrs):
337 for port_id, prefix_ids in self.cleanup_table.items():
338 ipt_mgr = self._get_ipt_mgr_by_port(port_id)
339 for prefix_id in prefix_ids:
340 self._clear_rules_from_tag_v4v6(ipt_mgr, tag=prefix_id)
341 applied_ipt_mgrs.add(ipt_mgr)
342 self.cleanup_table.clear()
343
344 def _delete_firewall_group_log(self, context, **kwargs):
345 log_resources = kwargs.get('log_resources')
346 applied_ipt_mgrs = set()
347
348 for log_resource in log_resources:
349 log_id = log_resource.get('id')
350 fwg_port_logs = self.fwg_port_logs[log_id]
351 for port in fwg_port_logs:
352 self._cleanup_prefixes_table(port.port_id, log_id)
353 del self.fwg_port_logs[log_id]
354
355 # Clean NFLOG rules:
356 self._cleanup_nflog_rules(applied_ipt_mgrs)
357
358 # Apply NFLOG rules into iptables managers
359 for ipt_mgr in applied_ipt_mgrs:
360 ipt_mgr.defer_apply_off()
361
362 # Clean up unused iptables managers
363 self._cleanup_unused_ipt_mgrs()
364
365 def _get_if_prefix(self, agent_mode, router):
366 """Get the if prefix from router"""
367 if not router.router.get('distributed'):
368 return INTERNAL_DEV_PREFIX
369
370 if agent_mode == constants.L3_AGENT_MODE_DVR_SNAT:
371 return SNAT_INT_DEV_PREFIX
372
373 if router.rtr_fip_connect:
374 return ROUTER_2_FIP_DEV_PREFIX
375
376 def _get_intf_name(self, port_id):
377 agent_mode = self.conf.agent_mode
378 router = self.agent_api.get_router_hosting_port(port_id)
379 if_prefix = self._get_if_prefix(agent_mode, router)
380 return (if_prefix + port_id)[:constants.LINUX_DEV_LEN]
381
382 def _get_ipt_mgr_by_port(self, port_id):
383
384 router = self.agent_api.get_router_hosting_port(port_id)
385 if router:
386 try:
387 ipt_mgr = self.ipt_mgr_list[router.router_id][port_id]
388 return ipt_mgr
389 except KeyError:
390 pass
391
392 ipt_mgr = router.iptables_manager
393 self.ipt_mgr_list[router.router_id][port_id] = ipt_mgr
394 return ipt_mgr
395
396 for router_id in self.ipt_mgr_list:
397 if port_id in self.ipt_mgr_list[router_id]:
398 return self.ipt_mgr_list[router_id][port_id]
399
400 def _setup_chains(self, applied_ipt_mgrs, fwg_port_log):
401 # Add NFLOG rules by log event
402 event = fwg_port_log.event
403 if event in [log_const.ACCEPT_EVENT, log_const.ALL_EVENT]:
404 self._add_nflog_rules_accepted(applied_ipt_mgrs, fwg_port_log)
405 if event in [log_const.DROP_EVENT, log_const.ALL_EVENT]:
406 self._add_log_rules_dropped(applied_ipt_mgrs, fwg_port_log)
407
408 def _add_nflog_rules_accepted(self, applied_ipt_mgrs, fwg_port_log):
409 """Add NFLOG rules to the accepted chain into iptables"""
410 action = log_const.ACCEPT_EVENT
411 port_id = fwg_port_log.port_id
412 prefix = self._get_prefix(port_id, action)
413 if not prefix:
414 # Generate a new prefix from port and action
415 project_id = fwg_port_log.project_id
416 prefix = LogPrefix(port_id, action, project_id)
417 self._add_to_prefixes_table(port_id, prefix)
418
419 # Get iptables manager from router port
420 ipt_mgr = self._get_ipt_mgr_by_port(port_id)
421 if ipt_mgr:
422 applied_ipt_mgrs.add(ipt_mgr)
423
424 device = self._get_intf_name(port_id)
425
426 # Add the NFLOG rules to the dropped chain into iptables
427 ipv4_rules, ipv6_rules = \
428 self._generate_nflog_rules_v4v6(device, prefix=prefix.id)
429 self._add_rules_to_chain_v4v6(ipt_mgr,
430 'accepted', ipv4_rules, ipv6_rules,
431 wrap=True, top=True, tag=prefix.id)
432
433 prefix.add_log_obj_ref(fwg_port_log.log_id)
434
435 def _add_log_rules_dropped(self, applied_ipt_mgrs, fwg_port_log):
436 """Add NFLOG rules to the dropped chain into iptables"""
437
438 action = log_const.DROP_EVENT
439 port_id = fwg_port_log.port_id
440 prefix = self._get_prefix(port_id, action)
441 if not prefix:
442 # Generate a new prefix from port and action
443 project_id = fwg_port_log.project_id
444 prefix = LogPrefix(port_id, action, project_id)
445 self._add_to_prefixes_table(port_id, prefix)
446 device = self._get_intf_name(port_id)
447
448 # Get iptables manager from router port
449 ipt_mgr = self._get_ipt_mgr_by_port(port_id)
450 if ipt_mgr:
451 applied_ipt_mgrs.add(ipt_mgr)
452
453 # Add the NFLOG rules to the dropped chain into iptables
454 ipv4_rules, ipv6_rules = \
455 self._generate_nflog_rules_v4v6(device, prefix=prefix.id)
456 self._add_rules_to_chain_v4v6(ipt_mgr,
457 'dropped', ipv4_rules, ipv6_rules,
458 wrap=True, top=True, tag=prefix.id)
459 # Add the NFLOG rules to the rejected chain in iptables
460 self._add_rules_to_chain_v4v6(ipt_mgr,
461 'rejected', ipv4_rules, ipv6_rules,
462 wrap=True, top=True, tag=prefix.id)
463 prefix.add_log_obj_ref(fwg_port_log.log_id)
464
465 def _add_rules_to_chain_v4v6(self, ipt_mgr, chain_name, v4_rules, v6_rules,
466 wrap=False, comment=None,
467 top=False, tag=None):
468 """Add rules to filter table in iptables and ip6tables"""
469
470 for rule in v4_rules:
471 ipt_mgr.ipv4['filter'].add_rule(chain_name, rule, wrap=wrap,
472 comment=comment, top=top, tag=tag)
473 for rule in v6_rules:
474 ipt_mgr.ipv6['filter'].add_rule(chain_name, rule, wrap=wrap,
475 comment=comment, top=top, tag=tag)
476
477 def _add_fwg_port_log(self, log_id, port_id, log_info):
478
479 self.fwg_port_logs[log_id].add(FWGPortLog(port_id, log_info))
480
481 # Add log ID into the corresponding LogPrefix object
482 if log_info['event'] == log_const.ALL_EVENT:
483 events = [log_const.ACCEPT_EVENT, log_const.DROP_EVENT]
484 else:
485 events = [log_info['event']]
486 for event in events:
487 prefix = self._get_prefix(port_id, event)
488 if prefix:
489 prefix.add_log_obj_ref(log_id)
490
491 def _generate_nflog_rules_v4v6(self, device, prefix):
492 iptables_rules = []
493 added_rules = set()
494 for direction in constants.VALID_DIRECTIONS:
495 args = self._generate_iptables_args(direction, device, prefix)
496 rule = ' '.join(args)
497 if rule in added_rules:
498 # Since these rules are already added to iptables,
499 # so we ignore them here
500 continue
501 added_rules.add(rule)
502 iptables_rules.append(rule)
503 LOG.debug("iptables-nflog-rules %r", iptables_rules)
504 return iptables_rules, iptables_rules
505
506 def _generate_iptables_args(self, direction, device, prefix=None):
507
508 direction_config = ['-%s %s' %
509 (IPTABLES_DIRECTION_DEVICE[direction], device)]
510 match_rule = []
511 if self.rate_limit:
512 match_rule += [
513 '-m', 'limit', '--limit', '%s/sec' % self.rate_limit]
514 if self.burst_limit:
515 match_rule += ['--limit-burst %s' % self.burst_limit]
516 target = ['-j', 'NFLOG']
517 if prefix:
518 target += ['--nflog-prefix', '%s' % prefix]
519
520 args = direction_config + match_rule + target
521 return args
522
523 def _clear_rules_from_tag_v4v6(self, ipt_mgt, tag):
524 """Remove rules from filter table in iptables and ip6tables"""
525 ipt_mgt.ipv4['filter'].clear_rules_by_tag(tag)
526 ipt_mgt.ipv6['filter'].clear_rules_by_tag(tag)