vpn_app.py 7.4 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
import datetime
import functools
import logging
import os
import uuid
import zipfile
from cStringIO import StringIO
from OpenSSL import crypto
from autoca import ca
from autoca import ca_app
from autoca import ca_stub
from flask import Blueprint, Flask, abort, redirect, request, make_response, \
    render_template, session, g, current_app

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>
ale's avatar
ale committed
31
  remote %(vpn_endpoint)s 443 tcp
ale's avatar
ale committed
32 33 34 35 36 37
</connection>

; SSL configuration.
ca ca.crt
cert %(cn)s.crt
key %(cn)s.key
38
crl-verify crl.pem
ale's avatar
ale committed
39 40 41
ns-cert-type server
'''

42 43 44
TBLK_PLIST_TEMPLATE = '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
ale's avatar
ale committed
45
<dict>
46 47 48 49 50 51 52 53
  <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>
ale's avatar
ale committed
54
</dict>
55 56 57
</plist>
'''

ale's avatar
ale committed
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 94 95 96 97 98 99 100
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
  named openvpn-ai.conf in the same directory as this README)::

    $ 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.


101 102 103 104 105 106 107
OSX
---

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


ale's avatar
ale committed
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 138 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
References
----------

OpenVPN documentation:
http://openvpn.net/index.php/open-source/documentation/

Further info:
%(vpn_site)s


'''


def csrf(fn):
    @functools.wraps(fn)
    def _csrf_wrapper(*args, **kwargs):
        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


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.before_request
def check_userlogin():
    g.username = None
    if 'username' in session:
        g.username = session['username']


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


@vpn_admin.route('/newcert', methods=['POST'])
@csrf
def new_cert():
    session['dl_ok'] = 'y'
    return render_template('download.html')


@vpn_admin.route('/newcertdl')
@csrf
def new_cert_dl():
    if session.pop('dl_ok', None) != 'y':
        return render_template('download_retry.html')

    # Create and sign a certificate.
    cn = str(uuid.uuid4())

    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,
181 182
            'bundle_identifier': '.'.join(
                current_app.config['VPN_ENDPOINT'].split('.')[::-1]) + '.' + cn,
ale's avatar
ale committed
183 184 185
            'vpn_endpoint': current_app.config['VPN_ENDPOINT'],
            'vpn_site': current_app.config['VPN_SITE_URL'],
            'expiry_date': expiry_date.strftime('%Y/%m/%d')}
186 187
    crt_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
ale's avatar
ale committed
188 189
    manifest = [
        ('ca.crt', g.ca.get_ca()),
190
        ('crl.pem', g.ca.get_crl(format='pem')),
191 192
        ('%s.crt' % cn, crt_pem),
        ('%s.key' % cn, key_pem),
ale's avatar
ale committed
193 194
        ('openvpn-%s.conf' % cn, OPENVPN_CONFIG_TEMPLATE % vars),
        ('README.txt', README_TEMPLATE % vars),
195 196

        # Tunnelblick configuration for OSX
197 198 199
        ('%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()),
200
        ('%s.tblk/crl.pem' % cn, g.ca.get_crl(format='pem')),
201 202
        ('%s.tblk/%s.crt' % (cn, cn), crt_pem),
        ('%s.tblk/%s.key' % (cn, cn), key_pem),
ale's avatar
ale committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
        ]

    zbuf = StringIO()
    zf = zipfile.ZipFile(zbuf, mode='w',
                         compression=zipfile.ZIP_DEFLATED)
    for filename, contents in manifest:
        zf.writestr(filename, contents)
    zf.close()
    response = make_response(zbuf.getvalue())
    response.headers['Content-Type'] = 'application/zip'
    response.headers['Content-Disposition'] = (
        'attachment; filename="%s.zip"' % cn)
    response.headers['Cache-control'] = 'private'
    return response


ale's avatar
ale committed
219
def make_app(config={}):
ale's avatar
ale committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    app = Flask(__name__)
    app.config.update(config)
    app.config.from_envvar('VPN_APP_SETTINGS', silent=True)
    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
236 237
    app.jinja_env.globals['footer'] = app.config.get('FOOTER')
    app.jinja_env.globals['help_url'] = app.config.get('HELP_URL')
ale's avatar
ale committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    return app


if __name__ == '__main__':
    # Run a test instance with a standalone HTTP server.
    import tempfile
    import shutil
    ca_dir = tempfile.mkdtemp()
    print 'CA dir:', ca_dir
    try:
        make_app({'DEBUG': 'true',
                  'SECRET_KEY': 'somesecret',
                  'VPN_CA_ROOT': ca_dir,
                  'VPN_CA_SUBJECT': {'CN': 'test CA', 'O': 'test'},
                  'VPN_ENDPOINT': 'vpn.example.com',
                  'VPN_SITE_URL': 'http://localhost:4000/',
254 255 256 257 258 259
                  'HELP_URL': '/help/',
                  'FOOTER': '''
<p class="footer">
  built by <a href="http://www.autistici.org/">autistici.org</a>
</p>
''',
ale's avatar
ale committed
260 261 262
                  }).run(port=4000)
    finally:
        shutil.rmtree(ca_dir)