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