CSIT-385 CSIT-386 IPv4/IPv6 IPsec tests
[csit.git] / resources / libraries / python / IPsecUtil.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """IPsec utilities library."""
15
16 from ipaddress import ip_network
17
18 from enum import Enum
19
20 from resources.libraries.python.VatExecutor import VatExecutor
21 from resources.libraries.python.topology import Topology
22 from resources.libraries.python.VatJsonUtil import VatJsonUtil
23
24
25 # pylint: disable=too-few-public-methods
26 class PolicyAction(Enum):
27     """Policy actions."""
28     BYPASS = 'bypass'
29     DISCARD = 'discard'
30     PROTECT = 'protect'
31
32     def __init__(self, string):
33         self.string = string
34
35
36 class CryptoAlg(Enum):
37     """Encryption algorithms."""
38     AES_CBC_128 = ('aes-cbc-128', 'AES-CBC', 16)
39     AES_CBC_192 = ('aes-cbc-192', 'AES-CBC', 24)
40     AES_CBC_256 = ('aes-cbc-256', 'AES-CBC', 32)
41
42     def __init__(self, alg_name, scapy_name, key_len):
43         self.alg_name = alg_name
44         self.scapy_name = scapy_name
45         self.key_len = key_len
46
47
48 class IntegAlg(Enum):
49     """Integrity algorithm."""
50     SHA1_96 = ('sha1-96', 'HMAC-SHA1-96', 20)
51     SHA_256_128 = ('sha-256-128', 'SHA2-256-128', 32)
52     SHA_384_192 = ('sha-384-192', 'SHA2-384-192', 48)
53     SHA_512_256 = ('sha-512-256', 'SHA2-512-256', 64)
54
55     def __init__(self, alg_name, scapy_name, key_len):
56         self.alg_name = alg_name
57         self.scapy_name = scapy_name
58         self.key_len = key_len
59
60
61 class IPsecUtil(object):
62     """IPsec utilities."""
63
64     # pylint: disable=too-many-arguments
65     # pylint: disable=too-many-locals
66
67     @staticmethod
68     def policy_action_bypass():
69         """Return policy action bypass.
70
71         :return: PolicyAction enum BYPASS object.
72         :rtype: PolicyAction
73         """
74         return PolicyAction.BYPASS
75
76     @staticmethod
77     def policy_action_discard():
78         """Return policy action discard.
79
80         :return: PolicyAction enum DISCARD object.
81         :rtype: PolicyAction
82         """
83         return PolicyAction.DISCARD
84
85     @staticmethod
86     def policy_action_protect():
87         """Return policy action protect.
88
89         :return: PolicyAction enum PROTECT object.
90         :rtype: PolicyAction
91         """
92         return PolicyAction.PROTECT
93
94     @staticmethod
95     def crypto_alg_aes_cbc_128():
96         """Return encryption algorithm aes-cbc-128.
97
98         :return: CryptoAlg enum AES_CBC_128 object.
99         :rtype: CryptoAlg
100         """
101         return CryptoAlg.AES_CBC_128
102
103     @staticmethod
104     def crypto_alg_aes_cbc_192():
105         """Return encryption algorithm aes-cbc-192.
106
107         :return: CryptoAlg enum AES_CBC_192 objec.
108         :rtype: CryptoAlg
109         """
110         return CryptoAlg.AES_CBC_192
111
112     @staticmethod
113     def crypto_alg_aes_cbc_256():
114         """Return encryption algorithm aes-cbc-256.
115
116         :return: CryptoAlg enum AES_CBC_256 object.
117         :rtype: CryptoAlg
118         """
119         return CryptoAlg.AES_CBC_256
120
121     @staticmethod
122     def get_crypto_alg_key_len(crypto_alg):
123         """Return encryption algorithm key length.
124
125         :param crypto_alg: Encryption algorithm.
126         :type crypto_alg: CryptoAlg
127         :return: Key length.
128         :rtype: int
129         """
130         return crypto_alg.key_len
131
132     @staticmethod
133     def get_crypto_alg_scapy_name(crypto_alg):
134         """Return encryption algorithm scapy name.
135
136         :param crypto_alg: Encryption algorithm.
137         :type crypto_alg: CryptoAlg
138         :return: Algorithm scapy name.
139         :rtype: str
140         """
141         return crypto_alg.scapy_name
142
143     @staticmethod
144     def integ_alg_sha1_96():
145         """Return integrity algorithm SHA1-96.
146
147         :return: IntegAlg enum SHA1_96 object.
148         :rtype: IntegAlg
149         """
150         return IntegAlg.SHA1_96
151
152     @staticmethod
153     def integ_alg_sha_256_128():
154         """Return integrity algorithm SHA-256-128.
155
156         :return: IntegAlg enum SHA_256_128 object.
157         :rtype: IntegAlg
158         """
159         return IntegAlg.SHA_256_128
160
161     @staticmethod
162     def integ_alg_sha_384_192():
163         """Return integrity algorithm SHA-384-192.
164
165         :return: IntegAlg enum SHA_384_192 object.
166         :rtype: IntegAlg
167         """
168         return IntegAlg.SHA_384_192
169
170     @staticmethod
171     def integ_alg_sha_512_256():
172         """Return integrity algorithm SHA-512-256.
173
174         :return: IntegAlg enum SHA_512_256 object.
175         :rtype: IntegAlg
176         """
177         return IntegAlg.SHA_512_256
178
179     @staticmethod
180     def get_integ_alg_key_len(integ_alg):
181         """Return integrity algorithm key length.
182
183         :param integ_alg: Integrity algorithm.
184         :type integ_alg: IntegAlg
185         :return: Key length.
186         :rtype: int
187         """
188         return integ_alg.key_len
189
190     @staticmethod
191     def get_integ_alg_scapy_name(integ_alg):
192         """Return integrity algorithm scapy name.
193
194         :param integ_alg: Integrity algorithm.
195         :type integ_alg: IntegAlg
196         :return: Algorithm scapy name.
197         :rtype: str
198         """
199         return integ_alg.scapy_name
200
201     @staticmethod
202     def vpp_ipsec_add_sad_entry(node, sad_id, spi, crypto_alg, crypto_key,
203                                 integ_alg, integ_key, tunnel_src=None,
204                                 tunnel_dst=None):
205         """Create Security Association Database entry on the VPP node.
206
207         :param node: VPP node to add SAD entry on.
208         :param sad_id: SAD entry ID.
209         :param spi: Security Parameter Index of this SAD entry.
210         :param crypto_alg: The encryption algorithm name.
211         :param crypto_key: The encryption key string.
212         :param integ_alg: The integrity algorithm name.
213         :param integ_key: The integrity key string.
214         :param tunnel_src: Tunnel header source IPv4 or IPv6 address. If not
215             specified ESP transport mode is used.
216         :param tunnel_dst: Tunnel header destination IPv4 or IPv6 address. If
217             not specified ESP transport mode is used.
218         :type node: dict
219         :type sad_id: int
220         :type spi: int
221         :type crypto_alg: CryptoAlg
222         :type crypto_key: str
223         :type integ_alg: str
224         :type integ_key: str
225         :type tunnel_src: str
226         :type tunnel_dst: str
227         """
228         ckey = crypto_key.encode('hex')
229         ikey = integ_key.encode('hex')
230         tunnel = 'tunnel_src {0} tunnel_dst {1}'.format(tunnel_src, tunnel_dst)\
231             if tunnel_src is not None and tunnel_dst is not None else ''
232
233         out = VatExecutor.cmd_from_template(node,
234                                             "ipsec/ipsec_sad_add_entry.vat",
235                                             sad_id=sad_id, spi=spi,
236                                             calg=crypto_alg.alg_name, ckey=ckey,
237                                             ialg=integ_alg.alg_name, ikey=ikey,
238                                             tunnel=tunnel)
239         VatJsonUtil.verify_vat_retval(
240             out[0],
241             err_msg='Add SAD entry failed on {0}'.format(node['host']))
242
243     @staticmethod
244     def vpp_ipsec_sa_set_key(node, sa_id, crypto_key, integ_key):
245         """Update Security Association (SA) keys.
246
247         :param node: VPP node to update SA keys.
248         :param sa_id: SAD entry ID.
249         :param crypto_key: The encryption key string.
250         :param integ_key: The integrity key string.
251         :type node: dict
252         :type sa_id: int
253         :type crypto_key: str
254         :type integ_key: str
255         """
256         ckey = crypto_key.encode('hex')
257         ikey = integ_key.encode('hex')
258
259         out = VatExecutor.cmd_from_template(node,
260                                             "ipsec/ipsec_sa_set_key.vat",
261                                             sa_id=sa_id,
262                                             ckey=ckey, ikey=ikey)
263         VatJsonUtil.verify_vat_retval(
264             out[0],
265             err_msg='Update SA key failed on {0}'.format(node['host']))
266
267     @staticmethod
268     def vpp_ipsec_add_spd(node, spd_id):
269         """Create Security Policy Database on the VPP node.
270
271         :param node: VPP node to add SPD on.
272         :param spd_id: SPD ID.
273         :type node: dict
274         :type spd_id: int
275         """
276         out = VatExecutor.cmd_from_template(node, "ipsec/ipsec_spd_add.vat",
277                                             spd_id=spd_id)
278         VatJsonUtil.verify_vat_retval(
279             out[0],
280             err_msg='Add SPD {0} failed on {1}'.format(spd_id, node['host']))
281
282     @staticmethod
283     def vpp_ipsec_spd_add_if(node, spd_id, interface):
284         """Add interface to the Security Policy Database.
285
286         :param node: VPP node.
287         :param spd_id: SPD ID to add interface on.
288         :param interface: Interface name or sw_if_index.
289         :type node: dict
290         :type spd_id: int
291         :type interface: str or int
292         """
293         sw_if_index = Topology.get_interface_sw_index(node, interface)\
294             if isinstance(interface, basestring) else interface
295
296         out = VatExecutor.cmd_from_template(node,
297                                             "ipsec/ipsec_interface_add_spd.vat",
298                                             spd_id=spd_id, sw_if_id=sw_if_index)
299         VatJsonUtil.verify_vat_retval(
300             out[0],
301             err_msg='Add interface {0} to SPD {1} failed on {2}'.format(
302                 interface, spd_id, node['host']))
303
304     @staticmethod
305     def vpp_ipsec_spd_add_entry(node, spd_id, priority, action, inbound=True,
306                                 sa_id=None, laddr_range=None, raddr_range=None,
307                                 proto=None, lport_range=None, rport_range=None):
308         """Create Security Policy Database entry on the VPP node.
309
310         :param node: VPP node to add SPD entry on.
311         :param spd_id: SPD ID to add entry on.
312         :param priority: SPD entry priority, higher number = higher priority.
313         :param action: Policy action.
314         :param inbound: If True policy is for inbound traffic, otherwise
315             outbound.
316         :param sa_id: SAD entry ID for protect action.
317         :param laddr_range: Policy selector local IPv4 or IPv6 address range in
318             format IP/prefix or IP/mask. If no mask is provided, it's considered
319             to be /32.
320         :param raddr_range: Policy selector remote IPv4 or IPv6 address range in
321             format IP/prefix or IP/mask. If no mask is provided, it's considered
322             to be /32.
323         :param proto: Policy selector next layer protocol number.
324         :param lport_range: Policy selector local TCP/UDP port range in format
325             <port_start>-<port_end>.
326         :param rport_range: Policy selector remote TCP/UDP port range in format
327             <port_start>-<port_end>.
328         :type node: dict
329         :type spd_id: int
330         :type priority: int
331         :type action: PolicyAction
332         :type inbound: bool
333         :type sa_id: int
334         :type laddr_range: string
335         :type raddr_range: string
336         :type proto: int
337         :type lport_range: string
338         :type rport_range: string
339         """
340         direction = 'inbound' if inbound else 'outbound'
341
342         act_str = action.value
343         if PolicyAction.PROTECT == action and sa_id is not None:
344             act_str += 'sa_id {0}'.format(sa_id)
345
346         selector = ''
347         if laddr_range is not None:
348             net = ip_network(unicode(laddr_range), strict=False)
349             selector += 'laddr_start {0} laddr_stop {1} '.format(
350                 net.network_address, net.broadcast_address)
351         if raddr_range is not None:
352             net = ip_network(unicode(raddr_range), strict=False)
353             selector += 'raddr_start {0} raddr_stop {1} '.format(
354                 net.network_address, net.broadcast_address)
355         if proto is not None:
356             selector += 'protocol {0} '.format(proto)
357         if lport_range is not None:
358             selector += 'lport_start {p[0]} lport_stop {p[1]} '.format(
359                 p=lport_range.split('-'))
360         if rport_range is not None:
361             selector += 'rport_start {p[0]} rport_stop {p[1]} '.format(
362                 p=rport_range.split('-'))
363
364         out = VatExecutor.cmd_from_template(node,
365                                             "ipsec/ipsec_spd_add_entry.vat",
366                                             spd_id=spd_id, priority=priority,
367                                             action=act_str, direction=direction,
368                                             selector=selector)
369         VatJsonUtil.verify_vat_retval(
370             out[0],
371             err_msg='Add entry to SPD {0} failed on {1}'.format(spd_id,
372                                                                 node['host']))
373
374     @staticmethod
375     def vpp_ipsec_show(node):
376         """Run "show ipsec" debug CLI command.
377
378         :param node: Node to run command on.
379         :type node: dict
380         """
381         VatExecutor().execute_script("ipsec/ipsec_show.vat", node,
382                                      json_out=False)