summaryrefslogtreecommitdiff
path: root/src/leap/gui/firstrun/tests/integration/fake_provider.py
blob: 668db5d1528b49dd3cc0e751ef945bde7dc582e4 (plain)
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
184
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
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
#!/usr/bin/env python
"""A server faking some of the provider resources and apis,
used for testing Leap Client requests

It needs that you create a subfolder named 'certs',
and that you place the following files:

[ ] certs/leaptestscert.pem
[ ] certs/leaptestskey.pem
[ ] certs/cacert.pem
[ ] certs/openvpn.pem

[ ] provider.json
[ ] eip-service.json
"""
# XXX NOTE: intended for manual debug.
# I intend to include this as a regular test after 0.2.0 release
# (so we can add twisted as a dep there)
import binascii
import json
import os
import sys

# python SRP LIB (! important MUST be >=1.0.1 !)
import srp

# GnuTLS Example -- is not working as expected
#from gnutls import crypto
#from gnutls.constants import COMP_LZO, COMP_DEFLATE, COMP_NULL
#from gnutls.interfaces.twisted import X509Credentials

# Going with OpenSSL as a workaround instead
# But we DO NOT want to introduce this dependency.
from OpenSSL import SSL

from zope.interface import Interface, Attribute, implements

from twisted.web.server import Site
from twisted.web.static import File
from twisted.web.resource import Resource
from twisted.internet import reactor

from leap.testing.https_server import where

# See
# http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.htmln
# for more examples

"""
Testing the FAKE_API:
#####################

 1) register an user
 >> curl -d "user[login]=me" -d "user[password_salt]=foo" \
         -d "user[password_verifier]=beef" http://localhost:8000/1/users.json
 << {"errors": null}

 2) check that if you try to register again, it will fail:
 >> curl -d "user[login]=me" -d "user[password_salt]=foo" \
         -d "user[password_verifier]=beef" http://localhost:8000/1/users.json
 << {"errors": {"login": "already taken!"}}

"""

# Globals to mock user/sessiondb

USERDB = {}
SESSIONDB = {}


safe_unhexlify = lambda x: binascii.unhexlify(x) \
    if (len(x) % 2 == 0) else binascii.unhexlify('0' + x)


class IUser(Interface):
    login = Attribute("User login.")
    salt = Attribute("Password salt.")
    verifier = Attribute("Password verifier.")
    session = Attribute("Session.")
    svr = Attribute("Server verifier.")


class User(object):
    implements(IUser)

    def __init__(self, login, salt, verifier):
        self.login = login
        self.salt = salt
        self.verifier = verifier
        self.session = None

    def set_server_verifier(self, svr):
        self.svr = svr

    def set_session(self, session):
        SESSIONDB[session] = self
        self.session = session


class FakeUsers(Resource):
    def __init__(self, name):
        self.name = name

    def render_POST(self, request):
        args = request.args

        login = args['user[login]'][0]
        salt = args['user[password_salt]'][0]
        verifier = args['user[password_verifier]'][0]

        if login in USERDB:
            return "%s\n" % json.dumps(
                {'errors': {'login': 'already taken!'}})

        print login, verifier, salt
        user = User(login, salt, verifier)
        USERDB[login] = user
        return json.dumps({'errors': None})


def get_user(request):
    login = request.args.get('login')
    if login:
        user = USERDB.get(login[0], None)
        if user:
            return user

    session = request.getSession()
    user = SESSIONDB.get(session, None)
    return user


class FakeSession(Resource):
    def __init__(self, name):
        self.name = name

    def render_GET(self, request):
        return "%s\n" % json.dumps({'errors': None})

    def render_POST(self, request):

        user = get_user(request)

        if not user:
            # XXX get real error from demo provider
            return json.dumps({'errors': 'no such user'})

        A = request.args['A'][0]

        _A = safe_unhexlify(A)
        _salt = safe_unhexlify(user.salt)
        _verifier = safe_unhexlify(user.verifier)

        svr = srp.Verifier(
            user.login,
            _salt,
            _verifier,
            _A,
            hash_alg=srp.SHA256,
            ng_type=srp.NG_1024)

        s, B = svr.get_challenge()

        _B = binascii.hexlify(B)

        print 'login = %s' % user.login
        print 'salt = %s' % user.salt
        print 'len(_salt) = %s' % len(_salt)
        print 'vkey = %s' % user.verifier
        print 'len(vkey) = %s' % len(_verifier)
        print 's = %s' % binascii.hexlify(s)
        print 'B = %s' % _B
        print 'len(B) = %s' % len(_B)

        session = request.getSession()
        user.set_session(session)
        user.set_server_verifier(svr)

        # yep, this is tricky.
        # some things are *already* unhexlified.
        data = {
            'salt': user.salt,
            'B': _B,
            'errors': None}

        return json.dumps(data)

    def render_PUT(self, request):

        # XXX check session???
        user = get_user(request)

        if not user:
            print 'NO USER'
            return json.dumps({'errors': 'no such user'})

        data = request.content.read()
        auth = data.split("client_auth=")
        M = auth[1] if len(auth) > 1 else None
        # if not H, return
        if not M:
            return json.dumps({'errors': 'no M proof passed by client'})

        svr = user.svr
        HAMK = svr.verify_session(binascii.unhexlify(M))
        if HAMK is None:
            print 'verification failed!!!'
            raise Exception("Authentication failed!")
            #import ipdb;ipdb.set_trace()

        assert svr.authenticated()
        print "***"
        print 'server authenticated user SRP!'
        print "***"

        return json.dumps(
            {'M2': binascii.hexlify(HAMK), 'errors': None})


class API_Sessions(Resource):
    def getChild(self, name, request):
        return FakeSession(name)


def get_certs_path():
    script_path = os.path.realpath(os.path.dirname(sys.argv[0]))
    certs_path = os.path.join(script_path, 'certs')
    return certs_path


def get_TLS_credentials():
    # XXX this is giving errors
    # XXX REview! We want to use gnutls!

    cert = crypto.X509Certificate(
        open(where('leaptestscert.pem')).read())
    key = crypto.X509PrivateKey(
        open(where('leaptestskey.pem')).read())
    ca = crypto.X509Certificate(
        open(where('cacert.pem')).read())
    #crl = crypto.X509CRL(open(certs_path + '/crl.pem').read())
    #cred = crypto.X509Credentials(cert, key, [ca], [crl])
    cred = X509Credentials(cert, key, [ca])
    cred.verify_peer = True
    cred.session_params.compressions = (COMP_LZO, COMP_DEFLATE, COMP_NULL)
    return cred


class OpenSSLServerContextFactory:
    # XXX workaround for broken TLS interface
    # from gnuTLS.

    def getContext(self):
        """Create an SSL context.
        This is a sample implementation that loads a certificate from a file
        called 'server.pem'."""

        ctx = SSL.Context(SSL.SSLv23_METHOD)
        #certs_path = get_certs_path()
        #ctx.use_certificate_file(certs_path + '/leaptestscert.pem')
        #ctx.use_privatekey_file(certs_path + '/leaptestskey.pem')
        ctx.use_certificate_file(where('leaptestscert.pem'))
        ctx.use_privatekey_file(where('leaptestskey.pem'))
        return ctx


def serve_fake_provider():
    root = Resource()
    root.putChild("provider.json", File("./provider.json"))
    config = Resource()
    config.putChild(
        "eip-service.json",
        File("./eip-service.json"))
    apiv1 = Resource()
    apiv1.putChild("config", config)
    apiv1.putChild("sessions.json", API_Sessions())
    apiv1.putChild("users.json", FakeUsers(None))
    apiv1.putChild("cert", File(get_certs_path() + '/openvpn.pem'))
    root.putChild("1", apiv1)

    cred = get_TLS_credentials()

    factory = Site(root)

    # regular http (for debugging with curl)
    reactor.listenTCP(8000, factory)

    # TLS with gnutls --- seems broken :(
    #reactor.listenTLS(8003, factory, cred)

    # OpenSSL
    reactor.listenSSL(8443, factory, OpenSSLServerContextFactory())

    reactor.run()


if __name__ == "__main__":

    from twisted.python import log
    log.startLogging(sys.stdout)

    serve_fake_provider()