vpn_app.py 5.96 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 48 49 50 51 52 53 54 55 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 94 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 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 181 182 183
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>
  remove %(vpn_endpoint)s 443 tcp
</connection>

; SSL configuration.
ca ca.crt
cert %(cn)s.crt
key %(cn)s.key
ns-cert-type server
'''

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.


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,
            'vpn_endpoint': current_app.config['VPN_ENDPOINT'],
            'vpn_site': current_app.config['VPN_SITE_URL'],
            'expiry_date': expiry_date.strftime('%Y/%m/%d')}
    manifest = [
        ('ca.crt', g.ca.get_ca()),
        ('%s.crt' % cn, 
         crypto.dump_certificate(crypto.FILETYPE_PEM, cert)),
        ('%s.key' % cn,
         crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)),
        ('openvpn-%s.conf' % cn, OPENVPN_CONFIG_TEMPLATE % vars),
        ('README.txt', README_TEMPLATE % vars),
        ]

    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
184
def make_app(config={}):
ale's avatar
ale committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    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
    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/',
                  }).run(port=4000)
    finally:
        shutil.rmtree(ca_dir)