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

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

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

45 46 47
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
48
<dict>
49 50 51 52 53 54 55 56
  <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
57
</dict>
58 59 60
</plist>
'''

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


104 105 106 107 108 109 110
OSX
---

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


111 112 113 114 115 116 117 118 119 120 121 122
Android
-------

Check out the OpenVPN app at http://code.google.com/p/ics-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.


ale's avatar
ale committed
123 124 125 126 127 128 129 130 131 132 133 134 135
References
----------

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

Further info:
%(vpn_site)s


'''


136 137 138
def to_pkcs12(crt_pem, key_pem, ca_pem):
    """Pack credentials into a PKCS12-format buffer."""
    tmpdir = tempfile.mkdtemp()
139
    bundle_pem = '\n'.join([ca_pem, crt_pem])
140
    try:
141
        for name, content in [('bundle.pem', bundle_pem), ('key.pem', key_pem)]:
142
            with open(os.path.join(tmpdir, name), 'w') as fd:
143 144 145
                fd.write(content)
        pipe = subprocess.Popen(
            ['openssl', 'pkcs12', '-export', '-password', 'pass:',
146
             '-in', 'bundle.pem', '-inkey', 'key.pem'],
147 148 149 150 151 152
            cwd=tmpdir, stdout=subprocess.PIPE)
        return pipe.communicate()[0]
    finally:
        shutil.rmtree(tmpdir)


153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
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
168
    @functools.wraps(fn)
169 170 171 172
    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
173
        return fn(*args, **kwargs)
174
    return _auth_wrapper
ale's avatar
ale committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192


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


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
@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
219
def new_cert():
220
    session['dl_ok'] = True
ale's avatar
ale committed
221 222 223 224
    return render_template('download.html')


@vpn_admin.route('/newcertdl')
225 226
@auth
@csrf(methods=['GET'])
ale's avatar
ale committed
227
def new_cert_dl():
228
    if not session.pop('dl_ok', None):
ale's avatar
ale committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
        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,
244 245
            'bundle_identifier': '.'.join(
                current_app.config['VPN_ENDPOINT'].split('.')[::-1]) + '.' + cn,
ale's avatar
ale committed
246 247 248
            'vpn_endpoint': current_app.config['VPN_ENDPOINT'],
            'vpn_site': current_app.config['VPN_SITE_URL'],
            'expiry_date': expiry_date.strftime('%Y/%m/%d')}
249
    ca_pem = g.ca.get_ca()
250 251
    crt_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
252
    pkcs12 = to_pkcs12(crt_pem, key_pem, ca_pem)
ale's avatar
ale committed
253
    manifest = [
254
        ('ca.crt', ca_pem),
255
        ('crl.pem', g.ca.get_crl(format='pem')),
256 257
        ('%s.crt' % cn, crt_pem),
        ('%s.key' % cn, key_pem),
258
        ('%s.pfx' % cn, pkcs12),
ale's avatar
ale committed
259 260
        ('openvpn-%s.conf' % cn, OPENVPN_CONFIG_TEMPLATE % vars),
        ('README.txt', README_TEMPLATE % vars),
261 262

        # Tunnelblick configuration for OSX
263 264 265
        ('%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()),
266
        ('%s.tblk/crl.pem' % cn, g.ca.get_crl(format='pem')),
267 268
        ('%s.tblk/%s.crt' % (cn, cn), crt_pem),
        ('%s.tblk/%s.key' % (cn, cn), key_pem),
ale's avatar
ale committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        ]

    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
285
def make_app(config={}):
ale's avatar
ale committed
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
    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/',
318 319 320 321 322
                  'FOOTER': '''
<p class="footer">
  built by <a href="http://www.autistici.org/">autistici.org</a>
</p>
''',
323 324
                  'AUTH_ENABLE': True,
                  'AUTH_FUNCTION': lambda x, y: (x and y and x == y),
ale's avatar
ale committed
325 326 327
                  }).run(port=4000)
    finally:
        shutil.rmtree(ca_dir)