Debian Codegraph @

neutron_fwaas/privileged/netlink_lib.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 # Some parts are based on python-conntrack:
17 # Copyright (c) 2009-2011,2015 Andrew Grigorev <[email protected]>
18 #
19 # Permission is hereby granted, free of charge, to any person obtaining a copy
20 # of this software and associated documentation files (the "Software"), to deal
21 # in the Software without restriction, including without limitation the rights
22 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23 # copies of the Software, and to permit persons to whom the Software is
24 # furnished to do so, subject to the following conditions:
25 #
26 # The above copyright notice and this permission notice shall be included in
27 # all copies or substantial portions of the Software.
28 #
29 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 # THE SOFTWARE.
36 #
37
38 import ctypes
39 from ctypes import util
40
41 from oslo_log import log as logging
42
43 from neutron_lib import constants
44
45 from neutron_fwaas import privileged
46 from neutron_fwaas.privileged import netlink_constants as nl_constants
47 from neutron_fwaas.privileged import utils as fwaas_utils
48
49 LOG = logging.getLogger(__name__)
50
51 nfct_lib = util.find_library('netfilter_conntrack')
52 nfct = ctypes.CDLL(nfct_lib)
53 libc = ctypes.CDLL(util.find_library('libc.so.6'))
54
55 # In unit tests the actual nfct library may not be installed, and since we
56 # don't make actual calls to it we don't want to add a hard dependency.
57 if nfct_lib:
58 # It's important that the types be defined properly on all of the functions
59 # we call from nfct, otherwise pointers can be truncated and cause
60 # segfaults.
61 nfct.nfct_set_attr.argtypes = [ctypes.c_void_p,
62 ctypes.c_int,
63 ctypes.c_void_p]
64 nfct.nfct_set_attr_u8.argtypes = [ctypes.c_void_p,
65 ctypes.c_int,
66 ctypes.c_uint8]
67 nfct.nfct_set_attr_u16.argtypes = [ctypes.c_void_p,
68 ctypes.c_int,
69 ctypes.c_uint16]
70 nfct.nfct_snprintf.argtypes = [ctypes.c_char_p,
71 ctypes.c_uint,
72 ctypes.c_void_p,
73 ctypes.c_uint,
74 ctypes.c_uint,
75 ctypes.c_uint]
76 nfct.nfct_new.restype = ctypes.c_void_p
77 nfct.nfct_destroy.argtypes = [ctypes.c_void_p]
78 nfct.nfct_query.argtypes = [ctypes.c_void_p,
79 ctypes.c_int,
80 ctypes.c_void_p]
81 nfct.nfct_callback_register.argtypes = [ctypes.c_void_p,
82 ctypes.c_int,
83 ctypes.c_void_p,
84 ctypes.c_void_p]
85 nfct.nfct_open.restype = ctypes.c_void_p
86 nfct.nfct_close.argtypes = [ctypes.c_void_p]
87
88
89 IP_VERSIONS = [constants.IP_VERSION_4, constants.IP_VERSION_6]
90 DATA_CALLBACK = None
91
92 ATTR_POSITIONS = {
93 'icmp': [('type', 6), ('code', 7), ('src', 4), ('dst', 5), ('id', 8)],
94 'icmpv6': [('type', 6), ('code', 7), ('src', 4), ('dst', 5), ('id', 8)],
95 'tcp': [('sport', 7), ('dport', 8), ('src', 5), ('dst', 6)],
96 'udp': [('sport', 6), ('dport', 7), ('src', 4), ('dst', 5)]
97 }
98
99 TARGET = {'src': {4: nl_constants.ATTR_IPV4_SRC,
100 6: nl_constants.ATTR_IPV6_SRC},
101 'dst': {4: nl_constants.ATTR_IPV4_DST,
102 6: nl_constants.ATTR_IPV6_DST},
103 'ipversion': {4: nl_constants.ATTR_L3PROTO,
104 6: nl_constants.ATTR_L3PROTO},
105 'protocol': {4: nl_constants.ATTR_L4PROTO,
106 6: nl_constants.ATTR_L4PROTO},
107 'code': {4: nl_constants.ATTR_ICMP_CODE,
108 6: nl_constants.ATTR_ICMP_CODE},
109 'type': {4: nl_constants.ATTR_ICMP_TYPE,
110 6: nl_constants.ATTR_ICMP_TYPE},
111 'id': {4: nl_constants.ATTR_ICMP_ID,
112 6: nl_constants.ATTR_ICMP_ID},
113 'sport': {4: nl_constants.ATTR_PORT_SRC,
114 6: nl_constants.ATTR_PORT_SRC},
115 'dport': {4: nl_constants.ATTR_PORT_DST,
116 6: nl_constants.ATTR_PORT_DST}}
117
118 NFCT_CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int,
119 ctypes.c_void_p, ctypes.c_void_p)
120
121
122 class ConntrackOpenFailedExit(SystemExit):
123 """Raised if we fail to open a new conntrack or conntrack handler"""
124
125
126 class ConntrackManager:
127 def __init__(self, family_socket=None):
128 self.family_socket = family_socket
129 self.set_functions = {
130 'src': {4: nfct.nfct_set_attr,
131 6: nfct.nfct_set_attr},
132 'dst': {4: nfct.nfct_set_attr,
133 6: nfct.nfct_set_attr},
134 'ipversion': {4: nfct.nfct_set_attr_u8,
135 6: nfct.nfct_set_attr_u8},
136 'protocol': {4: nfct.nfct_set_attr_u8,
137 6: nfct.nfct_set_attr_u8},
138 'type': {4: nfct.nfct_set_attr_u8,
139 6: nfct.nfct_set_attr_u8},
140 'code': {4: nfct.nfct_set_attr_u8,
141 6: nfct.nfct_set_attr_u8},
142 'id': {4: nfct.nfct_set_attr_u16,
143 6: nfct.nfct_set_attr_u16},
144 'sport': {4: nfct.nfct_set_attr_u16,
145 6: nfct.nfct_set_attr_u16},
146 'dport': {4: nfct.nfct_set_attr_u16,
147 6: nfct.nfct_set_attr_u16}, }
148
149 self.converters = {'src': bytes,
150 'dst': bytes,
151 'ipversion': nl_constants.IPVERSION_SOCKET.get,
152 'protocol': constants.IP_PROTOCOL_MAP.get,
153 'code': int,
154 'type': int,
155 'id': libc.htons,
156 'sport': libc.htons,
157 'dport': libc.htons, }
158
159 def list_entries(self):
160 entries = []
161 raw_entry = ctypes.create_string_buffer(nl_constants.BUFFER)
162
163 @NFCT_CALLBACK
164 def callback(type_, conntrack, data):
165 nfct.nfct_snprintf(raw_entry, nl_constants.BUFFER,
166 conntrack, type_,
167 nl_constants.NFCT_O_PLAIN,
168 nl_constants.NFCT_OF_TIME)
169 entries.append(raw_entry.value.decode('utf-8'))
170 return nl_constants.NFCT_CB_CONTINUE
171
172 self._callback_register(nl_constants.NFCT_T_ALL,
173 callback, DATA_CALLBACK)
174
175 data_ref = self._get_ref(self.family_socket or
176 nl_constants.IPVERSION_SOCKET[4])
177 self._query(nl_constants.NFCT_Q_DUMP, data_ref)
178 return entries
179
180 def delete_entries(self, entries):
181 conntrack = nfct.nfct_new()
182 try:
183 for entry in entries:
184 self._set_attributes(conntrack, entry)
185 self._query(nl_constants.NFCT_Q_DESTROY, conntrack)
186 except Exception as e:
187 msg = "Failed to delete conntrack entries %s" % e
188 LOG.critical(msg)
189 raise ConntrackOpenFailedExit(msg)
190 finally:
191 nfct.nfct_destroy(conntrack)
192
193 def flush_entries(self):
194 data_ref = self._get_ref(self.family_socket or
195 nl_constants.IPVERSION_SOCKET[4])
196 self._query(nl_constants.NFCT_Q_FLUSH, data_ref)
197
198 def _query(self, query_type, query_data):
199 result = nfct.nfct_query(self.conntrack_handler, query_type,
200 query_data)
201 if result == nl_constants.NFCT_CB_FAILURE:
202 LOG.warning("Netlink query failed")
203
204 def _convert_text_to_binary(self, source, addr_family):
205 dest = ctypes.create_string_buffer(
206 nl_constants.IPVERSION_BUFFER[addr_family])
207 libc.inet_pton(nl_constants.IPVERSION_SOCKET[addr_family],
208 source.encode('utf-8'), dest)
209 return dest.raw
210
211 def _set_attributes(self, conntrack, entry):
212 ipversion = entry.get('ipversion', 4)
213 for attr, value in entry.items():
214 set_function = self.set_functions[attr][ipversion]
215 target = TARGET[attr][ipversion]
216 converter = self.converters[attr]
217 if attr in ['src', 'dst']:
218 # convert src and dst of IPv4 and IPv6 into same format
219 value = self._convert_text_to_binary(value, ipversion)
220 set_function(conntrack, target, converter(value))
221
222 def _callback_register(self, message_type, callback_func, data):
223 nfct.nfct_callback_register(self.conntrack_handler,
224 message_type, callback_func, data)
225
226 def _get_ref(self, data):
227 return ctypes.byref(ctypes.c_int(data))
228
229 def __enter__(self):
230 self.conntrack_handler = nfct.nfct_open(
231 nl_constants.CONNTRACK,
232 nl_constants.NFNL_SUBSYS_CTNETLINK)
233 if not self.conntrack_handler:
234 msg = "Failed to open new conntrack handler"
235 LOG.critical(msg)
236 raise ConntrackOpenFailedExit(msg)
237 return self
238
239 def __exit__(self, *args):
240 nfct.nfct_close(self.conntrack_handler)
241
242
243 def _parse_entry(entry, ipversion):
244 """Parse entry from text to Python tuple
245
246 :param entry: conntrack entry in text
247 :param ipversion: ipversion 4 or 6
248 :return: conntrack entry in Python tuple
249 example: (4, 'tcp', '1', '2', '1.1.1.1', '2.2.2.2')
250 The attributes are ordered to be easy to compare with other entries
251 and compare with firewall rule
252 """
253 protocol = entry[1]
254 parsed_entry = [ipversion, protocol]
255 for attr, position in ATTR_POSITIONS[protocol]:
256 val = entry[position].partition('=')[2]
257 parsed_entry.append(int(val) if attr in ['sport', 'dport', 'type',
258 'code', 'id'] else val)
259 return tuple(parsed_entry)
260
261
262 @privileged.default.entrypoint
263 def flush_entries(namespace=None):
264 """Delete all conntrack entries
265
266 :param namespace: namespace to delete conntrack entries
267 :return: None
268 """
269 with fwaas_utils.in_namespace(namespace):
270 for ipversion in IP_VERSIONS:
271 with ConntrackManager(nl_constants.IPVERSION_SOCKET[ipversion]) \
272 as conntrack:
273 conntrack.flush_entries()
274
275
276 @privileged.default.entrypoint
277 def list_entries(namespace=None):
278 """List and parse all conntrack entries
279
280 :param namespace: namespace to get conntrack entries
281 :return: sorted list of conntrack entries in Python tuple
282 example: [(4, 'icmp', '8', '0', '1.1.1.1', '2.2.2.2', '1234'),
283 (4, 'tcp', '1', '2', '1.1.1.1', '2.2.2.2')]
284 """
285 parsed_entries = []
286 with fwaas_utils.in_namespace(namespace):
287 for ipversion in IP_VERSIONS:
288 with ConntrackManager(nl_constants.IPVERSION_SOCKET[ipversion]) \
289 as conntrack:
290 raw_entries = conntrack.list_entries()
291 for raw_entry in raw_entries:
292 parsed_entry = _parse_entry(raw_entry.split(), ipversion)
293 parsed_entries.append(parsed_entry)
294 return sorted(parsed_entries)
295
296
297 @privileged.default.entrypoint
298 def delete_entries(entries, namespace=None):
299 """Delete selected entries
300
301 :param entries: list of parsed (as tuple) entries to delete
302 :param namespace: namespace to delete conntrack entries
303 :return: None
304 """
305 entry_args = []
306 for entry in entries:
307 entry_arg = {'ipversion': entry[0], 'protocol': entry[1]}
308 for idx, attr in enumerate(ATTR_POSITIONS[entry_arg['protocol']]):
309 entry_arg[attr[0]] = entry[idx + 2]
310 entry_args.append(entry_arg)
311
312 with fwaas_utils.in_namespace(namespace):
313 with ConntrackManager() as conntrack:
314 conntrack.delete_entries(entry_args)