Debian Codegraph @

neutron_vpnaas/services/vpn/device_drivers/libreswan_ipsec.py

raw
1 # Copyright (c) 2015 Red Hat, Inc.
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 import os
16
17 from neutron.agent.linux import ip_lib
18 from neutron_vpnaas.services.vpn.device_drivers import ipsec
19
20
21 class LibreSwanProcess(ipsec.OpenSwanProcess):
22 """Libreswan Process manager class.
23
24 Libreswan needs nssdb initialised before running pluto daemon.
25 """
26 IPSEC_CONF_NAT_TRAVERSAL = None
27
28 DIALECT_MAP = dict(ipsec.BaseSwanProcess.DIALECT_MAP)
29
30 # pylint: disable=useless-super-delegation
31 def __init__(self, conf, process_id, vpnservice, namespace):
32 dialect_map_update = {
33 # ENCR_AES_CTR
34 'aes-128-ctr': 'aes_ctr128',
35 'aes-192-ctr': 'aes_ctr192',
36 'aes-256-ctr': 'aes_ctr256',
37 # ENCR_AES_CCM_8
38 'aes-128-ccm-8': 'aes_ccm_a128',
39 'aes-192-ccm-8': 'aes_ccm_a192',
40 'aes-256-ccm-8': 'aes_ccm_a256',
41 # ENCR_AES_CCM_12
42 'aes-128-ccm-12': 'aes_ccm_b128',
43 'aes-192-ccm-12': 'aes_ccm_b192',
44 'aes-256-ccm-12': 'aes_ccm_b256',
45 # ENCR_AES_CCM_16
46 'aes-128-ccm-16': 'aes_ccm_c128',
47 'aes-192-ccm-16': 'aes_ccm_c192',
48 'aes-256-ccm-16': 'aes_ccm_c256',
49 # ENCR_AES_GCM_8
50 'aes-128-gcm-8': 'aes_gcm_a128',
51 'aes-192-gcm-8': 'aes_gcm_a192',
52 'aes-256-gcm-8': 'aes_gcm_a256',
53 # ENCR_AES_GCM_12
54 'aes-128-gcm-12': 'aes_gcm_b128',
55 'aes-192-gcm-12': 'aes_gcm_b192',
56 'aes-256-gcm-12': 'aes_gcm_b256',
57 # ENCR_AES_GCM_16
58 'aes-128-gcm-16': 'aes_gcm_c128',
59 'aes-192-gcm-16': 'aes_gcm_c192',
60 'aes-256-gcm-16': 'aes_gcm_c256'
61 }
62 self.DIALECT_MAP.update(dialect_map_update)
63 self._rootwrap_cfg = self._get_rootwrap_config()
64 super().__init__(conf, process_id, vpnservice, namespace)
65
66 def _ipsec_execute(self, cmd, check_exit_code=True, extra_ok_codes=None):
67 """Execute ipsec command on namespace.
68
69 This execute is wrapped by namespace wrapper.
70 The namespace wrapper will bind /etc and /var/run
71 """
72 ip_wrapper = ip_lib.IPWrapper(namespace=self.namespace)
73 mount_paths = {'/etc': '%s/etc' % self.config_dir,
74 '/run': '%s/var/run' % self.config_dir}
75 mount_paths_str = ','.join(
76 "{}:{}".format(source, target)
77 for source, target in mount_paths.items())
78 ns_wrapper = self.get_ns_wrapper()
79 return ip_wrapper.netns.execute(
80 [ns_wrapper,
81 '--mount_paths=%s' % mount_paths_str,
82 ('--rootwrap_config=%s' % self._rootwrap_cfg
83 if self._rootwrap_cfg else ''),
84 '--cmd={},{}'.format(self.binary, ','.join(cmd))],
85 check_exit_code=check_exit_code,
86 extra_ok_codes=extra_ok_codes)
87
88 def _ensure_needed_files(self):
89 # addconn reads from /etc/hosts and /etc/resolv.conf. As /etc would be
90 # bind-mounted, create these two empty files in the target directory.
91 with open('%s/etc/hosts' % self.config_dir, 'a'):
92 pass
93 with open('%s/etc/resolv.conf' % self.config_dir, 'a'):
94 pass
95
96 def ensure_configs(self):
97 """Generate config files which are needed for Libreswan.
98
99 Initialise the nssdb, otherwise pluto daemon will fail to run.
100 """
101
102 # Since we set ipsec.secrets to be owned by root, the standard
103 # mechanisms for setting up the config files will get a permission
104 # problem when attempting to overwrite the file, so we need to
105 # remove it first.
106 secrets_file = self._get_config_filename('ipsec.secrets')
107 if os.path.exists(secrets_file):
108 self._execute(['rm', '-f', secrets_file])
109
110 super().ensure_configs()
111
112 # LibreSwan uses the capabilities library to restrict access to
113 # ipsec.secrets to users that have explicit access. Since pluto is
114 # running as root and the file has 0600 perms, we must set the
115 # owner of the file to root.
116 self._execute(['chown', '--from=%s' % os.getuid(), 'root:root',
117 secrets_file])
118
119 # Libreswan needs to write logs to this directory.
120 self._execute(['chown', '--from=%s' % os.getuid(), 'root:root',
121 self.log_dir])
122
123 self._ensure_needed_files()
124
125 # Load the ipsec kernel module if not loaded
126 self._ipsec_execute(['_stackmanager', 'start'])
127 # checknss creates nssdb only if it is missing
128 # It is added in Libreswan version v3.10
129 # For prior versions use initnss
130 try:
131 self._ipsec_execute(['checknss'])
132 except RuntimeError:
133 self._ipsec_execute(['initnss'])
134
135 def get_status(self):
136 return self._ipsec_execute(['whack', '--status'],
137 extra_ok_codes=[1, 3])
138
139 def start_pluto(self):
140 cmd = ['pluto',
141 '--use-xfrm',
142 '--uniqueids']
143
144 if self.conf.ipsec.enable_detailed_logging:
145 cmd += ['--perpeerlog', '--perpeerlogbase', self.log_dir]
146 self._ipsec_execute(cmd)
147
148 def add_ipsec_connection(self, nexthop, conn_id):
149 # Connections will be automatically added as auto=start/add for
150 # initiator=bi-directional/response-only specified in the config.
151 pass
152
153 def start_whack_listening(self):
154 # NOTE(huntxu): This is a workaround for with a weak (len<8) secret,
155 # "ipsec whack --listen" will exit with 3.
156 self._ipsec_execute(['whack', '--listen'], extra_ok_codes=[3])
157
158 def shutdown_whack(self):
159 self._ipsec_execute(['whack', '--shutdown'])
160
161 def initiate_connection(self, conn_name):
162 self._ipsec_execute(
163 ['whack', '--name', conn_name, '--asynchronous', '--initiate'])
164
165 def terminate_connection(self, conn_name):
166 self._ipsec_execute(['whack', '--name', conn_name, '--terminate'])
167
168
169 class LibreSwanDriver(ipsec.IPsecDriver):
170 def create_process(self, process_id, vpnservice, namespace):
171 return LibreSwanProcess(
172 self.conf,
173 process_id,
174 vpnservice,
175 namespace)