Debian Codegraph @

neutron_fwaas/services/firewall/service_drivers/agents/drivers/linux/legacy_conntrack.py

raw symbols SCIP
1 # Copyright (c) 2017 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 neutron.agent.linux import utils as linux_utils
17 from neutron_lib import constants
18 from oslo_log import log as logging
19
20 from neutron_fwaas.services.firewall.service_drivers.agents.drivers import\
21 conntrack_base
22
23 LOG = logging.getLogger(__name__)
24
25 IP_VERSIONS = [constants.IP_VERSION_4, constants.IP_VERSION_6]
26
27 ATTR_POSITIONS = {
28 'icmp': (('type', 5), ('code', 6), ('src', 3), ('dst', 4), ('id', 7)),
29 'icmpv6': (('type', 5), ('code', 6), ('src', 3), ('dst', 4), ('id', 7)),
30 'tcp': (('sport', 6), ('dport', 7), ('src', 4), ('dst', 5)),
31 'udp': (('sport', 5), ('dport', 6), ('src', 3), ('dst', 4))
32 }
33
34
35 def normalize_filters_tuple(rule_tuple):
36 new_rule = []
37 for el in rule_tuple:
38 if el is None:
39 new_rule.append('')
40 else:
41 new_rule.append(el)
42 return tuple(new_rule)
43
44
45 class ConntrackLegacy(conntrack_base.ConntrackDriverBase):
46 def initialize(self, execute=None):
47 LOG.debug('Initialize Conntrack Legacy')
48 self.execute = execute or linux_utils.execute
49
50 def flush_entries(self, namespace):
51 prefixcmd = ['ip', 'netns', 'exec', namespace] if namespace else []
52 cmd = prefixcmd + ['conntrack', '-D']
53 self._execute_command(cmd)
54
55 def delete_entries(self, rules, namespace):
56 rule_filters = [self._get_filter_from_rule(r) for r in rules]
57 rule_filters.sort(key=normalize_filters_tuple)
58
59 delete_entries = self._get_entries_to_delete(
60 rule_filters, self.list_entries(namespace))
61 for delete_entry in delete_entries:
62 cmd = self._get_conntrack_cmd_from_entry(delete_entry, namespace)
63 self._execute_command(cmd)
64
65 def _execute_command(self, cmd):
66 try:
67 output = self.execute(cmd,
68 run_as_root=True,
69 check_exit_code=True,
70 extra_ok_codes=[1],
71 privsep_exec=True)
72 except RuntimeError:
73 msg = "Failed execute conntrack command %s" % cmd
74 raise RuntimeError(msg)
75 return output
76
77 def list_entries(self, namespace):
78 """List and parse all conntrack entries
79
80 :param namespace: namespace to get conntrack entries
81 :returns: sorted list of conntrack entries in Python tuple
82 for example: [(4, 'icmp', 8, 0, '1.1.1.1', '2.2.2.2', 1234),
83 (4, 'tcp', 1, 2, '1.1.1.1', '2.2.2.2')]
84 """
85 parsed_entries = []
86 prefixcmd = ['ip', 'netns', 'exec', namespace] if namespace else []
87 for ip_version in IP_VERSIONS:
88 cmd = prefixcmd + ['conntrack', '-L',
89 '-f', 'ipv' + str(ip_version)]
90 raw_entries = self._execute_command(cmd).splitlines()
91 for raw_entry in raw_entries:
92 parsed_entry = self._parse_entry(raw_entry.split(), ip_version)
93 if parsed_entry is not None:
94 parsed_entries.append(parsed_entry)
95 return sorted(parsed_entries)
96
97 def _get_conntrack_cmd_from_entry(self, entry, namespace):
98 prefixcmd = ['ip', 'netns', 'exec', namespace] if namespace else []
99 cmd = ['conntrack', '-D']
100 contrack_filter = ['-f', 'ipv' + str(entry[0]), '-p', entry[1]]
101 if entry[1] in ['icmp', 'icmpv6']:
102 contrack_filter.extend(['--icmp-type', entry[2],
103 '--icmp-code', entry[3],
104 '-s', entry[4],
105 '-d', entry[5],
106 '--icmp-id', entry[6]])
107 else:
108 contrack_filter.extend(['--sport', entry[2],
109 '--dport', entry[3],
110 '-s', entry[4],
111 '-d', entry[5]])
112 exec_cmd = prefixcmd + cmd + contrack_filter
113 return exec_cmd
114
115 def _parse_entry(self, entry, ip_version):
116 """Parse entry from text to Python tuple
117
118 :param entry: conntrack entry as a list of string
119 :param ip_version: ip version 4 or 6
120 :returns: conntrack entry in Python tuple
121 for example: (4, 'tcp', 1, 2, '1.1.1.1', '2.2.2.2')
122 The attributes are ordered to be easy to compare with other entries
123 and compare with firewall rule
124 """
125 protocol = entry[0]
126 if protocol not in ATTR_POSITIONS:
127 LOG.warning(
128 'Skipping conntrack entry %s with unsupported protocol', entry)
129 return None
130
131 parsed_entry = [ip_version, protocol]
132 for attr, position in ATTR_POSITIONS[protocol]:
133 val = entry[position].partition('=')[2]
134 parsed_entry.append(int(val) if attr in ['sport', 'dport', 'type',
135 'code', 'id'] else val)
136 return tuple(parsed_entry)
137
138 def _get_entries_to_delete(self, rule_filters, entries):
139 """Specify conntrack entries to delete
140
141 :param rule_filters: List of filters parsed from firewall rules
142 :param entries: all entries within namespace
143 :returns: conntrack entries to delete
144 """
145 # List all entries from namespace, they are already parsed
146 # to a list of tuples:
147 # [(4, 'icmp', 8, 0, '1.1.1.1', '2.2.2.2', 1234),
148 # (4, 'tcp', 1, 2, '1.1.1.1', '2.2.2.2')]
149 delete_entries = []
150 entry_index = 0
151 entry_number = len(entries)
152 for rule_filter in rule_filters:
153 while entry_index < entry_number:
154 # Compare entry with rule
155 comp = self._compare_entry_and_rule_filter(
156 rule_filter, entries[entry_index])
157 # Increase entry_index when entry is under rule
158 if comp < 0:
159 entry_index += 1
160 # Append entry to delete_entry if it matches with rule
161 elif comp == 0:
162 delete_entries.append(entries[entry_index])
163 entry_index += 1
164 # Switch to new higher rule
165 else:
166 break
167 return delete_entries
168
169 @staticmethod
170 def _get_filter_from_rule(rule):
171 """Parse the firewall rule to a tuple
172
173 :param rule: firewall rule
174 :returns: a tuple of parsed information
175 """
176 rule_filter = []
177 keys = ('ip_version', 'protocol',
178 'source_port', 'destination_port',
179 'source_ip_address', 'destination_ip_address')
180 for key in keys:
181 if key in ('source_port', 'destination_port'):
182 port_range = rule.get(key, [])
183 if port_range:
184 port_lower, sep, port_upper = port_range.partition(':')
185 port_upper = port_upper if sep else port_lower
186 port_range = [port_lower, port_upper]
187 rule_filter.append(port_range or [])
188 else:
189 rule_filter.append(rule.get(key, []))
190 return tuple(rule_filter)
191
192 @staticmethod
193 def _compare_entry_and_rule_filter(rule_filter, entry):
194 """Define that the entry should be deleted or not
195
196 :param rule_filter: filter that is parsed from a firewall rule
197 for example: (4, 'tcp', ['22', '33'], ['44', '55'])
198 :param entry: parsed conntrack entry,
199 for example: (4, 'tcp', 1, 2, '1.1.1.1', '2.2.2.2')
200 :returns: -1 if entry is lower than rule
201 0 if entry matches rule,
202 1 if entry is higher than rule
203 """
204 ENTRY_IS_LOWER = -1
205 ENTRY_MATCHES = 0
206 ENTRY_IS_HIGHER = 1
207 rule_ip_version = rule_filter[0]
208 if entry[0] < rule_ip_version:
209 return ENTRY_IS_LOWER
210 elif entry[0] > rule_ip_version:
211 return ENTRY_IS_HIGHER
212 rule_protocol = rule_filter[1]
213 if rule_protocol == constants.PROTO_NAME_IPV6_ICMP:
214 rule_protocol = constants.PROTO_NAME_IPV6_ICMP_LEGACY
215 if rule_protocol:
216 if entry[1] < rule_protocol:
217 return ENTRY_IS_LOWER
218 elif entry[1] > rule_protocol:
219 return ENTRY_IS_HIGHER
220 sport_range = rule_filter[2]
221 if sport_range:
222 sport_range = [int(port) for port in sport_range]
223 if entry[2] < min(sport_range[0], sport_range[-1]):
224 return ENTRY_IS_LOWER
225 elif entry[2] > max(sport_range[0], sport_range[-1]):
226 return ENTRY_IS_HIGHER
227 dport_range = rule_filter[3]
228 if dport_range:
229 dport_range = [int(port) for port in dport_range]
230 if entry[3] < min(dport_range[0], dport_range[-1]):
231 return ENTRY_IS_LOWER
232 elif entry[3] > max(dport_range[0], dport_range[-1]):
233 return ENTRY_IS_HIGHER
234 return ENTRY_MATCHES