vpn_app.py 8.41 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12
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, \
13
    render_template, session, g, current_app, url_for
ale's avatar
ale committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

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
References
----------

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

Further info:
%(vpn_site)s


'''


121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
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):
ale's avatar
ale committed
136
    @functools.wraps(fn)
137 138 139 140
    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'))
ale's avatar
ale committed
141
        return fn(*args, **kwargs)
142
    return _auth_wrapper
ale's avatar
ale committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160


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')


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
@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'])
ale's avatar
ale committed
187
def new_cert():
188
    session['dl_ok'] = True
ale's avatar
ale committed
189 190 191 192
    return render_template('download.html')


@vpn_admin.route('/newcertdl')
193 194
@auth
@csrf(methods=['GET'])
ale's avatar
ale committed
195
def new_cert_dl():
196
    if not session.pop('dl_ok', None):
ale's avatar
ale committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        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,
212 213
            'bundle_identifier': '.'.join(
                current_app.config['VPN_ENDPOINT'].split('.')[::-1]) + '.' + cn,
ale's avatar
ale committed
214 215 216
            'vpn_endpoint': current_app.config['VPN_ENDPOINT'],
            'vpn_site': current_app.config['VPN_SITE_URL'],
            'expiry_date': expiry_date.strftime('%Y/%m/%d')}
217 218
    crt_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
ale's avatar
ale committed
219 220
    manifest = [
        ('ca.crt', g.ca.get_ca()),
221
        ('crl.pem', g.ca.get_crl(format='pem')),
222 223
        ('%s.crt' % cn, crt_pem),
        ('%s.key' % cn, key_pem),
ale's avatar
ale committed
224 225
        ('openvpn-%s.conf' % cn, OPENVPN_CONFIG_TEMPLATE % vars),
        ('README.txt', README_TEMPLATE % vars),
226 227

        # Tunnelblick configuration for OSX
228 229 230
        ('%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()),
231
        ('%s.tblk/crl.pem' % cn, g.ca.get_crl(format='pem')),
232 233
        ('%s.tblk/%s.crt' % (cn, cn), crt_pem),
        ('%s.tblk/%s.key' % (cn, cn), key_pem),
ale's avatar
ale committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        ]

    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
250
def make_app(config={}):
ale's avatar
ale committed
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
    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/',
283 284 285 286 287
                  'FOOTER': '''
<p class="footer">
  built by <a href="http://www.autistici.org/">autistici.org</a>
</p>
''',
288 289
                  'AUTH_ENABLE': True,
                  'AUTH_FUNCTION': lambda x, y: (x and y and x == y),
ale's avatar
ale committed
290 291 292
                  }).run(port=4000)
    finally:
        shutil.rmtree(ca_dir)