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