vpn_app.py 12.7 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import datetime
import functools
import itsdangerous
import logging
import os
import shutil
import subprocess
import tempfile
import threading
import time
import uuid
import zipfile
from cStringIO import StringIO
from OpenSSL import crypto
from flask import Blueprint, Flask, abort, redirect, request, make_response, \
    render_template, session, g, current_app, url_for

from autoca import ca
from autoca import ca_app
from autoca import ca_stub

vpn_admin = Blueprint('vpn_admin', __name__)
log = logging.getLogger(__name__)

OPENVPN_CONFIG_TEMPLATE = '''
client
dev tun
resolv-retry infinite
nobind
persist-key
persist-tun

<connection>
  remote %(vpn_endpoint)s 1194 udp
</connection>

<connection>
  remote %(vpn_endpoint)s 443 tcp
</connection>

; SSL configuration.
ca ca.crt
cert %(cn)s.crt
key %(cn)s.key
crl-verify crl.pem
ns-cert-type server
tls-auth tlsauth.key 1
48
49
50
51
auth SHA512
cipher AES-256-CBC
tls-version-min 1.2 or-highest
tls-cipher TLS-DHE-RSA-WITH-AES-256-GCM-SHA384
ale's avatar
ale committed
52
53
54
'''

TBLK_PLIST_TEMPLATE = '''<?xml version="1.0" encoding="UTF-8"?>
godog's avatar
godog committed
55
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
ale's avatar
ale committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<plist version="1.0">
<dict>
  <key>CFBundleIdentifier</key>
  <string>%(bundle_identifier)s</string>
  <key>CFBundleVersion</key>
  <string>1</string>
  <key>TBPackageVersion</key>
  <string>1</string>
  <key>TBSharePackage</key>
  <string>private</string>
</dict>
</plist>
'''

README_TEMPLATE = '''
VPN client configuration
========================

The ZIP file you just got contains an SSL certificate (and private
key) used to authenticate to the VPN network.  This file is very
sensitive, keep it in a safe place.

The certificate will expire on %(expiry_date)s. Go back to where you got the
ZIP file in the first place to obtain another one.

The specific instructions to install the VPN connection on your device
may vary depending on your OS, some examples follow.  Refer to the
official OpenVPN documentation for further information.


Linux (without NetworkManager)
------------------------------

- Install OpenVPN, i.e. on a Debian-based system::

    $ sudo apt-get install openvpn

- Start the VPN connection by pointing openvpn at your config (the file
94
  named openvpn-%(cn)s.conf in the same directory as this README)::
ale's avatar
ale committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137

    $ sudo openvpn --config openvpn-%(cn)s.conf


Linux (with NetworkManager)
---------------------------

If you are using NetworkManager to configure your network connections,
you are probably better off having it deal with OpenVPN itself.  A
NetworkManager plugin exists for this purpose::

    $ sudo apt-get install network-manager-openvpn-gnome

You can then configure the VPN using NetworkManager itself, use
"Certificates (TLS)" as the Authentication Type, and use the
certificates contained in this ZIP file.


OSX
---

The ZIP file contains a configuration for Tunnelblick. Double-click
on it and it will install itself automatically.


Android
-------

Check out the OpenVPN app at
https://play.google.com/store/apps/details?id=de.blinkt.openvpn

To use it:

- Select the PKCS12 format for the credentials and select the
  <uuid>.pfx file from the ZIP archive.

- Ensure that LZO compression is disabled.


References
----------

OpenVPN documentation:
godog's avatar
godog committed
138
https://openvpn.net/index.php/open-source/documentation/
ale's avatar
ale committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

Further info:
%(vpn_site)s


'''


class Singleton(object):
    """Singleton with deferred instantiation."""

    def __init__(self, cls):
        self.lock = threading.Lock()
        self.obj = None
        self.cls = cls

    def __call__(self, *args):
        with self.lock:
            if self.obj is None:
                self.obj = self.cls(*args)
            return self.obj


class Signer(object):
    """Generates secure download tokens that are valid for a few seconds."""

    TIMEOUT = 60

    def __init__(self, secret):
        self.l = threading.local()
        self.secret = secret

    def _signer(self):
        if not hasattr(self.l, 'signer'):
            self.l.signer = itsdangerous.URLSafeTimedSerializer(self.secret, salt='cn')
        return self.l.signer

    def encode(self, cn):
        return self._signer().dumps(cn)

    def decode(self, token):
        return self._signer().loads(token, max_age=self.TIMEOUT)


class ZipCacheCleanupThread(threading.Thread):

    EXPIRE_TIME = 120

    def __init__(self, root):
        threading.Thread.__init__(self)
        self.root = root
        self.setDaemon(True)
        self.start()

    def purge_cached_files(self):
        cutoff = self.EXPIRE_TIME
        now = time.time()
        for f in os.listdir(self.root):
            if f.startswith('.') or not f.endswith('.zip'):
                continue
            fp = os.path.join(self.root, f)
200
            mtime = os.path.getmtime(fp)
ale's avatar
ale committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
            if (now - mtime) > cutoff:
                os.unlink(fp)

    def run(self):
        while True:
            time.sleep(60)
            try:
                self.purge_cached_files()
            except:
                pass


class ZipCache(object):
    """A simple on-disk cache of recent zip files."""

    cleanup_thread = Singleton(ZipCacheCleanupThread)

    def __init__(self, root):
        self.root = root
        self.cleanup = self.cleanup_thread(root)

    def _path(self, cn):
        return os.path.join(self.root, cn + '.zip')

    def get(self, cn):
        try:
            with open(self._path(cn), 'r') as fd:
                return fd.read()
        except:
            return None

    def put(self, cn, contents):
        with open(self._path(cn), 'w') as fd:
            fd.write(contents)


def to_pkcs12(crt_pem, key_pem, ca_pem):
    """Pack credentials into a PKCS12-format buffer."""
    tmpdir = tempfile.mkdtemp()
    bundle_pem = '\n'.join([ca_pem, crt_pem])
    try:
        for name, content in [('bundle.pem', bundle_pem), ('key.pem', key_pem)]:
            with open(os.path.join(tmpdir, name), 'w') as fd:
                fd.write(content)
        pipe = subprocess.Popen(
            ['openssl', 'pkcs12', '-export', '-password', 'pass:',
             '-in', 'bundle.pem', '-inkey', 'key.pem'],
            cwd=tmpdir, stdout=subprocess.PIPE)
        return pipe.communicate()[0]
    finally:
        shutil.rmtree(tmpdir)


def csrf(methods=('POST',)):
    def _csrf(fn):
        @functools.wraps(fn)
        def _csrf_wrapper(*args, **kwargs):
            if request.method in methods:
                query_args = (request.method == 'POST') and request.form or request.args
                token = session.pop('_csrf', None)
                if not token or token != query_args.get('_csrf'):
                    abort(400)
            return fn(*args, **kwargs)
        return _csrf_wrapper
    return _csrf


def auth(fn):
    @functools.wraps(fn)
    def _auth_wrapper(*args, **kwargs):
        if current_app.config.get('AUTH_ENABLE'):
            if not session.get('logged_in'):
                return redirect(url_for('vpn_admin.login'))
        return fn(*args, **kwargs)
    return _auth_wrapper


def generate_csrf_token():
    if '_csrf' not in session:
        session['_csrf'] = os.urandom(18).encode('base64').rstrip()
    return session['_csrf']


@vpn_admin.before_request
def set_ca_wrapper():
    g.ca = current_app.ca


@vpn_admin.route('/')
def index():
    return render_template('index.html')


@vpn_admin.route('/login', methods=['GET', 'POST'])
@csrf()
def login():
    error = None
    username = ''
    if request.method == 'POST':
        username = request.form.get('username', '')
        password = request.form.get('password', '')
        if current_app.config['AUTH_FUNCTION'](username, password):
            session['logged_in'] = True
            return redirect(url_for('vpn_admin.new_cert',
                                    _csrf=generate_csrf_token()))
        else:
            error = 'Authentication failed'
    return render_template('login.html', error=error, username=username)


@vpn_admin.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('vpn_admin.index'))


@vpn_admin.route('/newcert', methods=['GET', 'POST'])
@auth
@csrf(methods=['GET', 'POST'])
def new_cert():
    cn = str(uuid.uuid4())
    cn_token = current_app.signer.encode(cn)
    return render_template('download.html', cn_token=cn_token)


@vpn_admin.route('/newcertdl')
@auth
@csrf(methods=['GET'])
def new_cert_dl():
    # Retrieve CN from the signed token.
    try:
        cn = current_app.signer.decode(request.args.get('t'))
    except:
        return render_template('download_retry.html')

    # Check if the certificate is new or not, so that the user can
    # perform multiple downloads of the same certificate / private
    # keypair until the token is valid.
    zip_data = current_app.zipcache.get(cn)
    if not zip_data:

        # Create and sign the new certificate.
        validity = int(current_app.config.get('VPN_CERT_VALIDITY', 7))
        expiry_date = datetime.date.today() + datetime.timedelta(validity)

        subject = current_app.config.get('VPN_DEFAULT_SUBJECT_ATTRS', {}).copy()
        subject['CN'] = cn

        pkey, cert = g.ca.make_certificate(subject, days=validity)

        # Create the zipfile in-memory, with all the files the user needs.
        vars = {'cn': cn,
                'bundle_identifier': '.'.join(
                current_app.config['VPN_ENDPOINT'].split('.')[::-1]) + '.' + cn,
                'vpn_endpoint': current_app.config['VPN_ENDPOINT'],
                'vpn_site': current_app.config['VPN_SITE_URL'],
                'expiry_date': expiry_date.strftime('%Y/%m/%d')}
        ca_pem = g.ca.get_ca()
        crt_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
        key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
        pkcs12 = to_pkcs12(crt_pem, key_pem, ca_pem)
        manifest = [
            ('ca.crt', ca_pem),
            ('crl.pem', g.ca.get_crl(format='pem')),
            ('%s.crt' % cn, crt_pem),
            ('%s.key' % cn, key_pem),
            ('%s.pfx' % cn, pkcs12),
            ('tlsauth.key', current_app.config['TLS_AUTH_KEY']),
godog's avatar
godog committed
369
            ('%s.ovpn' % cn, OPENVPN_CONFIG_TEMPLATE % vars),
ale's avatar
ale committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
            ('README.txt', README_TEMPLATE % vars),

            # Tunnelblick configuration for OSX
            ('%s.tblk/Info.plist' % cn, TBLK_PLIST_TEMPLATE % vars),
            ('%s.tblk/config.ovpn' % cn, OPENVPN_CONFIG_TEMPLATE % vars),
            ('%s.tblk/ca.crt' % cn, g.ca.get_ca()),
            ('%s.tblk/crl.pem' % cn, g.ca.get_crl(format='pem')),
            ('%s.tblk/%s.crt' % (cn, cn), crt_pem),
            ('%s.tblk/%s.key' % (cn, cn), key_pem),
            ('%s.tblk/tlsauth.key' % cn, current_app.config['TLS_AUTH_KEY']),
            ]

        zbuf = StringIO()
        zf = zipfile.ZipFile(zbuf, mode='w',
                             compression=zipfile.ZIP_DEFLATED)
        for filename, contents in manifest:
            zf.writestr(filename, contents)
        zf.close()
        zip_data = zbuf.getvalue()

        current_app.zipcache.put(cn, zip_data)

    response = make_response(zip_data)
    response.headers['Content-Type'] = 'application/zip'
    response.headers['Content-Disposition'] = (
        'attachment; filename="%s.zip"' % cn)
    response.headers['Cache-control'] = 'private'
    return response


def make_app(config={}):
    app = Flask(__name__)
    app.config.update(config)
    app.config.from_envvar('APP_CONFIG', silent=True)
    app.signer = Signer(app.config['SIGNER_SECRET'])
    app.zipcache = ZipCache(app.config['CACHE_DIR'])
    app.register_blueprint(vpn_admin)

    # Figure out how to hook to the CA.
    if app.config.get('VPN_CA_URL'):
        app.ca = ca_stub.CaStub(app.config['VPN_CA_URL'],
                                app.config.get('CA_SHARED_SECRET'))
    else:
        app.ca = ca.CA(app.config['VPN_CA_ROOT'],
                       app.config['VPN_CA_SUBJECT'],
                       int(app.config.get('VPN_CA_BITS', 4096)))
        app.register_blueprint(ca_app.ca_app, url_prefix='/ca')

    app.jinja_env.globals['csrf_token'] = generate_csrf_token
    return app


if __name__ == '__main__':
    # Run a test instance with a standalone HTTP server.
    ca_dir = tempfile.mkdtemp()
    print 'CA dir:', ca_dir
    try:
        make_app({'DEBUG': 'true',
                  'SECRET_KEY': 'somesecret',
                  'SIGNER_SECRET': 'moresecrets',
                  'VPN_CA_ROOT': ca_dir,
                  'VPN_CA_SUBJECT': {'CN': 'test CA', 'O': 'test'},
                  'VPN_ENDPOINT': 'vpn.example.com',
                  'VPN_SITE_URL': 'http://localhost:4000/',
                  'FOOTER': '''
<p class="footer">
godog's avatar
godog committed
436
  built by <a href="https://www.autistici.org/">autistici.org</a>
ale's avatar
ale committed
437
438
439
440
441
442
443
444
</p>
''',
                  'AUTH_ENABLE': True,
                  'AUTH_FUNCTION': lambda x, y: (x and y and x == y),
                  'CACHE_DIR': 'cache',
                  }).run(port=4000)
    finally:
        shutil.rmtree(ca_dir)