1# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import logging
6
7from autotest_lib.client.bin import utils
8from autotest_lib.client.cros import network_chroot
9from autotest_lib.client.common_lib.cros import site_eap_certs
10
11class VPNServer(object):
12    """Context enclosing the use of a VPN server instance."""
13
14    def __enter__(self):
15        self.start_server()
16        return self
17
18
19    def __exit__(self, exception, value, traceback):
20        logging.info('Log contents: %s', self.get_log_contents())
21        self.stop_server()
22
23
24class L2TPIPSecVPNServer(VPNServer):
25    """Implementation of an L2TP/IPSec VPN.  Uses ipsec starter and xl2tpd."""
26    PRELOAD_MODULES = ('af_key', 'ah4', 'esp4', 'ipcomp', 'xfrm_user',
27                       'xfrm4_tunnel')
28    ROOT_DIRECTORIES = ('etc/ipsec.d', 'etc/ipsec.d/cacerts',
29                        'etc/ipsec.d/certs', 'etc/ipsec.d/crls',
30                        'etc/ipsec.d/private', 'etc/ppp', 'etc/xl2tpd')
31    CHAP_USER = 'chapuser'
32    CHAP_SECRET = 'chapsecret'
33    IPSEC_COMMAND = '/usr/sbin/ipsec'
34    IPSEC_LOGFILE = 'var/log/charon.log'
35    IPSEC_PRESHARED_KEY = 'preshared-key'
36    IPSEC_CA_CERTIFICATE = 'etc/ipsec.d/cacerts/ca.cert'
37    IPSEC_SERVER_CERTIFICATE = 'etc/ipsec.d/certs/server.cert'
38    PPPD_PID_FILE = 'var/run/ppp0.pid'
39    XAUTH_USER = 'xauth_user'
40    XAUTH_PASSWORD = 'xauth_password'
41    XAUTH_SECONDARY_AUTHENTICATION_STANZA = 'rightauth2=xauth'
42    XL2TPD_COMMAND = '/usr/sbin/xl2tpd'
43    XL2TPD_CONFIG_FILE = 'etc/xl2tpd/xl2tpd.conf'
44    XL2TPD_PID_FILE = 'var/run/xl2tpd.pid'
45    SERVER_IP_ADDRESS = '192.168.1.99'
46    IPSEC_COMMON_CONFIGS = {
47        'etc/strongswan.conf' :
48            'charon {\n'
49            '  filelog {\n'
50            '    %(charon-logfile)s {\n'
51            '      time_format = %%b %%e %%T\n'
52            '      default = 3\n'
53            '    }\n'
54            '  }\n'
55            '  install_routes = no\n'
56            '  ignore_routing_tables = 0\n'
57            '  routing_table = 0\n'
58            '}\n',
59
60        'etc/passwd' :
61            'root:x:0:0:root:/root:/bin/bash\n'
62            'ipsec:*:212:212::/dev/null:/bin/false\n',
63
64        'etc/group' :
65            'ipsec:x:212:\n',
66
67        XL2TPD_CONFIG_FILE :
68            '[global]\n'
69            '\n'
70            '[lns default]\n'
71            '  ip range = 192.168.1.128-192.168.1.254\n'
72            '  local ip = 192.168.1.99\n'
73            '  require chap = yes\n'
74            '  refuse pap = yes\n'
75            '  require authentication = yes\n'
76            '  name = LinuxVPNserver\n'
77            '  ppp debug = yes\n'
78            '  pppoptfile = /etc/ppp/options.xl2tpd\n'
79            '  length bit = yes\n',
80
81        'etc/xl2tpd/l2tp-secrets' :
82            '*      them    l2tp-secret',
83
84        'etc/ppp/chap-secrets' :
85            '%(chap-user)s        *       %(chap-secret)s      *',
86
87        'etc/ppp/options.xl2tpd' :
88            'ipcp-accept-local\n'
89            'ipcp-accept-remote\n'
90            'noccp\n'
91            'auth\n'
92            'crtscts\n'
93            'idle 1800\n'
94            'mtu 1410\n'
95            'mru 1410\n'
96            'nodefaultroute\n'
97            'debug\n'
98            'lock\n'
99            'proxyarp\n'
100    }
101    IPSEC_TYPED_CONFIGS = {
102        'psk': {
103            'etc/ipsec.conf' :
104                'config setup\n'
105                '  charondebug="%(charon-debug-flags)s"\n'
106                'conn L2TP\n'
107                '  keyexchange=ikev1\n'
108                '  authby=psk\n'
109                '  %(xauth-stanza)s\n'
110                '  rekey=no\n'
111                '  left=%(local-ip)s\n'
112                '  leftprotoport=17/1701\n'
113                '  right=%%any\n'
114                '  rightprotoport=17/%%any\n'
115                '  auto=add\n',
116
117            'etc/ipsec.secrets' :
118              '%(local-ip)s %%any : PSK "%(preshared-key)s"\n'
119              '%(xauth-user)s : XAUTH "%(xauth-password)s"\n',
120        },
121        'cert': {
122            'etc/ipsec.conf' :
123                'config setup\n'
124                '  charondebug="%(charon-debug-flags)s"\n'
125                'conn L2TP\n'
126                '  keyexchange=ikev1\n'
127                '  left=%(local-ip)s\n'
128                '  leftcert=server.cert\n'
129                '  leftid="C=US, ST=California, L=Mountain View, '
130                'CN=chromelab-wifi-testbed-server.mtv.google.com"\n'
131                '  leftprotoport=17/1701\n'
132                '  right=%%any\n'
133                '  rightca="C=US, ST=California, L=Mountain View, '
134                'CN=chromelab-wifi-testbed-root.mtv.google.com"\n'
135                '  rightprotoport=17/%%any\n'
136                '  auto=add\n',
137
138            'etc/ipsec.secrets' : ': RSA server.key ""\n',
139
140            IPSEC_SERVER_CERTIFICATE : site_eap_certs.server_cert_1,
141            IPSEC_CA_CERTIFICATE : site_eap_certs.ca_cert_1,
142            'etc/ipsec.d/private/server.key' :
143                site_eap_certs.server_private_key_1,
144        },
145    }
146
147    """Implementation of an L2TP/IPSec server instance."""
148    def __init__(self, auth_type, interface_name, address, network_prefix,
149                 perform_xauth_authentication=False):
150        self._auth_type = auth_type
151        self._chroot = network_chroot.NetworkChroot(interface_name,
152                                                    address, network_prefix)
153        self._perform_xauth_authentication = perform_xauth_authentication
154
155
156    def start_server(self):
157        """Start VPN server instance"""
158        if self._auth_type not in self.IPSEC_TYPED_CONFIGS:
159            raise RuntimeError('L2TP/IPSec type %s is not define' %
160                               self._auth_type)
161        chroot = self._chroot
162        chroot.add_root_directories(self.ROOT_DIRECTORIES)
163        chroot.add_config_templates(self.IPSEC_COMMON_CONFIGS)
164        chroot.add_config_templates(self.IPSEC_TYPED_CONFIGS[self._auth_type])
165        chroot.add_config_values({
166            'chap-user': self.CHAP_USER,
167            'chap-secret': self.CHAP_SECRET,
168            'charon-debug-flags': 'dmn 2, mgr 2, ike 2, net 2',
169            'charon-logfile': self.IPSEC_LOGFILE,
170            'preshared-key': self.IPSEC_PRESHARED_KEY,
171            'xauth-user': self.XAUTH_USER,
172            'xauth-password': self.XAUTH_PASSWORD,
173            'xauth-stanza': self.XAUTH_SECONDARY_AUTHENTICATION_STANZA
174                    if self._perform_xauth_authentication else '',
175        })
176        chroot.add_startup_command('%s start' % self.IPSEC_COMMAND)
177        chroot.add_startup_command('%s -c /%s -C /tmp/l2tpd.control' %
178                                   (self.XL2TPD_COMMAND,
179                                    self.XL2TPD_CONFIG_FILE))
180        self.preload_modules()
181        chroot.startup()
182
183
184    def stop_server(self):
185        """Start VPN server instance"""
186        chroot = self._chroot
187        chroot.run([self.IPSEC_COMMAND, 'stop'], ignore_status=True)
188        chroot.kill_pid_file(self.XL2TPD_PID_FILE, missing_ok=True)
189        chroot.kill_pid_file(self.PPPD_PID_FILE, missing_ok=True)
190        chroot.shutdown()
191
192
193    def get_log_contents(self):
194        """Return all logs related to the chroot."""
195        return self._chroot.get_log_contents()
196
197
198    def preload_modules(self):
199        """Pre-load ipsec modules since they can't be loaded from chroot."""
200        for module in self.PRELOAD_MODULES:
201            utils.system('modprobe %s' % module)
202
203
204class OpenVPNServer(VPNServer):
205    """Implementation of an OpenVPN service."""
206    PRELOAD_MODULES = ('tun',)
207    ROOT_DIRECTORIES = ('etc/openvpn', 'etc/ssl')
208    CA_CERTIFICATE_FILE = 'etc/openvpn/ca.crt'
209    SERVER_CERTIFICATE_FILE = 'etc/openvpn/server.crt'
210    SERVER_KEY_FILE = 'etc/openvpn/server.key'
211    DIFFIE_HELLMAN_FILE = 'etc/openvpn/diffie-hellman.pem'
212    OPENVPN_COMMAND = '/usr/sbin/openvpn'
213    OPENVPN_CONFIG_FILE = 'etc/openvpn/openvpn.conf'
214    OPENVPN_PID_FILE = 'var/run/openvpn.pid'
215    OPENVPN_STATUS_FILE = 'tmp/openvpn.status'
216    AUTHENTICATION_SCRIPT = 'etc/openvpn_authentication_script.sh'
217    EXPECTED_AUTHENTICATION_FILE = 'etc/openvpn_expected_authentication.txt'
218    PASSWORD = 'password'
219    USERNAME = 'username'
220    SERVER_IP_ADDRESS = '10.11.12.1'
221    CONFIGURATION = {
222        'etc/ssl/blacklist' : '',
223        CA_CERTIFICATE_FILE : site_eap_certs.ca_cert_1,
224        SERVER_CERTIFICATE_FILE : site_eap_certs.server_cert_1,
225        SERVER_KEY_FILE : site_eap_certs.server_private_key_1,
226        DIFFIE_HELLMAN_FILE : site_eap_certs.dh1024_pem_key_1,
227        AUTHENTICATION_SCRIPT :
228            '#!/bin/bash\n'
229            'diff -q $1 %(expected-authentication-file)s\n',
230        EXPECTED_AUTHENTICATION_FILE : '%(username)s\n%(password)s\n',
231        OPENVPN_CONFIG_FILE :
232            'ca /%(ca-cert)s\n'
233            'cert /%(server-cert)s\n'
234            'dev tun\n'
235            'dh /%(diffie-hellman-params-file)s\n'
236            'keepalive 10 120\n'
237            'local %(local-ip)s\n'
238            'log /var/log/openvpn.log\n'
239            'ifconfig-pool-persist /tmp/ipp.txt\n'
240            'key /%(server-key)s\n'
241            'persist-key\n'
242            'persist-tun\n'
243            'port 1194\n'
244            'proto udp\n'
245            'server 10.11.12.0 255.255.255.0\n'
246            'status /%(status-file)s\n'
247            'verb 5\n'
248            'writepid /%(pid-file)s\n'
249            '%(optional-user-verification)s\n'
250    }
251
252    def __init__(self, interface_name, address, network_prefix,
253                 perform_username_authentication=False):
254        self._chroot = network_chroot.NetworkChroot(interface_name,
255                                                    address, network_prefix)
256        self._perform_username_authentication = perform_username_authentication
257
258
259    def start_server(self):
260        """Start VPN server instance"""
261        chroot = self._chroot
262        chroot.add_root_directories(self.ROOT_DIRECTORIES)
263        # Create a configuration template from the key-value pairs.
264        chroot.add_config_templates(self.CONFIGURATION)
265        config_values = {
266            'ca-cert': self.CA_CERTIFICATE_FILE,
267            'diffie-hellman-params-file': self.DIFFIE_HELLMAN_FILE,
268            'expected-authentication-file': self.EXPECTED_AUTHENTICATION_FILE,
269            'optional-user-verification': '',
270            'password': self.PASSWORD,
271            'pid-file': self.OPENVPN_PID_FILE,
272            'server-cert': self.SERVER_CERTIFICATE_FILE,
273            'server-key': self.SERVER_KEY_FILE,
274            'status-file': self.OPENVPN_STATUS_FILE,
275            'username': self.USERNAME,
276        }
277        if self._perform_username_authentication:
278            config_values['optional-user-verification'] = (
279                    'auth-user-pass-verify /%s via-file\nscript-security 2' %
280                    self.AUTHENTICATION_SCRIPT)
281        chroot.add_config_values(config_values)
282        chroot.add_startup_command('chmod 755 %s' % self.AUTHENTICATION_SCRIPT)
283        chroot.add_startup_command('%s --config /%s &' %
284                                   (self.OPENVPN_COMMAND,
285                                    self.OPENVPN_CONFIG_FILE))
286        self.preload_modules()
287        chroot.startup()
288
289
290    def preload_modules(self):
291        """Pre-load modules since they can't be loaded from chroot."""
292        for module in self.PRELOAD_MODULES:
293            utils.system('modprobe %s' % module)
294
295
296    def get_log_contents(self):
297        """Return all logs related to the chroot."""
298        return self._chroot.get_log_contents()
299
300
301    def stop_server(self):
302        """Start VPN server instance"""
303        chroot = self._chroot
304        chroot.kill_pid_file(self.OPENVPN_PID_FILE, missing_ok=True)
305        chroot.shutdown()
306