From 5ff29dc57e2877a14e705d09b7042cddf4165d0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 6 Mar 2013 15:27:23 -0300 Subject: Remove everything to start from scratch --- src/leap/crypto/__init__.py | 0 src/leap/crypto/certs.py | 112 ------------------------------------ src/leap/crypto/certs_gnutls.py | 112 ------------------------------------ src/leap/crypto/leapkeyring.py | 70 ---------------------- src/leap/crypto/tests/__init__.py | 0 src/leap/crypto/tests/test_certs.py | 22 ------- 6 files changed, 316 deletions(-) delete mode 100644 src/leap/crypto/__init__.py delete mode 100644 src/leap/crypto/certs.py delete mode 100644 src/leap/crypto/certs_gnutls.py delete mode 100644 src/leap/crypto/leapkeyring.py delete mode 100644 src/leap/crypto/tests/__init__.py delete mode 100644 src/leap/crypto/tests/test_certs.py (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/__init__.py b/src/leap/crypto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leap/crypto/certs.py b/src/leap/crypto/certs.py deleted file mode 100644 index cbb5725a..00000000 --- a/src/leap/crypto/certs.py +++ /dev/null @@ -1,112 +0,0 @@ -import logging -import os -from StringIO import StringIO -import ssl -import time - -from dateutil.parser import parse -from OpenSSL import crypto - -from leap.util.misc import null_check - -logger = logging.getLogger(__name__) - - -class BadCertError(Exception): - """ - raised for malformed certs - """ - - -class NoCertError(Exception): - """ - raised for cert not found in given path - """ - - -def get_https_cert_from_domain(domain, port=443): - """ - @param domain: a domain name to get a certificate from. - """ - cert = ssl.get_server_certificate((domain, port)) - x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert) - return x509 - - -def get_cert_from_file(_file): - null_check(_file, "pem file") - if isinstance(_file, (str, unicode)): - if not os.path.isfile(_file): - raise NoCertError - with open(_file) as f: - cert = f.read() - else: - cert = _file.read() - x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert) - return x509 - - -def get_pkey_from_file(_file): - getkey = lambda f: crypto.load_privatekey( - crypto.FILETYPE_PEM, f.read()) - - if isinstance(_file, str): - with open(_file) as f: - key = getkey(f) - else: - key = getkey(_file) - return key - - -def can_load_cert_and_pkey(string): - """ - loads certificate and private key from - a buffer - """ - try: - f = StringIO(string) - cert = get_cert_from_file(f) - - f = StringIO(string) - key = get_pkey_from_file(f) - - null_check(cert, 'certificate') - null_check(key, 'private key') - except Exception as exc: - logger.error(type(exc), exc.message) - raise BadCertError - else: - return True - - -def get_cert_fingerprint(domain=None, port=443, filepath=None, - hash_type="SHA256", sep=":"): - """ - @param domain: a domain name to get a fingerprint from - @type domain: str - @param filepath: path to a file containing a PEM file - @type filepath: str - @param hash_type: the hash function to be used in the fingerprint. - must be one of SHA1, SHA224, SHA256, SHA384, SHA512 - @type hash_type: str - @rparam: hex_fpr, a hexadecimal representation of a bytestring - containing the fingerprint. - @rtype: string - """ - if domain: - cert = get_https_cert_from_domain(domain, port=port) - if filepath: - cert = get_cert_from_file(filepath) - hex_fpr = cert.digest(hash_type) - return hex_fpr - - -def get_time_boundaries(certfile): - cert = get_cert_from_file(certfile) - null_check(cert, 'certificate') - - fromts, tots = (cert.get_notBefore(), cert.get_notAfter()) - from_, to_ = map( - lambda ts: time.gmtime(time.mktime(parse(ts).timetuple())), - (fromts, tots)) - return from_, to_ diff --git a/src/leap/crypto/certs_gnutls.py b/src/leap/crypto/certs_gnutls.py deleted file mode 100644 index 20c0e043..00000000 --- a/src/leap/crypto/certs_gnutls.py +++ /dev/null @@ -1,112 +0,0 @@ -''' -We're using PyOpenSSL now - -import ctypes -from StringIO import StringIO -import socket - -import gnutls.connection -import gnutls.crypto -import gnutls.library - -from leap.util.misc import null_check - - -class BadCertError(Exception): - """raised for malformed certs""" - - -def get_https_cert_from_domain(domain): - """ - @param domain: a domain name to get a certificate from. - """ - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - cred = gnutls.connection.X509Credentials() - - session = gnutls.connection.ClientSession(sock, cred) - session.connect((domain, 443)) - session.handshake() - cert = session.peer_certificate - return cert - - -def get_cert_from_file(_file): - getcert = lambda f: gnutls.crypto.X509Certificate(f.read()) - if isinstance(_file, str): - with open(_file) as f: - cert = getcert(f) - else: - cert = getcert(_file) - return cert - - -def get_pkey_from_file(_file): - getkey = lambda f: gnutls.crypto.X509PrivateKey(f.read()) - if isinstance(_file, str): - with open(_file) as f: - key = getkey(f) - else: - key = getkey(_file) - return key - - -def can_load_cert_and_pkey(string): - try: - f = StringIO(string) - cert = get_cert_from_file(f) - - f = StringIO(string) - key = get_pkey_from_file(f) - - null_check(cert, 'certificate') - null_check(key, 'private key') - except: - # XXX catch GNUTLSError? - raise BadCertError - else: - return True - -def get_cert_fingerprint(domain=None, filepath=None, - hash_type="SHA256", sep=":"): - """ - @param domain: a domain name to get a fingerprint from - @type domain: str - @param filepath: path to a file containing a PEM file - @type filepath: str - @param hash_type: the hash function to be used in the fingerprint. - must be one of SHA1, SHA224, SHA256, SHA384, SHA512 - @type hash_type: str - @rparam: hex_fpr, a hexadecimal representation of a bytestring - containing the fingerprint. - @rtype: string - """ - if domain: - cert = get_https_cert_from_domain(domain) - if filepath: - cert = get_cert_from_file(filepath) - - _buffer = ctypes.create_string_buffer(64) - buffer_length = ctypes.c_size_t(64) - - SUPPORTED_DIGEST_FUN = ("SHA1", "SHA224", "SHA256", "SHA384", "SHA512") - if hash_type in SUPPORTED_DIGEST_FUN: - digestfunction = getattr( - gnutls.library.constants, - "GNUTLS_DIG_%s" % hash_type) - else: - # XXX improperlyconfigured or something - raise Exception("digest function not supported") - - gnutls.library.functions.gnutls_x509_crt_get_fingerprint( - cert._c_object, digestfunction, - ctypes.byref(_buffer), ctypes.byref(buffer_length)) - - # deinit - #server_cert._X509Certificate__deinit(server_cert._c_object) - # needed? is segfaulting - - fpr = ctypes.string_at(_buffer, buffer_length.value) - hex_fpr = sep.join(u"%02X" % ord(char) for char in fpr) - - return hex_fpr -''' diff --git a/src/leap/crypto/leapkeyring.py b/src/leap/crypto/leapkeyring.py deleted file mode 100644 index c241d0bc..00000000 --- a/src/leap/crypto/leapkeyring.py +++ /dev/null @@ -1,70 +0,0 @@ -import keyring - -from leap.base.config import get_config_file - -############# -# Disclaimer -############# -# This currently is not a keyring, it's more like a joke. -# No, seriously. -# We're affected by this **bug** - -# https://bitbucket.org/kang/python-keyring-lib/ -# issue/65/dbusexception-method-opensession-with - -# so using the gnome keyring does not seem feasible right now. -# I thought this was the next best option to store secrets in plain sight. - -# in the future we should move to use the gnome/kde/macosx/win keyrings. - - -class LeapCryptedFileKeyring(keyring.backend.CryptedFileKeyring): - - filename = ".secrets" - - @property - def file_path(self): - return get_config_file(self.filename) - - def __init__(self, seed=None): - self.seed = seed - - def _get_new_password(self): - # XXX every time this method is called, - # $deity kills a kitten. - return "secret%s" % self.seed - - def _init_file(self): - self.keyring_key = self._get_new_password() - self.set_password('keyring_setting', 'pass_ref', 'pass_ref_value') - - def _unlock(self): - self.keyring_key = self._get_new_password() - print 'keyring key ', self.keyring_key - try: - ref_pw = self.get_password( - 'keyring_setting', - 'pass_ref') - print 'ref pw ', ref_pw - assert ref_pw == "pass_ref_value" - except AssertionError: - self._lock() - raise ValueError('Incorrect password') - - -def leap_set_password(key, value, seed="xxx"): - key, value = map(unicode, (key, value)) - keyring.set_keyring(LeapCryptedFileKeyring(seed=seed)) - keyring.set_password('leap', key, value) - - -def leap_get_password(key, seed="xxx"): - keyring.set_keyring(LeapCryptedFileKeyring(seed=seed)) - #import ipdb;ipdb.set_trace() - return keyring.get_password('leap', key) - - -if __name__ == "__main__": - leap_set_password('test', 'bar') - passwd = leap_get_password('test') - assert passwd == 'bar' diff --git a/src/leap/crypto/tests/__init__.py b/src/leap/crypto/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leap/crypto/tests/test_certs.py b/src/leap/crypto/tests/test_certs.py deleted file mode 100644 index e476b630..00000000 --- a/src/leap/crypto/tests/test_certs.py +++ /dev/null @@ -1,22 +0,0 @@ -import unittest - -from leap.testing.https_server import where -from leap.crypto import certs - - -class CertTestCase(unittest.TestCase): - - def test_can_load_client_and_pkey(self): - with open(where('leaptestscert.pem')) as cf: - cs = cf.read() - with open(where('leaptestskey.pem')) as kf: - ks = kf.read() - certs.can_load_cert_and_pkey(cs + ks) - - with self.assertRaises(certs.BadCertError): - # screw header - certs.can_load_cert_and_pkey(cs.replace("BEGIN", "BEGINN") + ks) - - -if __name__ == "__main__": - unittest.main() -- cgit v1.2.3 From 97554d4c413dd60be4ed67c9553cb0976ce420b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 6 Mar 2013 15:37:07 -0300 Subject: Add SRP related code: authentication and registration --- src/leap/crypto/__init__.py | 0 src/leap/crypto/constants.py | 18 ++ src/leap/crypto/srpauth.py | 439 +++++++++++++++++++++++++++++++++++++++++ src/leap/crypto/srpregister.py | 154 +++++++++++++++ 4 files changed, 611 insertions(+) create mode 100644 src/leap/crypto/__init__.py create mode 100644 src/leap/crypto/constants.py create mode 100644 src/leap/crypto/srpauth.py create mode 100644 src/leap/crypto/srpregister.py (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/__init__.py b/src/leap/crypto/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/leap/crypto/constants.py b/src/leap/crypto/constants.py new file mode 100644 index 00000000..c5eaef1f --- /dev/null +++ b/src/leap/crypto/constants.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# constants.py +# Copyright (C) 2013 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +SIGNUP_TIMEOUT = 5 diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py new file mode 100644 index 00000000..dbcc95cb --- /dev/null +++ b/src/leap/crypto/srpauth.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# srpauth.py +# Copyright (C) 2013 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import requests +import srp +import binascii +import logging + +from PySide import QtCore + +from leap.config.providerconfig import ProviderConfig + +logger = logging.getLogger(__name__) + + +class SRPAuthenticationError(Exception): + """ + Exception raised for authentication errors + """ + pass + + +class SRPAuth(QtCore.QThread): + """ + SRPAuth singleton + """ + + class __impl(object): + """ + Implementation of the SRPAuth interface + """ + + LOGIN_KEY = "login" + A_KEY = "A" + CLIENT_AUTH_KEY = "client_auth" + + def __init__(self, provider_config): + """ + Constructor for SRPAuth implementation + + @param server: Server to which we will authenticate + @type server: str + """ + assert provider_config, "We need a provider config to authenticate" + + self._provider_config = provider_config + + # **************************************************** # + # Dependency injection helpers, override this for more + # granular testing + self._fetcher = requests + self._srp = srp + self._hashfun = self._srp.SHA256 + self._ng = self._srp.NG_1024 + # **************************************************** # + + self._session = self._fetcher.session() + self._session_id = None + self._session_id_lock = QtCore.QMutex() + self._uid = None + self._uid_lock = QtCore.QMutex() + + self._srp_user = None + self._srp_a = None + + def _safe_unhexlify(self, val): + """ + Rounds the val to a multiple of 2 and returns the + unhexlified value + + @param val: hexlified value + @type val: str + + @rtype: binary hex data + @return: unhexlified val + """ + return binascii.unhexlify(val) \ + if (len(val) % 2 == 0) else binascii.unhexlify('0' + val) + + def _authentication_preprocessing(self, username, password): + """ + Generates the SRP.User to get the A SRP parameter + + @param username: username to login + @type username: str + @param password: password for the username + @type password: str + """ + logger.debug("Authentication preprocessing...") + self._srp_user = self._srp.User(username, + password, + self._hashfun, + self._ng) + _, A = self._srp_user.start_authentication() + + self._srp_a = A + + def _start_authentication(self, username, password): + """ + Sends the first request for authentication to retrieve the + salt and B parameter + + Might raise SRPAuthenticationError + + @param username: username to login + @type username: str + @param password: password for the username + @type password: str + + @return: salt and B parameters + @rtype: tuple + """ + logger.debug("Starting authentication process...") + try: + auth_data = { + self.LOGIN_KEY: username, + self.A_KEY: binascii.hexlify(self._srp_a) + } + sessions_url = "%s/%s/%s/" % \ + (self._provider_config.get_api_uri(), + self._provider_config.get_api_version(), + "sessions") + init_session = self._session.post(sessions_url, + data=auth_data, + verify=self._provider_config. + get_ca_cert_path()) + except requests.exceptions.ConnectionError as e: + logger.error("No connection made (salt): %r" % + (e,)) + raise SRPAuthenticationError("Could not establish a " + "connection") + except Exception as e: + logger.error("Unknown error: %r" % (e,)) + raise SRPAuthenticationError("Unknown error: %r" % + (e,)) + + if init_session.status_code not in (200,): + logger.error("No valid response (salt): " + "Status code = %r. Content: %r" % + (init_session.status_code, init_session.content)) + if init_session.status_code == 422: + raise SRPAuthenticationError("Unknown user") + salt = init_session.json().get("salt", None) + B = init_session.json().get("B", None) + + if salt is None: + logger.error("No salt parameter sent") + raise SRPAuthenticationError("The server did not send the " + + "salt parameter") + if B is None: + logger.error("No B parameter sent") + raise SRPAuthenticationError("The server did not send the " + + "B parameter") + + return salt, B + + def _process_challenge(self, salt, B, username): + """ + Given the salt and B processes the auth challenge and + generates the M2 parameter + + Might throw SRPAuthenticationError + + @param salt: salt for the username + @type salt: str + @param B: B SRP parameter + @type B: str + @param username: username for this session + @type username: str + + @return: the M2 SRP parameter + @rtype: str + """ + logger.debug("Processing challenge...") + try: + unhex_salt = self._safe_unhexlify(salt) + unhex_B = self._safe_unhexlify(B) + except TypeError as e: + logger.error("Bad data from server: %r" % (e,)) + raise SRPAuthenticationError("The data sent from the server " + "had errors") + M = self._srp_user.process_challenge(unhex_salt, unhex_B) + + auth_url = "%s/%s/%s/%s" % (self._provider_config.get_api_uri(), + self._provider_config. + get_api_version(), + "sessions", + username) + + auth_data = { + self.CLIENT_AUTH_KEY: binascii.hexlify(M) + } + + try: + auth_result = self._session.put(auth_url, + data=auth_data, + verify=self._provider_config. + get_ca_cert_path()) + except requests.exceptions.ConnectionError as e: + logger.error("No connection made (HAMK): %r" % (e,)) + raise SRPAuthenticationError("Could not connect to the server") + + if auth_result.status_code == 422: + logger.error("[%s] Wrong password (HAMK): [%s]" % + (auth_result.status_code, + auth_result.json(). + get("errors", ""))) + raise SRPAuthenticationError("Wrong password") + + if auth_result.status_code not in (200,): + logger.error("No valid response (HAMK): " + "Status code = %s. Content = %r" % + (auth_result.status_code, auth_result.content)) + raise SRPAuthenticationError("Unknown error (%s)" % + (auth_result.status_code,)) + + M2 = auth_result.json().get("M2", None) + self.set_uid(auth_result.json().get("id", None)) + + if M2 is None or self.get_uid() is None: + logger.error("Something went wrong. Content = %r" % + (auth_result.content,)) + raise SRPAuthenticationError("Problem getting data from" + " server") + + return M2 + + def _verify_session(self, M2): + """ + Verifies the session based on the M2 parameter. If the + verification succeeds, it sets the session_id for this + session + + Might throw SRPAuthenticationError + + @param M2: M2 SRP parameter + @type M2: str + """ + logger.debug("Verifying session...") + try: + unhex_M2 = self._safe_unhexlify(M2) + except TypeError: + logger.error("Bad data from server (HAWK)") + raise SRPAuthenticationError("Bad data from server") + + self._srp_user.verify_session(unhex_M2) + + if not self._srp_user.authenticated(): + logger.error("Auth verification failed") + raise SRPAuthenticationError("Auth verification failed") + logger.debug("Session verified.") + + self.set_session_id(self._session.cookies["_session_id"]) + + def authenticate(self, username, password): + """ + Executes the whole authentication process for a user + + Might raise SRPAuthenticationError + + @param username: username for this session + @type username: str + @param password: password for this user + @type password: str + """ + assert self.get_session_id() is None, "Already logged in" + + self._authentication_preprocessing(username, password) + salt, B = self._start_authentication(username, password) + M2 = self._process_challenge(salt, B, username) + self._verify_session(M2) + + assert self.get_session_id(), "Something went wrong because" + \ + " we don't have the auth cookie afterwards" + + def logout(self): + """ + Logs out the current session. + Expects a session_id to exists, might raise AssertionError + """ + logger.debug("Starting logout...") + + assert self.get_session_id(), "Cannot logout an unexisting session" + + logout_url = "%s/%s/%s/" % (self._provider_config.get_api_uri(), + self._provider_config. + get_api_version(), + "sessions") + try: + self._session.delete(logout_url, + data=self.get_session_id(), + verify=self._provider_config. + get_ca_cert_path()) + except Exception as e: + logger.warning("Something went wrong with the logout: %r" % + (e,)) + + self.set_session_id(None) + self.set_uid(None) + # Also reset the session + self._session = self._fetcher.session() + logger.debug("Successfully logged out.") + + def set_session_id(self, session_id): + QtCore.QMutexLocker(self._session_id_lock) + self._session_id = session_id + + def get_session_id(self): + QtCore.QMutexLocker(self._session_id_lock) + return self._session_id + + def set_uid(self, uid): + QtCore.QMutexLocker(self._uid_lock) + self._uid = uid + + def get_uid(self): + QtCore.QMutexLocker(self._uid_lock) + return self._uid + + __instance = None + + authentication_finished = QtCore.Signal(bool, str) + logout_finished = QtCore.Signal(bool, str) + + DO_NOTHING = 0 + DO_LOGIN = 1 + DO_LOGOUT = 2 + + def __init__(self, provider_config): + """ + Creates a singleton instance if needed + """ + QtCore.QThread.__init__(self) + + # Check whether we already have an instance + if SRPAuth.__instance is None: + # Create and remember instance + SRPAuth.__instance = SRPAuth.__impl(provider_config) + + # Store instance reference as the only member in the handle + self.__dict__['_SRPAuth__instance'] = SRPAuth.__instance + + self._should_login = self.DO_NOTHING + self._should_login_lock = QtCore.QMutex() + self._username = None + self._password = None + + def authenticate(self, username, password): + """ + Executes the whole authentication process for a user + + Might raise SRPAuthenticationError + + @param username: username for this session + @type username: str + @param password: password for this user + @type password: str + """ + + with QtCore.QMutexLocker(self._should_login_lock): + self._should_login = self.DO_LOGIN + self._username = username + self._password = password + # Detach the start call to Qt's event loop + QtCore.QTimer.singleShot(0, self.start) + + def logout(self): + """ + Logs out the current session. + Expects a session_id to exists, might raise AssertionError + """ + QtCore.QMutexLocker(self._should_login_lock) + self._should_login = self.DO_LOGOUT + # Detach the start call to Qt's event loop + QtCore.QTimer.singleShot(0, self.start) + + def _runLogin(self, username, password): + try: + self.__instance.authenticate(username, password) + self.authentication_finished.emit(True, "Succeeded") + except Exception as e: + self.authentication_finished.emit(False, "%s" % (e,)) + + def _runLogout(self): + try: + self.__instance.logout() + self.logout_finished.emit(True, "Succeeded") + except Exception as e: + self.logout_finished.emit(False, "%s" % (e,)) + + def run(self): + QtCore.QMutexLocker(self._should_login_lock) + if self._should_login == self.DO_LOGIN: + self._runLogin(self._username, self._password) + elif self._should_login == self.DO_LOGOUT: + self._runLogout() + self._should_login = self.DO_NOTHING + + +if __name__ == "__main__": + logger = logging.getLogger(name='leap') + logger.setLevel(logging.DEBUG) + console = logging.StreamHandler() + console.setLevel(logging.DEBUG) + formatter = logging.Formatter( + '%(asctime)s ' + '- %(name)s - %(levelname)s - %(message)s') + console.setFormatter(formatter) + logger.addHandler(console) + + provider = ProviderConfig() + + if provider.load("leap/providers/bitmask.net/provider.json"): + # url = "%s/tickets" % (provider.get_api_uri(),) + # print url + # res = requests.session().get(url, verify=provider.get_ca_cert_path()) + # print res.content + # res.raise_for_status() + auth = SRPAuth(provider) + auth.start() + auth.authenticate("test2", "sarasaaaa") + res = requests.session().get("%s/cert" % (provider.get_api_uri(),), + verify=provider.get_ca_cert_path()) + print res.content + auth.logout() diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py new file mode 100644 index 00000000..d9b2b22b --- /dev/null +++ b/src/leap/crypto/srpregister.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# srpregister.py +# Copyright (C) 2013 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import requests +import binascii +import srp +import logging + +from urlparse import urlparse + +from leap.config.providerconfig import ProviderConfig +from leap.crypto.constants import SIGNUP_TIMEOUT + +logger = logging.getLogger(__name__) + + +class SRPRegister(object): + """ + Registers a user to a specific provider using SRP + """ + + USER_LOGIN_KEY = 'user[login]' + USER_VERIFIER_KEY = 'user[password_verifier]' + USER_SALT_KEY = 'user[password_salt]' + + def __init__(self, + provider_config=None, + register_path="users"): + """ + Constructor + + @param provider_config: provider configuration instance, + properly loaded + @type privider_config: ProviderConfig + @param register_path: webapp path for registering users + @type register_path; str + """ + + assert provider_config, "Please provider a provider" + assert isinstance(provider_config, ProviderConfig), \ + "We need a ProviderConfig instead of %r" % (provider_config,) + + self._provider_config = provider_config + + # **************************************************** # + # Dependency injection helpers, override this for more + # granular testing + self._fetcher = requests + self._srp = srp + self._hashfun = self._srp.SHA256 + self._ng = self._srp.NG_1024 + # **************************************************** # + + parsed_url = urlparse(provider_config.get_api_uri()) + self._provider = parsed_url.hostname + self._port = parsed_url.port + + self._register_path = register_path + + self._session = self._fetcher.session() + + def _get_registration_uri(self): + """ + Returns the URI where the register request should be made for + the provider + + @rtype: str + """ + + if self._port: + uri = "https://%s:%s/%s/%s" % ( + self._provider, + self._port, + self._provider_config.get_api_version(), + self._register_path) + else: + uri = "https://%s/%s/%s" % ( + self._provider, + self._provider_config.get_api_version(), + self._register_path) + + return uri + + def register_user(self, username, password): + """ + Registers a user with the validator based on the password provider + + @param username: username to register + @type username: str + @param password: password for this username + @type password: str + + @rtype: tuple + @rparam: (ok, request) + """ + salt, verifier = self._srp.create_salted_verification_key( + username, + password, + self._hashfun, + self._ng) + + user_data = { + self.USER_LOGIN_KEY: username, + self.USER_VERIFIER_KEY: binascii.hexlify(verifier), + self.USER_SALT_KEY: binascii.hexlify(salt) + } + + uri = self._get_registration_uri() + + logger.debug('Post to uri: %s' % uri) + logger.debug("Will try to register user = %s" % (username,)) + logger.debug("user_data => %r" % (user_data,)) + + req = self._session.post(uri, + data=user_data, + timeout=SIGNUP_TIMEOUT, + verify=self._provider_config. + get_ca_cert_path()) + + return (req.ok, req) + + +if __name__ == "__main__": + logger = logging.getLogger(name='leap') + logger.setLevel(logging.DEBUG) + console = logging.StreamHandler() + console.setLevel(logging.DEBUG) + formatter = logging.Formatter( + '%(asctime)s ' + '- %(name)s - %(levelname)s - %(message)s') + console.setFormatter(formatter) + logger.addHandler(console) + + provider = ProviderConfig() + + if provider.load("leap/providers/bitmask.net/provider.json"): + register = SRPRegister(provider_config=provider) + print "Registering user..." + print register.register_user("test1", "sarasaaaa") + print register.register_user("test2", "sarasaaaa") -- cgit v1.2.3 From 751638b4eb8208e1eaa1beaaed284da6b412bca7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Thu, 7 Mar 2013 19:05:11 -0300 Subject: Change asserts for a custom leap_assert method Also: - Make SRPAuth and the Bootstrappers be a QObject instead of a QThread so we can use them inside another more generic thread - Add a generic CheckerThread that runs checks or whatever operation as long as it returns a boolean value - Closes the whole application if the wizard is rejected at the first run - Do not fail when the config directory doesn't exist - Set the wizard pixmap logo as LEAP's logo - Improve wizard checks - Make SRPRegister play nice with the CheckerThread --- src/leap/crypto/srpauth.py | 108 +++++++++++++++++++++++++---------------- src/leap/crypto/srpregister.py | 17 ++++--- 2 files changed, 77 insertions(+), 48 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index dbcc95cb..28e4f037 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -20,9 +20,11 @@ import srp import binascii import logging -from PySide import QtCore +from PySide import QtCore, QtGui from leap.config.providerconfig import ProviderConfig +from leap.util.check import leap_assert +from leap.util.checkerthread import CheckerThread logger = logging.getLogger(__name__) @@ -34,7 +36,7 @@ class SRPAuthenticationError(Exception): pass -class SRPAuth(QtCore.QThread): +class SRPAuth(QtCore.QObject): """ SRPAuth singleton """ @@ -55,7 +57,8 @@ class SRPAuth(QtCore.QThread): @param server: Server to which we will authenticate @type server: str """ - assert provider_config, "We need a provider config to authenticate" + leap_assert(provider_config, + "We need a provider config to authenticate") self._provider_config = provider_config @@ -277,15 +280,15 @@ class SRPAuth(QtCore.QThread): @param password: password for this user @type password: str """ - assert self.get_session_id() is None, "Already logged in" + leap_assert(self.get_session_id() is None, "Already logged in") self._authentication_preprocessing(username, password) salt, B = self._start_authentication(username, password) M2 = self._process_challenge(salt, B, username) self._verify_session(M2) - assert self.get_session_id(), "Something went wrong because" + \ - " we don't have the auth cookie afterwards" + leap_assert(self.get_session_id(), "Something went wrong because" + " we don't have the auth cookie afterwards") def logout(self): """ @@ -294,7 +297,8 @@ class SRPAuth(QtCore.QThread): """ logger.debug("Starting logout...") - assert self.get_session_id(), "Cannot logout an unexisting session" + leap_assert(self.get_session_id(), + "Cannot logout an unexisting session") logout_url = "%s/%s/%s/" % (self._provider_config.get_api_uri(), self._provider_config. @@ -344,7 +348,7 @@ class SRPAuth(QtCore.QThread): """ Creates a singleton instance if needed """ - QtCore.QThread.__init__(self) + QtCore.QObject.__init__(self) # Check whether we already have an instance if SRPAuth.__instance is None: @@ -371,47 +375,47 @@ class SRPAuth(QtCore.QThread): @type password: str """ - with QtCore.QMutexLocker(self._should_login_lock): - self._should_login = self.DO_LOGIN - self._username = username - self._password = password - # Detach the start call to Qt's event loop - QtCore.QTimer.singleShot(0, self.start) - - def logout(self): - """ - Logs out the current session. - Expects a session_id to exists, might raise AssertionError - """ - QtCore.QMutexLocker(self._should_login_lock) - self._should_login = self.DO_LOGOUT - # Detach the start call to Qt's event loop - QtCore.QTimer.singleShot(0, self.start) - - def _runLogin(self, username, password): try: self.__instance.authenticate(username, password) + + logger.debug("Successful login!") self.authentication_finished.emit(True, "Succeeded") + return True except Exception as e: + logger.error("Error logging in %s" % (e,)) self.authentication_finished.emit(False, "%s" % (e,)) + return False - def _runLogout(self): + def logout(self): + """ + Logs out the current session. + Expects a session_id to exists, might raise AssertionError + """ try: self.__instance.logout() self.logout_finished.emit(True, "Succeeded") + return True except Exception as e: self.logout_finished.emit(False, "%s" % (e,)) - - def run(self): - QtCore.QMutexLocker(self._should_login_lock) - if self._should_login == self.DO_LOGIN: - self._runLogin(self._username, self._password) - elif self._should_login == self.DO_LOGOUT: - self._runLogout() - self._should_login = self.DO_NOTHING + return False if __name__ == "__main__": + import sys + from functools import partial + app = QtGui.QApplication(sys.argv) + + import signal + + def sigint_handler(*args, **kwargs): + logger.debug('SIGINT catched. shutting down...') + checker = args[0] + checker.set_should_quit() + QtGui.QApplication.quit() + + def signal_tester(d): + print d + logger = logging.getLogger(name='leap') logger.setLevel(logging.DEBUG) console = logging.StreamHandler() @@ -422,8 +426,23 @@ if __name__ == "__main__": console.setFormatter(formatter) logger.addHandler(console) - provider = ProviderConfig() + checker = CheckerThread() + + sigint = partial(sigint_handler, checker) + signal.signal(signal.SIGINT, sigint) + timer = QtCore.QTimer() + timer.start(500) + timer.timeout.connect(lambda: None) + app.connect(app, QtCore.SIGNAL("aboutToQuit()"), + checker.set_should_quit) + w = QtGui.QWidget() + w.resize(100, 100) + w.show() + + checker.start() + + provider = ProviderConfig() if provider.load("leap/providers/bitmask.net/provider.json"): # url = "%s/tickets" % (provider.get_api_uri(),) # print url @@ -431,9 +450,14 @@ if __name__ == "__main__": # print res.content # res.raise_for_status() auth = SRPAuth(provider) - auth.start() - auth.authenticate("test2", "sarasaaaa") - res = requests.session().get("%s/cert" % (provider.get_api_uri(),), - verify=provider.get_ca_cert_path()) - print res.content - auth.logout() + auth_instantiated = partial(auth.authenticate, "test2", "sarasaaaa") + + checker.add_checks([auth_instantiated, auth.logout]) + + #auth.authenticate("test2", "sarasaaaa") + #res = requests.session().get("%s/cert" % (provider.get_api_uri(),), + #verify=provider.get_ca_cert_path()) + #print res.content + #auth.logout() + + sys.exit(app.exec_()) diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index d9b2b22b..cf673e35 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -20,15 +20,17 @@ import binascii import srp import logging +from PySide import QtCore from urlparse import urlparse from leap.config.providerconfig import ProviderConfig from leap.crypto.constants import SIGNUP_TIMEOUT +from leap.util.check import leap_assert, leap_assert_type logger = logging.getLogger(__name__) -class SRPRegister(object): +class SRPRegister(QtCore.QObject): """ Registers a user to a specific provider using SRP """ @@ -37,6 +39,8 @@ class SRPRegister(object): USER_VERIFIER_KEY = 'user[password_verifier]' USER_SALT_KEY = 'user[password_salt]' + registration_finished = QtCore.Signal(bool, object) + def __init__(self, provider_config=None, register_path="users"): @@ -49,10 +53,9 @@ class SRPRegister(object): @param register_path: webapp path for registering users @type register_path; str """ - - assert provider_config, "Please provider a provider" - assert isinstance(provider_config, ProviderConfig), \ - "We need a ProviderConfig instead of %r" % (provider_config,) + QtCore.QObject.__init__(self) + leap_assert(provider_config, "Please provider a provider") + leap_assert_type(provider_config, ProviderConfig) self._provider_config = provider_config @@ -131,7 +134,9 @@ class SRPRegister(object): verify=self._provider_config. get_ca_cert_path()) - return (req.ok, req) + self.registration_finished.emit(req.ok, req) + + return req.ok if __name__ == "__main__": -- cgit v1.2.3 From 926575bc811e8382100695a3396da7191fb43eb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Fri, 8 Mar 2013 13:15:38 -0300 Subject: Add translation support Also: - Make OpenVPN use a random port every time - Logout in parallel so the UI doesn't block - Add the WAIT status from OpenVPN to the mainwindow displays - Support non-unix sockets in the LinuxVPNLauncher --- src/leap/crypto/srpauth.py | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 28e4f037..8530b7da 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -156,18 +156,18 @@ class SRPAuth(QtCore.QObject): "Status code = %r. Content: %r" % (init_session.status_code, init_session.content)) if init_session.status_code == 422: - raise SRPAuthenticationError("Unknown user") + raise SRPAuthenticationError(self.tr("Unknown user")) salt = init_session.json().get("salt", None) B = init_session.json().get("B", None) if salt is None: logger.error("No salt parameter sent") - raise SRPAuthenticationError("The server did not send the " + - "salt parameter") + raise SRPAuthenticationError(self.tr("The server did not send " + "the salt parameter")) if B is None: logger.error("No B parameter sent") - raise SRPAuthenticationError("The server did not send the " + - "B parameter") + raise SRPAuthenticationError(self.tr("The server did not send " + "the B parameter")) return salt, B @@ -194,8 +194,8 @@ class SRPAuth(QtCore.QObject): unhex_B = self._safe_unhexlify(B) except TypeError as e: logger.error("Bad data from server: %r" % (e,)) - raise SRPAuthenticationError("The data sent from the server " - "had errors") + raise SRPAuthenticationError(self.tr("The data sent from " + "the server had errors")) M = self._srp_user.process_challenge(unhex_salt, unhex_B) auth_url = "%s/%s/%s/%s" % (self._provider_config.get_api_uri(), @@ -215,20 +215,21 @@ class SRPAuth(QtCore.QObject): get_ca_cert_path()) except requests.exceptions.ConnectionError as e: logger.error("No connection made (HAMK): %r" % (e,)) - raise SRPAuthenticationError("Could not connect to the server") + raise SRPAuthenticationError(self.tr("Could not connect to " + "the server")) if auth_result.status_code == 422: logger.error("[%s] Wrong password (HAMK): [%s]" % (auth_result.status_code, auth_result.json(). get("errors", ""))) - raise SRPAuthenticationError("Wrong password") + raise SRPAuthenticationError(self.tr("Wrong password")) if auth_result.status_code not in (200,): logger.error("No valid response (HAMK): " "Status code = %s. Content = %r" % (auth_result.status_code, auth_result.content)) - raise SRPAuthenticationError("Unknown error (%s)" % + raise SRPAuthenticationError(self.tr("Unknown error (%s)") % (auth_result.status_code,)) M2 = auth_result.json().get("M2", None) @@ -237,8 +238,8 @@ class SRPAuth(QtCore.QObject): if M2 is None or self.get_uid() is None: logger.error("Something went wrong. Content = %r" % (auth_result.content,)) - raise SRPAuthenticationError("Problem getting data from" - " server") + raise SRPAuthenticationError(self.tr("Problem getting data " + "from server")) return M2 @@ -258,13 +259,14 @@ class SRPAuth(QtCore.QObject): unhex_M2 = self._safe_unhexlify(M2) except TypeError: logger.error("Bad data from server (HAWK)") - raise SRPAuthenticationError("Bad data from server") + raise SRPAuthenticationError(self.tr("Bad data from server")) self._srp_user.verify_session(unhex_M2) if not self._srp_user.authenticated(): logger.error("Auth verification failed") - raise SRPAuthenticationError("Auth verification failed") + raise SRPAuthenticationError(self.tr("Auth verification " + "failed")) logger.debug("Session verified.") self.set_session_id(self._session.cookies["_session_id"]) @@ -379,7 +381,7 @@ class SRPAuth(QtCore.QObject): self.__instance.authenticate(username, password) logger.debug("Successful login!") - self.authentication_finished.emit(True, "Succeeded") + self.authentication_finished.emit(True, self.tr("Succeeded")) return True except Exception as e: logger.error("Error logging in %s" % (e,)) @@ -393,7 +395,7 @@ class SRPAuth(QtCore.QObject): """ try: self.__instance.logout() - self.logout_finished.emit(True, "Succeeded") + self.logout_finished.emit(True, self.tr("Succeeded")) return True except Exception as e: self.logout_finished.emit(False, "%s" % (e,)) -- cgit v1.2.3 From e4e5f35c3fc7ff02bc20a6ef7eaffae09f485061 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Fri, 8 Mar 2013 14:24:05 -0300 Subject: Add keyring and username/password saving capabilities Also: - Fix translations in SRPAuth - Support non-ascii passwords - Make the server check if the characters are allowed, just check for easy passwords --- src/leap/crypto/srpauth.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 8530b7da..2877efab 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -41,7 +41,7 @@ class SRPAuth(QtCore.QObject): SRPAuth singleton """ - class __impl(object): + class __impl(QtCore.QObject): """ Implementation of the SRPAuth interface """ @@ -57,6 +57,8 @@ class SRPAuth(QtCore.QObject): @param server: Server to which we will authenticate @type server: str """ + QtCore.QObject.__init__(self) + leap_assert(provider_config, "We need a provider config to authenticate") -- cgit v1.2.3 From a120904b512394346b286bb417adf34fc622e739 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Tue, 12 Mar 2013 14:26:38 -0300 Subject: Get eip cert with session_id when possible --- src/leap/crypto/srpauth.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 2877efab..c1964514 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -390,6 +390,9 @@ class SRPAuth(QtCore.QObject): self.authentication_finished.emit(False, "%s" % (e,)) return False + def get_session_id(self): + return self.__instance.get_session_id() + def logout(self): """ Logs out the current session. -- cgit v1.2.3 From 98699d1c1c9d4698faa6bd7b1c7cf5b576372381 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 13 Mar 2013 11:39:06 -0300 Subject: Separate stdlibs from non-std in imports --- src/leap/crypto/srpauth.py | 5 +++-- src/leap/crypto/srpregister.py | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index c1964514..e9c72408 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -15,11 +15,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -import requests -import srp import binascii import logging +import requests +import srp + from PySide import QtCore, QtGui from leap.config.providerconfig import ProviderConfig diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index cf673e35..471ef28f 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -15,11 +15,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -import requests import binascii -import srp import logging +import requests +import srp + from PySide import QtCore from urlparse import urlparse -- cgit v1.2.3 From fc80cfd6d393534d71bfd0489557d3b4203cf4fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 13 Mar 2013 11:45:34 -0300 Subject: Default to port 443 if no port is specified --- src/leap/crypto/srpregister.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index 471ef28f..c99f79ab 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -72,6 +72,8 @@ class SRPRegister(QtCore.QObject): parsed_url = urlparse(provider_config.get_api_uri()) self._provider = parsed_url.hostname self._port = parsed_url.port + if self._port is None: + self._port = "443" self._register_path = register_path @@ -85,17 +87,11 @@ class SRPRegister(QtCore.QObject): @rtype: str """ - if self._port: - uri = "https://%s:%s/%s/%s" % ( - self._provider, - self._port, - self._provider_config.get_api_version(), - self._register_path) - else: - uri = "https://%s/%s/%s" % ( - self._provider, - self._provider_config.get_api_version(), - self._register_path) + uri = "https://%s:%s/%s/%s" % ( + self._provider, + self._port, + self._provider_config.get_api_version(), + self._register_path) return uri -- cgit v1.2.3 From d0dfad6ac2af360de6421ce74a6831b5b81ad019 Mon Sep 17 00:00:00 2001 From: kali Date: Thu, 14 Mar 2013 07:08:31 +0900 Subject: namespace leap + leap.common split leap is a namespace package from here on. common folder will be deleted and moved to leap_pycommon repository. --- src/leap/crypto/srpauth.py | 2 +- src/leap/crypto/srpregister.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index e9c72408..152d77b5 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -23,8 +23,8 @@ import srp from PySide import QtCore, QtGui +from leap.common.check import leap_assert from leap.config.providerconfig import ProviderConfig -from leap.util.check import leap_assert from leap.util.checkerthread import CheckerThread logger = logging.getLogger(__name__) diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index c99f79ab..9a9cac76 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -26,7 +26,7 @@ from urlparse import urlparse from leap.config.providerconfig import ProviderConfig from leap.crypto.constants import SIGNUP_TIMEOUT -from leap.util.check import leap_assert, leap_assert_type +from leap.common.check import leap_assert, leap_assert_type logger = logging.getLogger(__name__) -- cgit v1.2.3 From d193fee401d606f6120ac11819a0127e7ee92458 Mon Sep 17 00:00:00 2001 From: kali Date: Tue, 26 Mar 2013 01:15:44 +0900 Subject: tests for srpregister and srpauth in this commit too, the twisted fake_provider implementation --- src/leap/crypto/srpauth.py | 31 +-- src/leap/crypto/srpregister.py | 25 ++- src/leap/crypto/tests/__init__.py | 16 ++ src/leap/crypto/tests/fake_provider.py | 333 ++++++++++++++++++++++++++++++ src/leap/crypto/tests/test.txt | 1 + src/leap/crypto/tests/test_provider.json | 15 ++ src/leap/crypto/tests/test_srpauth.py | 136 ++++++++++++ src/leap/crypto/tests/test_srpregister.py | 142 +++++++++++++ 8 files changed, 677 insertions(+), 22 deletions(-) create mode 100644 src/leap/crypto/tests/__init__.py create mode 100755 src/leap/crypto/tests/fake_provider.py create mode 100644 src/leap/crypto/tests/test.txt create mode 100644 src/leap/crypto/tests/test_provider.json create mode 100644 src/leap/crypto/tests/test_srpauth.py create mode 100644 src/leap/crypto/tests/test_srpregister.py (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 152d77b5..027ee0d7 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -272,7 +272,14 @@ class SRPAuth(QtCore.QObject): "failed")) logger.debug("Session verified.") - self.set_session_id(self._session.cookies["_session_id"]) + SESSION_ID_KEY = "_session_id" + session_id = self._session.cookies.get(SESSION_ID_KEY, None) + if not session_id: + logger.error("Bad cookie from server (missing _session_id)") + raise SRPAuthenticationError(self.tr("Session cookie " + "verification " + "failed")) + self.set_session_id(session_id) def authenticate(self, username, password): """ @@ -409,11 +416,18 @@ class SRPAuth(QtCore.QObject): if __name__ == "__main__": + import signal import sys + from functools import partial app = QtGui.QApplication(sys.argv) - import signal + if not len(sys.argv) == 3: + print 'Usage: srpauth.py ' + sys.exit(0) + + _user = sys.argv[1] + _pass = sys.argv[2] def sigint_handler(*args, **kwargs): logger.debug('SIGINT catched. shutting down...') @@ -452,20 +466,9 @@ if __name__ == "__main__": provider = ProviderConfig() if provider.load("leap/providers/bitmask.net/provider.json"): - # url = "%s/tickets" % (provider.get_api_uri(),) - # print url - # res = requests.session().get(url, verify=provider.get_ca_cert_path()) - # print res.content - # res.raise_for_status() auth = SRPAuth(provider) - auth_instantiated = partial(auth.authenticate, "test2", "sarasaaaa") + auth_instantiated = partial(auth.authenticate, _user, _pass) checker.add_checks([auth_instantiated, auth.logout]) - #auth.authenticate("test2", "sarasaaaa") - #res = requests.session().get("%s/cert" % (provider.get_api_uri(),), - #verify=provider.get_ca_cert_path()) - #print res.content - #auth.logout() - sys.exit(app.exec_()) diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index 9a9cac76..dc137aeb 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -55,7 +55,7 @@ class SRPRegister(QtCore.QObject): @type register_path; str """ QtCore.QObject.__init__(self) - leap_assert(provider_config, "Please provider a provider") + leap_assert(provider_config, "Please provide a provider") leap_assert_type(provider_config, ProviderConfig) self._provider_config = provider_config @@ -125,15 +125,24 @@ class SRPRegister(QtCore.QObject): logger.debug("Will try to register user = %s" % (username,)) logger.debug("user_data => %r" % (user_data,)) - req = self._session.post(uri, - data=user_data, - timeout=SIGNUP_TIMEOUT, - verify=self._provider_config. - get_ca_cert_path()) + try: + req = self._session.post(uri, + data=user_data, + timeout=SIGNUP_TIMEOUT, + verify=self._provider_config. + get_ca_cert_path()) - self.registration_finished.emit(req.ok, req) + except requests.exceptions.SSLError as exc: + logger.error("SSLError: %s" % exc.message) + _ok = False + req = None - return req.ok + else: + _ok = req.ok + + self.registration_finished.emit(_ok, req) + + return _ok if __name__ == "__main__": diff --git a/src/leap/crypto/tests/__init__.py b/src/leap/crypto/tests/__init__.py new file mode 100644 index 00000000..7f118735 --- /dev/null +++ b/src/leap/crypto/tests/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# __init__.py +# Copyright (C) 2013 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . diff --git a/src/leap/crypto/tests/fake_provider.py b/src/leap/crypto/tests/fake_provider.py new file mode 100755 index 00000000..4b05bbff --- /dev/null +++ b/src/leap/crypto/tests/fake_provider.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# fake_provider.py +# Copyright (C) 2013 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +"""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: + +XXX check if in use + +[ ] test-openvpn.pem +[ ] test-provider.json +[ ] test-eip-service.json +""" +import binascii +import json +import os +import sys + +import srp + +from OpenSSL import SSL + +from zope.interface import Interface, Attribute, implements + +from twisted.web.server import Site, Request +from twisted.web.static import File +from twisted.web.resource import Resource +from twisted.internet import reactor + +from leap.common.testing.https_server import where + +# See +# http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html +# 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 + << {"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 + << {"errors": {"login": "already taken!"}} + +""" + +# Globals to mock user/sessiondb + +_USERDB = {} +_SESSIONDB = {} + +_here = os.path.split(__file__)[0] + + +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 '[server]', login, verifier, salt + user = User(login, salt, verifier) + _USERDB[login] = user + return json.dumps({'errors': None}) + + +def getSession(self, sessionInterface=None): + """ + we overwrite twisted.web.server.Request.getSession method to + put the right cookie name in place + """ + if not self.session: + #cookiename = b"_".join([b'TWISTED_SESSION'] + self.sitepath) + cookiename = b"_".join([b'_session_id'] + self.sitepath) + sessionCookie = self.getCookie(cookiename) + if sessionCookie: + try: + self.session = self.site.getSession(sessionCookie) + except KeyError: + pass + # if it still hasn't been set, fix it up. + if not self.session: + self.session = self.site.makeSession() + self.addCookie(cookiename, self.session.uid, path=b'/') + self.session.touch() + if sessionInterface: + return self.session.getComponent(sessionInterface) + return self.session + + +def get_user(request): + """ + Returns user from the session dict + """ + login = request.args.get('login') + if login: + user = _USERDB.get(login[0], None) + if user: + return user + + request.getSession = getSession.__get__(request, Request) + session = request.getSession() + + user = _SESSIONDB.get(session, None) + return user + + +class FakeSession(Resource): + def __init__(self, name): + """ + Initializes session + """ + self.name = name + + def render_GET(self, request): + """ + Handles GET requests. + """ + return "%s\n" % json.dumps({'errors': None}) + + def render_POST(self, request): + """ + Handles POST requests. + """ + 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 '[server] login = %s' % user.login + print '[server] salt = %s' % user.salt + print '[server] len(_salt) = %s' % len(_salt) + print '[server] vkey = %s' % user.verifier + print '[server] len(vkey) = %s' % len(_verifier) + print '[server] s = %s' % binascii.hexlify(s) + print '[server] B = %s' % _B + print '[server] len(B) = %s' % len(_B) + + # override Request.getSession + request.getSession = getSession.__get__(request, Request) + 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): + """ + Handles PUT requests. + """ + # XXX check session??? + user = get_user(request) + + if not user: + print '[server] 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 '[server] verification failed!!!' + raise Exception("Authentication failed!") + #import ipdb;ipdb.set_trace() + + assert svr.authenticated() + print "***" + print '[server] User successfully authenticated using SRP!' + print "***" + + return json.dumps( + {'M2': binascii.hexlify(HAMK), + 'id': '9c943eb9d96a6ff1b7a7030bdeadbeef', + 'errors': None}) + + +class API_Sessions(Resource): + def getChild(self, name, request): + return FakeSession(name) + + +class OpenSSLServerContextFactory: + + def getContext(self): + """ + Create an SSL context. + """ + ctx = SSL.Context(SSL.SSLv23_METHOD) + #ctx = SSL.Context(SSL.TLSv1_METHOD) + ctx.use_certificate_file(where('leaptestscert.pem')) + ctx.use_privatekey_file(where('leaptestskey.pem')) + + return ctx + + +def get_provider_factory(): + """ + Instantiates a Site that serves the resources + that we expect from a valid provider. + Listens on: + * port 8000 for http connections + * port 8443 for https connections + + @rparam: factory for a site + @rtype: Site instance + """ + root = Resource() + root.putChild("provider.json", File( + os.path.join(_here, + "test_provider.json"))) + config = Resource() + config.putChild( + "eip-service.json", + File("./eip-service.json")) + apiv1 = Resource() + apiv1.putChild("config", config) + apiv1.putChild("sessions", API_Sessions()) + apiv1.putChild("users", FakeUsers(None)) + apiv1.putChild("cert", File( + os.path.join(_here, + 'openvpn.pem'))) + root.putChild("1", apiv1) + + factory = Site(root) + return factory + + +if __name__ == "__main__": + + from twisted.python import log + log.startLogging(sys.stdout) + + factory = get_provider_factory() + + # regular http (for debugging with curl) + reactor.listenTCP(8000, factory) + reactor.listenSSL(8443, factory, OpenSSLServerContextFactory()) + reactor.run() + + diff --git a/src/leap/crypto/tests/test.txt b/src/leap/crypto/tests/test.txt new file mode 100644 index 00000000..d6406617 --- /dev/null +++ b/src/leap/crypto/tests/test.txt @@ -0,0 +1 @@ +OK! diff --git a/src/leap/crypto/tests/test_provider.json b/src/leap/crypto/tests/test_provider.json new file mode 100644 index 00000000..c37bef8f --- /dev/null +++ b/src/leap/crypto/tests/test_provider.json @@ -0,0 +1,15 @@ +{ + "api_uri": "https://localhost:8443", + "api_version": "1", + "ca_cert_fingerprint": "SHA256: 0f17c033115f6b76ff67871872303ff65034efe7dd1b910062ca323eb4da5c7e", + "ca_cert_uri": "https://bitmask.net/ca.crt", + "default_language": "en", + "domain": "example.com", + "enrollment_policy": "open", + "name": { + "en": "Bitmask" + }, + "services": [ + "openvpn" + ] +} diff --git a/src/leap/crypto/tests/test_srpauth.py b/src/leap/crypto/tests/test_srpauth.py new file mode 100644 index 00000000..ce9403c7 --- /dev/null +++ b/src/leap/crypto/tests/test_srpauth.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# test_srpauth.py +# Copyright (C) 2013 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +""" +Tests for leap/crypto/srpauth.py +""" +try: + import unittest +except ImportError: + import unittest +import os +import sys + +from mock import MagicMock +from nose.twistedtools import reactor, threaded_reactor, stop_reactor +from twisted.python import log + +from leap.common.testing.https_server import where +from leap.config.providerconfig import ProviderConfig +from leap.crypto import srpauth +from leap.crypto import srpregister +from leap.crypto.tests import fake_provider + +log.startLogging(sys.stdout) + + +def _get_capath(): + return where("cacert.pem") + +_here = os.path.split(__file__)[0] + + +class ImproperlyConfiguredError(Exception): + """ + Raised if the test provider is missing configuration + """ + + +class SRPRegisterTestCase(unittest.TestCase): + """ + Tests for the SRP Authentication class + """ + __name__ = "SRPAuth tests" + + @classmethod + def setUpClass(cls): + """ + Sets up this TestCase with a simple and faked provider instance: + + * runs a threaded reactor + * loads a mocked ProviderConfig that points to the certs in the + leap.common.testing module. + """ + factory = fake_provider.get_provider_factory() + reactor.listenTCP(8000, factory) + reactor.listenSSL( + 8443, factory, + fake_provider.OpenSSLServerContextFactory()) + threaded_reactor() + + provider = ProviderConfig() + provider.get_ca_cert_path = MagicMock() + provider.get_ca_cert_path.return_value = _get_capath() + loaded = provider.load(path=os.path.join( + _here, "test_provider.json")) + if not loaded: + raise ImproperlyConfiguredError( + "Could not load test provider config") + cls.provider = provider + cls.register = srpregister.SRPRegister(provider_config=provider) + cls.auth = srpauth.SRPAuth(provider) + cls._auth_instance = cls.auth.__dict__['_SRPAuth__instance'] + cls.authenticate = cls._auth_instance.authenticate + cls.logout = cls._auth_instance.logout + + @classmethod + def tearDownClass(cls): + """ + Stops reactor when tearing down the class + """ + stop_reactor() + + def test_auth(self): + """ + Checks whether a pair of valid credentials is able to be authenticated. + """ + TEST_USER = "register_test_auth" + TEST_PASS = "pass" + + # pristine registration, should go well + ok = self.register.register_user(TEST_USER, TEST_PASS) + self.assertTrue(ok) + + self.authenticate(TEST_USER, TEST_PASS) + with self.assertRaises(AssertionError): + # AssertionError: already logged in + # We probably could take this as its own exception + self.authenticate(TEST_USER, TEST_PASS) + + self.logout() + + # cannot log out two times in a row (there's no session) + with self.assertRaises(AssertionError): + self.logout() + + def test_auth_with_bad_credentials(self): + """ + Checks that auth does not succeed with bad credentials. + """ + TEST_USER = "register_test_auth" + TEST_PASS = "pass" + + # non-existent credentials, should fail + with self.assertRaises(srpauth.SRPAuthenticationError): + self.authenticate("baduser_1", "passwrong") + + # good user, bad password, should fail + with self.assertRaises(srpauth.SRPAuthenticationError): + self.authenticate(TEST_USER, "passwrong") + + # bad user, good password, should fail too :) + with self.assertRaises(srpauth.SRPAuthenticationError): + self.authenticate("myunclejoe", TEST_PASS) diff --git a/src/leap/crypto/tests/test_srpregister.py b/src/leap/crypto/tests/test_srpregister.py new file mode 100644 index 00000000..b065958d --- /dev/null +++ b/src/leap/crypto/tests/test_srpregister.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# test_srpregister.py +# Copyright (C) 2013 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +""" +Tests for leap/crypto/srpregister.py +""" +try: + import unittest +except ImportError: + import unittest +import os +import sys + +from mock import MagicMock +from nose.twistedtools import reactor, threaded_reactor, stop_reactor +from twisted.python import log + +from leap.common.testing.https_server import where +from leap.config.providerconfig import ProviderConfig +from leap.crypto import srpregister +from leap.crypto.tests import fake_provider + +log.startLogging(sys.stdout) + + +def _get_capath(): + return where("cacert.pem") + +_here = os.path.split(__file__)[0] + + +class ImproperlyConfiguredError(Exception): + """ + Raised if the test provider is missing configuration + """ + + +class SRPRegisterTestCase(unittest.TestCase): + """ + Tests for the SRP Register class + """ + __name__ = "SRPRegister tests" + + @classmethod + def setUpClass(cls): + """ + Sets up this TestCase with a simple and faked provider instance: + + * runs a threaded reactor + """ + factory = fake_provider.get_provider_factory() + reactor.listenTCP(8000, factory) + reactor.listenSSL( + 8443, factory, + fake_provider.OpenSSLServerContextFactory()) + threaded_reactor() + + def setUp(self): + """ + Sets up common parameters for each test: + + * loads a mocked ProviderConfig that points to the certs in the + leap.common.testing module. + """ + provider = ProviderConfig() + provider.get_ca_cert_path = MagicMock() + provider.get_ca_cert_path.return_value = _get_capath() + loaded = provider.load(path=os.path.join( + _here, "test_provider.json")) + if not loaded: + raise ImproperlyConfiguredError( + "Could not load test provider config") + self.register = srpregister.SRPRegister(provider_config=provider) + + @classmethod + def tearDownClass(cls): + """ + Stops reactor when tearing down the class + """ + stop_reactor() + + def test_register_user(self): + """ + Checks if the registration of an unused name works as expected when + it is the first time that we attempt to register that user, as well as + when we request a user that is taken. + """ + # pristine registration + ok = self.register.register_user("foouser_firsttime", "barpass") + self.assertTrue(ok) + + # second registration attempt with the same user should return errors + ok = self.register.register_user("foouser_second", "barpass") + self.assertTrue(ok) + + # FIXME currently we are catching this in an upper layer, + # we could bring the error validation to the SRPRegister class + ok = self.register.register_user("foouser_second", "barpass") + # XXX + #self.assertFalse(ok) + + def test_correct_http_uri(self): + """ + Checks that registration autocorrect http uris to https ones. + """ + HTTP_URI = "http://localhost:8443" + HTTPS_URI = "https://localhost:8443/1/users" + provider = ProviderConfig() + provider.get_ca_cert_path = MagicMock() + provider.get_ca_cert_path.return_value = _get_capath() + provider.get_api_uri = MagicMock() + + # we introduce a http uri in the config file... + provider.get_api_uri.return_value = HTTP_URI + loaded = provider.load(path=os.path.join( + _here, "test_provider.json")) + if not loaded: + raise ImproperlyConfiguredError( + "Could not load test provider config") + self.register = srpregister.SRPRegister(provider_config=provider) + + # ... and we check that we're correctly taking the HTTPS protocol + # instead + self.assertEquals(self.register._get_registration_uri(), + HTTPS_URI) + ok = self.register.register_user("test_failhttp", "barpass") + self.assertTrue(ok) + + # XXX need to assert that _get_registration_uri was called too -- cgit v1.2.3 From 05fe7f44a899288a8a69b9a46793513b87f8d228 Mon Sep 17 00:00:00 2001 From: kali Date: Tue, 26 Mar 2013 02:55:55 +0900 Subject: workaround for srp server timing out on consecutive runs --- src/leap/crypto/tests/fake_provider.py | 2 - src/leap/crypto/tests/test_srpauth.py | 136 ------------------------------ src/leap/crypto/tests/test_srpregister.py | 107 ++++++++++++++++++----- 3 files changed, 86 insertions(+), 159 deletions(-) delete mode 100644 src/leap/crypto/tests/test_srpauth.py (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/fake_provider.py b/src/leap/crypto/tests/fake_provider.py index 4b05bbff..d3e05812 100755 --- a/src/leap/crypto/tests/fake_provider.py +++ b/src/leap/crypto/tests/fake_provider.py @@ -329,5 +329,3 @@ if __name__ == "__main__": reactor.listenTCP(8000, factory) reactor.listenSSL(8443, factory, OpenSSLServerContextFactory()) reactor.run() - - diff --git a/src/leap/crypto/tests/test_srpauth.py b/src/leap/crypto/tests/test_srpauth.py deleted file mode 100644 index ce9403c7..00000000 --- a/src/leap/crypto/tests/test_srpauth.py +++ /dev/null @@ -1,136 +0,0 @@ -# -*- coding: utf-8 -*- -# test_srpauth.py -# Copyright (C) 2013 LEAP -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -""" -Tests for leap/crypto/srpauth.py -""" -try: - import unittest -except ImportError: - import unittest -import os -import sys - -from mock import MagicMock -from nose.twistedtools import reactor, threaded_reactor, stop_reactor -from twisted.python import log - -from leap.common.testing.https_server import where -from leap.config.providerconfig import ProviderConfig -from leap.crypto import srpauth -from leap.crypto import srpregister -from leap.crypto.tests import fake_provider - -log.startLogging(sys.stdout) - - -def _get_capath(): - return where("cacert.pem") - -_here = os.path.split(__file__)[0] - - -class ImproperlyConfiguredError(Exception): - """ - Raised if the test provider is missing configuration - """ - - -class SRPRegisterTestCase(unittest.TestCase): - """ - Tests for the SRP Authentication class - """ - __name__ = "SRPAuth tests" - - @classmethod - def setUpClass(cls): - """ - Sets up this TestCase with a simple and faked provider instance: - - * runs a threaded reactor - * loads a mocked ProviderConfig that points to the certs in the - leap.common.testing module. - """ - factory = fake_provider.get_provider_factory() - reactor.listenTCP(8000, factory) - reactor.listenSSL( - 8443, factory, - fake_provider.OpenSSLServerContextFactory()) - threaded_reactor() - - provider = ProviderConfig() - provider.get_ca_cert_path = MagicMock() - provider.get_ca_cert_path.return_value = _get_capath() - loaded = provider.load(path=os.path.join( - _here, "test_provider.json")) - if not loaded: - raise ImproperlyConfiguredError( - "Could not load test provider config") - cls.provider = provider - cls.register = srpregister.SRPRegister(provider_config=provider) - cls.auth = srpauth.SRPAuth(provider) - cls._auth_instance = cls.auth.__dict__['_SRPAuth__instance'] - cls.authenticate = cls._auth_instance.authenticate - cls.logout = cls._auth_instance.logout - - @classmethod - def tearDownClass(cls): - """ - Stops reactor when tearing down the class - """ - stop_reactor() - - def test_auth(self): - """ - Checks whether a pair of valid credentials is able to be authenticated. - """ - TEST_USER = "register_test_auth" - TEST_PASS = "pass" - - # pristine registration, should go well - ok = self.register.register_user(TEST_USER, TEST_PASS) - self.assertTrue(ok) - - self.authenticate(TEST_USER, TEST_PASS) - with self.assertRaises(AssertionError): - # AssertionError: already logged in - # We probably could take this as its own exception - self.authenticate(TEST_USER, TEST_PASS) - - self.logout() - - # cannot log out two times in a row (there's no session) - with self.assertRaises(AssertionError): - self.logout() - - def test_auth_with_bad_credentials(self): - """ - Checks that auth does not succeed with bad credentials. - """ - TEST_USER = "register_test_auth" - TEST_PASS = "pass" - - # non-existent credentials, should fail - with self.assertRaises(srpauth.SRPAuthenticationError): - self.authenticate("baduser_1", "passwrong") - - # good user, bad password, should fail - with self.assertRaises(srpauth.SRPAuthenticationError): - self.authenticate(TEST_USER, "passwrong") - - # bad user, good password, should fail too :) - with self.assertRaises(srpauth.SRPAuthenticationError): - self.authenticate("myunclejoe", TEST_PASS) diff --git a/src/leap/crypto/tests/test_srpregister.py b/src/leap/crypto/tests/test_srpregister.py index b065958d..a59f71cb 100644 --- a/src/leap/crypto/tests/test_srpregister.py +++ b/src/leap/crypto/tests/test_srpregister.py @@ -15,7 +15,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ -Tests for leap/crypto/srpregister.py +Tests for: + * leap/crypto/srpregister.py + * leap/crypto/srpauth.py """ try: import unittest @@ -30,7 +32,7 @@ from twisted.python import log from leap.common.testing.https_server import where from leap.config.providerconfig import ProviderConfig -from leap.crypto import srpregister +from leap.crypto import srpregister, srpauth from leap.crypto.tests import fake_provider log.startLogging(sys.stdout) @@ -48,11 +50,11 @@ class ImproperlyConfiguredError(Exception): """ -class SRPRegisterTestCase(unittest.TestCase): +class SRPTestCase(unittest.TestCase): """ - Tests for the SRP Register class + Tests for the SRP Register and Auth classes """ - __name__ = "SRPRegister tests" + __name__ = "SRPRegister and SRPAuth tests" @classmethod def setUpClass(cls): @@ -60,30 +62,39 @@ class SRPRegisterTestCase(unittest.TestCase): Sets up this TestCase with a simple and faked provider instance: * runs a threaded reactor + * loads a mocked ProviderConfig that points to the certs in the + leap.common.testing module. """ factory = fake_provider.get_provider_factory() - reactor.listenTCP(8000, factory) - reactor.listenSSL( - 8443, factory, + http = reactor.listenTCP(8001, factory) + https = reactor.listenSSL( + 0, factory, fake_provider.OpenSSLServerContextFactory()) - threaded_reactor() - - def setUp(self): - """ - Sets up common parameters for each test: + get_port = lambda p: p.getHost().port + cls.http_port = get_port(http) + cls.https_port = get_port(https) - * loads a mocked ProviderConfig that points to the certs in the - leap.common.testing module. - """ provider = ProviderConfig() provider.get_ca_cert_path = MagicMock() provider.get_ca_cert_path.return_value = _get_capath() + + provider.get_api_uri = MagicMock() + provider.get_api_uri.return_value = cls._get_https_uri() + loaded = provider.load(path=os.path.join( _here, "test_provider.json")) if not loaded: raise ImproperlyConfiguredError( "Could not load test provider config") - self.register = srpregister.SRPRegister(provider_config=provider) + cls.register = srpregister.SRPRegister(provider_config=provider) + + cls.auth = srpauth.SRPAuth(provider) + cls._auth_instance = cls.auth.__dict__['_SRPAuth__instance'] + cls.authenticate = cls._auth_instance.authenticate + cls.logout = cls._auth_instance.logout + + # run! + threaded_reactor() @classmethod def tearDownClass(cls): @@ -92,6 +103,17 @@ class SRPRegisterTestCase(unittest.TestCase): """ stop_reactor() + # helper methods + + @classmethod + def _get_https_uri(cls): + """ + Returns a https uri with the right https port initialized + """ + return "https://localhost:%s" % (cls.https_port,) + + # Register tests + def test_register_user(self): """ Checks if the registration of an unused name works as expected when @@ -109,15 +131,13 @@ class SRPRegisterTestCase(unittest.TestCase): # FIXME currently we are catching this in an upper layer, # we could bring the error validation to the SRPRegister class ok = self.register.register_user("foouser_second", "barpass") - # XXX - #self.assertFalse(ok) def test_correct_http_uri(self): """ Checks that registration autocorrect http uris to https ones. """ - HTTP_URI = "http://localhost:8443" - HTTPS_URI = "https://localhost:8443/1/users" + HTTP_URI = "http://localhost:%s" % (self.https_port, ) + HTTPS_URI = "https://localhost:%s/1/users" % (self.https_port, ) provider = ProviderConfig() provider.get_ca_cert_path = MagicMock() provider.get_ca_cert_path.return_value = _get_capath() @@ -130,6 +150,7 @@ class SRPRegisterTestCase(unittest.TestCase): if not loaded: raise ImproperlyConfiguredError( "Could not load test provider config") + self.register = srpregister.SRPRegister(provider_config=provider) # ... and we check that we're correctly taking the HTTPS protocol @@ -140,3 +161,47 @@ class SRPRegisterTestCase(unittest.TestCase): self.assertTrue(ok) # XXX need to assert that _get_registration_uri was called too + + # Auth tests + + def test_auth(self): + """ + Checks whether a pair of valid credentials is able to be authenticated. + """ + TEST_USER = "register_test_auth" + TEST_PASS = "pass" + + # pristine registration, should go well + ok = self.register.register_user(TEST_USER, TEST_PASS) + self.assertTrue(ok) + + self.authenticate(TEST_USER, TEST_PASS) + with self.assertRaises(AssertionError): + # AssertionError: already logged in + # We probably could take this as its own exception + self.authenticate(TEST_USER, TEST_PASS) + + self.logout() + + # cannot log out two times in a row (there's no session) + with self.assertRaises(AssertionError): + self.logout() + + def test_auth_with_bad_credentials(self): + """ + Checks that auth does not succeed with bad credentials. + """ + TEST_USER = "register_test_auth" + TEST_PASS = "pass" + + # non-existent credentials, should fail + with self.assertRaises(srpauth.SRPAuthenticationError): + self.authenticate("baduser_1", "passwrong") + + # good user, bad password, should fail + with self.assertRaises(srpauth.SRPAuthenticationError): + self.authenticate(TEST_USER, "passwrong") + + # bad user, good password, should fail too :) + with self.assertRaises(srpauth.SRPAuthenticationError): + self.authenticate("myunclejoe", TEST_PASS) -- cgit v1.2.3 From 42593d4c6bda51a544a72abc0f935633939dad49 Mon Sep 17 00:00:00 2001 From: kali Date: Mon, 8 Apr 2013 23:44:22 +0900 Subject: Several fixes as per review --- src/leap/crypto/srpauth.py | 4 ++-- src/leap/crypto/srpregister.py | 12 +++++------- src/leap/crypto/tests/fake_provider.py | 29 ++++++++++++++++++++++++++++- src/leap/crypto/tests/test.txt | 1 - src/leap/crypto/tests/test_srpregister.py | 2 +- 5 files changed, 36 insertions(+), 12 deletions(-) delete mode 100644 src/leap/crypto/tests/test.txt (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 027ee0d7..8028a6dc 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -50,6 +50,7 @@ class SRPAuth(QtCore.QObject): LOGIN_KEY = "login" A_KEY = "A" CLIENT_AUTH_KEY = "client_auth" + SESSION_ID_KEY = "_session_id" def __init__(self, provider_config): """ @@ -272,8 +273,7 @@ class SRPAuth(QtCore.QObject): "failed")) logger.debug("Session verified.") - SESSION_ID_KEY = "_session_id" - session_id = self._session.cookies.get(SESSION_ID_KEY, None) + session_id = self._session.cookies.get(self.SESSION_ID_KEY, None) if not session_id: logger.error("Bad cookie from server (missing _session_id)") raise SRPAuthenticationError(self.tr("Session cookie " diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index dc137aeb..59aaf257 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -125,6 +125,7 @@ class SRPRegister(QtCore.QObject): logger.debug("Will try to register user = %s" % (username,)) logger.debug("user_data => %r" % (user_data,)) + ok = None try: req = self._session.post(uri, data=user_data, @@ -134,15 +135,12 @@ class SRPRegister(QtCore.QObject): except requests.exceptions.SSLError as exc: logger.error("SSLError: %s" % exc.message) - _ok = False req = None - + ok = False else: - _ok = req.ok - - self.registration_finished.emit(_ok, req) - - return _ok + ok = req.ok + self.registration_finished.emit(ok, req) + return ok if __name__ == "__main__": diff --git a/src/leap/crypto/tests/fake_provider.py b/src/leap/crypto/tests/fake_provider.py index d3e05812..d533b82b 100755 --- a/src/leap/crypto/tests/fake_provider.py +++ b/src/leap/crypto/tests/fake_provider.py @@ -78,6 +78,9 @@ safe_unhexlify = lambda x: binascii.unhexlify(x) \ class IUser(Interface): + """ + Defines the User Interface + """ login = Attribute("User login.") salt = Attribute("Password salt.") verifier = Attribute("Password verifier.") @@ -86,6 +89,10 @@ class IUser(Interface): class User(object): + """ + User object. + We store it in our simple session mocks + """ implements(IUser) @@ -94,20 +101,37 @@ class User(object): self.salt = salt self.verifier = verifier self.session = None + self.svr = None def set_server_verifier(self, svr): + """ + Adds a svr verifier object to this + User instance + """ self.svr = svr def set_session(self, session): + """ + Adds this instance of User to the + global session dict + """ _SESSIONDB[session] = self self.session = session class FakeUsers(Resource): + """ + Resource that handles user registration. + """ + def __init__(self, name): self.name = name def render_POST(self, request): + """ + Handles POST to the users api resource + Simulates a login. + """ args = request.args login = args['user[login]'][0] @@ -268,11 +292,14 @@ class FakeSession(Resource): class API_Sessions(Resource): + """ + Top resource for the API v1 + """ def getChild(self, name, request): return FakeSession(name) -class OpenSSLServerContextFactory: +class OpenSSLServerContextFactory(object): def getContext(self): """ diff --git a/src/leap/crypto/tests/test.txt b/src/leap/crypto/tests/test.txt deleted file mode 100644 index d6406617..00000000 --- a/src/leap/crypto/tests/test.txt +++ /dev/null @@ -1 +0,0 @@ -OK! diff --git a/src/leap/crypto/tests/test_srpregister.py b/src/leap/crypto/tests/test_srpregister.py index a59f71cb..5ba7306f 100644 --- a/src/leap/crypto/tests/test_srpregister.py +++ b/src/leap/crypto/tests/test_srpregister.py @@ -20,7 +20,7 @@ Tests for: * leap/crypto/srpauth.py """ try: - import unittest + import unittest2 as unittest except ImportError: import unittest import os -- cgit v1.2.3 From fd17db8aaeda0c5997a608fd2d2e0392eb0c68ae Mon Sep 17 00:00:00 2001 From: Tomas Touceda Date: Wed, 10 Apr 2013 09:56:36 -0300 Subject: Emit session_id and uid through events --- src/leap/crypto/srpauth.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 8028a6dc..ba8ac3f5 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -26,6 +26,8 @@ from PySide import QtCore, QtGui from leap.common.check import leap_assert from leap.config.providerconfig import ProviderConfig from leap.util.checkerthread import CheckerThread +from leap.common.events import signal as events_signal +from leap.common.events import events_pb2 as proto logger = logging.getLogger(__name__) @@ -237,7 +239,11 @@ class SRPAuth(QtCore.QObject): (auth_result.status_code,)) M2 = auth_result.json().get("M2", None) - self.set_uid(auth_result.json().get("id", None)) + uid = auth_result.json().get("id", None) + + events_signal(proto.CLIENT_UID, content=uid) + + self.set_uid(uid) if M2 is None or self.get_uid() is None: logger.error("Something went wrong. Content = %r" % @@ -279,6 +285,9 @@ class SRPAuth(QtCore.QObject): raise SRPAuthenticationError(self.tr("Session cookie " "verification " "failed")) + + events_signal(proto.CLIENT_SESSION_ID, content=session_id) + self.set_session_id(session_id) def authenticate(self, username, password): -- cgit v1.2.3 From f74849f4c926a83190169cae570e9ec826fd46da Mon Sep 17 00:00:00 2001 From: kali Date: Wed, 1 May 2013 04:14:15 +0900 Subject: pep8 --- src/leap/crypto/srpregister.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index 59aaf257..749b6f8c 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -128,10 +128,10 @@ class SRPRegister(QtCore.QObject): ok = None try: req = self._session.post(uri, - data=user_data, - timeout=SIGNUP_TIMEOUT, - verify=self._provider_config. - get_ca_cert_path()) + data=user_data, + timeout=SIGNUP_TIMEOUT, + verify=self._provider_config. + get_ca_cert_path()) except requests.exceptions.SSLError as exc: logger.error("SSLError: %s" % exc.message) -- cgit v1.2.3 From 2dae2703fb8c2ae7e721ce83020c0dd10ff9ca33 Mon Sep 17 00:00:00 2001 From: kali Date: Fri, 3 May 2013 02:59:22 +0900 Subject: updated documentation * documentation reviewed after rewrite, ready for 0.2.1 * updated docstrings format to fit sphinx autodoc --- src/leap/crypto/srpauth.py | 68 +++++++++++++++++----------------- src/leap/crypto/srpregister.py | 22 +++++------ src/leap/crypto/tests/fake_provider.py | 4 +- 3 files changed, 47 insertions(+), 47 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index ba8ac3f5..9446cee8 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -58,8 +58,8 @@ class SRPAuth(QtCore.QObject): """ Constructor for SRPAuth implementation - @param server: Server to which we will authenticate - @type server: str + :param server: Server to which we will authenticate + :type server: str """ QtCore.QObject.__init__(self) @@ -91,11 +91,11 @@ class SRPAuth(QtCore.QObject): Rounds the val to a multiple of 2 and returns the unhexlified value - @param val: hexlified value - @type val: str + :param val: hexlified value + :type val: str - @rtype: binary hex data - @return: unhexlified val + :rtype: binary hex data + :return: unhexlified val """ return binascii.unhexlify(val) \ if (len(val) % 2 == 0) else binascii.unhexlify('0' + val) @@ -104,10 +104,10 @@ class SRPAuth(QtCore.QObject): """ Generates the SRP.User to get the A SRP parameter - @param username: username to login - @type username: str - @param password: password for the username - @type password: str + :param username: username to login + :type username: str + :param password: password for the username + :type password: str """ logger.debug("Authentication preprocessing...") self._srp_user = self._srp.User(username, @@ -125,13 +125,13 @@ class SRPAuth(QtCore.QObject): Might raise SRPAuthenticationError - @param username: username to login - @type username: str - @param password: password for the username - @type password: str + :param username: username to login + :type username: str + :param password: password for the username + :type password: str - @return: salt and B parameters - @rtype: tuple + :return: salt and B parameters + :rtype: tuple """ logger.debug("Starting authentication process...") try: @@ -184,15 +184,15 @@ class SRPAuth(QtCore.QObject): Might throw SRPAuthenticationError - @param salt: salt for the username - @type salt: str - @param B: B SRP parameter - @type B: str - @param username: username for this session - @type username: str + :param salt: salt for the username + :type salt: str + :param B: B SRP parameter + :type B: str + :param username: username for this session + :type username: str - @return: the M2 SRP parameter - @rtype: str + :return: the M2 SRP parameter + :rtype: str """ logger.debug("Processing challenge...") try: @@ -261,8 +261,8 @@ class SRPAuth(QtCore.QObject): Might throw SRPAuthenticationError - @param M2: M2 SRP parameter - @type M2: str + :param M2: M2 SRP parameter + :type M2: str """ logger.debug("Verifying session...") try: @@ -296,10 +296,10 @@ class SRPAuth(QtCore.QObject): Might raise SRPAuthenticationError - @param username: username for this session - @type username: str - @param password: password for this user - @type password: str + :param username: username for this session + :type username: str + :param password: password for this user + :type password: str """ leap_assert(self.get_session_id() is None, "Already logged in") @@ -390,10 +390,10 @@ class SRPAuth(QtCore.QObject): Might raise SRPAuthenticationError - @param username: username for this session - @type username: str - @param password: password for this user - @type password: str + :param username: username for this session + :type username: str + :param password: password for this user + :type password: str """ try: diff --git a/src/leap/crypto/srpregister.py b/src/leap/crypto/srpregister.py index 749b6f8c..07b3c917 100644 --- a/src/leap/crypto/srpregister.py +++ b/src/leap/crypto/srpregister.py @@ -48,11 +48,11 @@ class SRPRegister(QtCore.QObject): """ Constructor - @param provider_config: provider configuration instance, + :param provider_config: provider configuration instance, properly loaded - @type privider_config: ProviderConfig - @param register_path: webapp path for registering users - @type register_path; str + :type privider_config: ProviderConfig + :param register_path: webapp path for registering users + :type register_path; str """ QtCore.QObject.__init__(self) leap_assert(provider_config, "Please provide a provider") @@ -84,7 +84,7 @@ class SRPRegister(QtCore.QObject): Returns the URI where the register request should be made for the provider - @rtype: str + :rtype: str """ uri = "https://%s:%s/%s/%s" % ( @@ -99,13 +99,13 @@ class SRPRegister(QtCore.QObject): """ Registers a user with the validator based on the password provider - @param username: username to register - @type username: str - @param password: password for this username - @type password: str + :param username: username to register + :type username: str + :param password: password for this username + :type password: str - @rtype: tuple - @rparam: (ok, request) + :rtype: tuple + :rparam: (ok, request) """ salt, verifier = self._srp.create_salted_verification_key( username, diff --git a/src/leap/crypto/tests/fake_provider.py b/src/leap/crypto/tests/fake_provider.py index d533b82b..74a735ff 100755 --- a/src/leap/crypto/tests/fake_provider.py +++ b/src/leap/crypto/tests/fake_provider.py @@ -321,8 +321,8 @@ def get_provider_factory(): * port 8000 for http connections * port 8443 for https connections - @rparam: factory for a site - @rtype: Site instance + :rparam: factory for a site + :rtype: Site instance """ root = Resource() root.putChild("provider.json", File( -- cgit v1.2.3 From c533900a43f5006e6b4cb9d070b4bd30fb67f0b5 Mon Sep 17 00:00:00 2001 From: Tomas Touceda Date: Fri, 10 May 2013 16:41:42 -0300 Subject: Save auth token --- src/leap/crypto/srpauth.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 9446cee8..26bd0295 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -82,6 +82,8 @@ class SRPAuth(QtCore.QObject): self._session_id_lock = QtCore.QMutex() self._uid = None self._uid_lock = QtCore.QMutex() + self._token = None + self._token_lock = QtCore.QMutex() self._srp_user = None self._srp_a = None @@ -240,10 +242,12 @@ class SRPAuth(QtCore.QObject): M2 = auth_result.json().get("M2", None) uid = auth_result.json().get("id", None) + token = auth_result.json().get("token", None) events_signal(proto.CLIENT_UID, content=uid) self.set_uid(uid) + self.set_token(token) if M2 is None or self.get_uid() is None: logger.error("Something went wrong. Content = %r" % @@ -356,6 +360,14 @@ class SRPAuth(QtCore.QObject): QtCore.QMutexLocker(self._uid_lock) return self._uid + def set_token(self, token): + QtCore.QMutexLocker(self._token_lock) + self._token = token + + def get_token(self, token): + QtCore.QMutexLocker(self._token_lock) + return self._token + __instance = None authentication_finished = QtCore.Signal(bool, str) -- cgit v1.2.3 From 4e201329042d43c8d281c5737d3d5f6f8e2bf67f Mon Sep 17 00:00:00 2001 From: Tomas Touceda Date: Fri, 10 May 2013 17:01:11 -0300 Subject: Add support for requests<1.0.0 --- src/leap/crypto/srpauth.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 26bd0295..dbaac01b 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -20,12 +20,14 @@ import logging import requests import srp +import json from PySide import QtCore, QtGui from leap.common.check import leap_assert from leap.config.providerconfig import ProviderConfig from leap.util.checkerthread import CheckerThread +from leap.util.request_helpers import get_content from leap.common.events import signal as events_signal from leap.common.events import events_pb2 as proto @@ -159,14 +161,18 @@ class SRPAuth(QtCore.QObject): raise SRPAuthenticationError("Unknown error: %r" % (e,)) + content, mtime = get_content(init_session) + if init_session.status_code not in (200,): logger.error("No valid response (salt): " "Status code = %r. Content: %r" % - (init_session.status_code, init_session.content)) + (init_session.status_code, content)) if init_session.status_code == 422: raise SRPAuthenticationError(self.tr("Unknown user")) - salt = init_session.json().get("salt", None) - B = init_session.json().get("B", None) + + json_content = json.loads(content) + salt = json_content.get("salt", None) + B = json_content.get("B", None) if salt is None: logger.error("No salt parameter sent") @@ -226,22 +232,25 @@ class SRPAuth(QtCore.QObject): raise SRPAuthenticationError(self.tr("Could not connect to " "the server")) + content, mtime = get_content(auth_result) + if auth_result.status_code == 422: logger.error("[%s] Wrong password (HAMK): [%s]" % (auth_result.status_code, - auth_result.json(). + content. get("errors", ""))) raise SRPAuthenticationError(self.tr("Wrong password")) if auth_result.status_code not in (200,): logger.error("No valid response (HAMK): " "Status code = %s. Content = %r" % - (auth_result.status_code, auth_result.content)) + (auth_result.status_code, content)) raise SRPAuthenticationError(self.tr("Unknown error (%s)") % (auth_result.status_code,)) - M2 = auth_result.json().get("M2", None) - uid = auth_result.json().get("id", None) + json_content = json.loads(content) + M2 = json_content.get("M2", None) + uid = json_content.get("id", None) token = auth_result.json().get("token", None) events_signal(proto.CLIENT_UID, content=uid) @@ -251,7 +260,7 @@ class SRPAuth(QtCore.QObject): if M2 is None or self.get_uid() is None: logger.error("Something went wrong. Content = %r" % - (auth_result.content,)) + (content,)) raise SRPAuthenticationError(self.tr("Problem getting data " "from server")) -- cgit v1.2.3 From 8781a893aeaa62286633021e9d3eb8502bd129ee Mon Sep 17 00:00:00 2001 From: Tomas Touceda Date: Sat, 11 May 2013 11:49:17 -0300 Subject: Support requests<1.0.0 for the token saving too --- src/leap/crypto/srpauth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index dbaac01b..ce6c28f4 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -251,7 +251,7 @@ class SRPAuth(QtCore.QObject): json_content = json.loads(content) M2 = json_content.get("M2", None) uid = json_content.get("id", None) - token = auth_result.json().get("token", None) + token = json_content.get("token", None) events_signal(proto.CLIENT_UID, content=uid) -- cgit v1.2.3 From b0abf507bb8eb570328172b659ab072bc4b08634 Mon Sep 17 00:00:00 2001 From: Tomas Touceda Date: Wed, 15 May 2013 16:16:32 -0300 Subject: Integrate soledad and keymanager in the client --- src/leap/crypto/srpauth.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index ce6c28f4..2f3cbd1c 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -373,7 +373,7 @@ class SRPAuth(QtCore.QObject): QtCore.QMutexLocker(self._token_lock) self._token = token - def get_token(self, token): + def get_token(self): QtCore.QMutexLocker(self._token_lock) return self._token @@ -431,6 +431,12 @@ class SRPAuth(QtCore.QObject): def get_session_id(self): return self.__instance.get_session_id() + def get_uid(self): + return self.__instance.get_uid() + + def get_token(self): + return self.__instance.get_token() + def logout(self): """ Logs out the current session. -- cgit v1.2.3 From 884d0e0f4dbba34b6f6f5afe6e27390a7606a7fa Mon Sep 17 00:00:00 2001 From: kali Date: Wed, 29 May 2013 04:02:43 +0900 Subject: make tests pass & fix pep8 --- src/leap/crypto/srpauth.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 2f3cbd1c..f1897e1d 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -22,6 +22,9 @@ import requests import srp import json +#this error is raised from requests +from simplejson.decoder import JSONDecodeError + from PySide import QtCore, QtGui from leap.common.check import leap_assert @@ -232,7 +235,10 @@ class SRPAuth(QtCore.QObject): raise SRPAuthenticationError(self.tr("Could not connect to " "the server")) - content, mtime = get_content(auth_result) + try: + content, mtime = get_content(auth_result) + except JSONDecodeError: + raise SRPAuthenticationError("Bad JSON content in auth result") if auth_result.status_code == 422: logger.error("[%s] Wrong password (HAMK): [%s]" % @@ -319,6 +325,7 @@ class SRPAuth(QtCore.QObject): self._authentication_preprocessing(username, password) salt, B = self._start_authentication(username, password) M2 = self._process_challenge(salt, B, username) + self._verify_session(M2) leap_assert(self.get_session_id(), "Something went wrong because" -- cgit v1.2.3 From 655cec1fec89eb30fc17bdc0a5f527e5a91ba5b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Tue, 4 Jun 2013 12:56:17 -0300 Subject: Remove CheckerThread from SRPAuth Also, some pep8 fixes --- src/leap/crypto/srpauth.py | 60 ---------------------------------------------- 1 file changed, 60 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index f1897e1d..28086279 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -29,7 +29,6 @@ from PySide import QtCore, QtGui from leap.common.check import leap_assert from leap.config.providerconfig import ProviderConfig -from leap.util.checkerthread import CheckerThread from leap.util.request_helpers import get_content from leap.common.events import signal as events_signal from leap.common.events import events_pb2 as proto @@ -456,62 +455,3 @@ class SRPAuth(QtCore.QObject): except Exception as e: self.logout_finished.emit(False, "%s" % (e,)) return False - - -if __name__ == "__main__": - import signal - import sys - - from functools import partial - app = QtGui.QApplication(sys.argv) - - if not len(sys.argv) == 3: - print 'Usage: srpauth.py ' - sys.exit(0) - - _user = sys.argv[1] - _pass = sys.argv[2] - - def sigint_handler(*args, **kwargs): - logger.debug('SIGINT catched. shutting down...') - checker = args[0] - checker.set_should_quit() - QtGui.QApplication.quit() - - def signal_tester(d): - print d - - logger = logging.getLogger(name='leap') - logger.setLevel(logging.DEBUG) - console = logging.StreamHandler() - console.setLevel(logging.DEBUG) - formatter = logging.Formatter( - '%(asctime)s ' - '- %(name)s - %(levelname)s - %(message)s') - console.setFormatter(formatter) - logger.addHandler(console) - - checker = CheckerThread() - - sigint = partial(sigint_handler, checker) - signal.signal(signal.SIGINT, sigint) - - timer = QtCore.QTimer() - timer.start(500) - timer.timeout.connect(lambda: None) - app.connect(app, QtCore.SIGNAL("aboutToQuit()"), - checker.set_should_quit) - w = QtGui.QWidget() - w.resize(100, 100) - w.show() - - checker.start() - - provider = ProviderConfig() - if provider.load("leap/providers/bitmask.net/provider.json"): - auth = SRPAuth(provider) - auth_instantiated = partial(auth.authenticate, _user, _pass) - - checker.add_checks([auth_instantiated, auth.logout]) - - sys.exit(app.exec_()) -- cgit v1.2.3 From 40c1190ad556aee33d1b90a9c234b36ad0759861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Thu, 6 Jun 2013 11:39:57 -0300 Subject: Make the login process more granular with defers --- src/leap/crypto/srpauth.py | 73 ++++++++++++++++++++++++++++------------------ 1 file changed, 44 insertions(+), 29 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 28086279..3e47f679 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -25,10 +25,10 @@ import json #this error is raised from requests from simplejson.decoder import JSONDecodeError -from PySide import QtCore, QtGui +from PySide import QtCore +from twisted.internet import threads from leap.common.check import leap_assert -from leap.config.providerconfig import ProviderConfig from leap.util.request_helpers import get_content from leap.common.events import signal as events_signal from leap.common.events import events_pb2 as proto @@ -124,13 +124,15 @@ class SRPAuth(QtCore.QObject): self._srp_a = A - def _start_authentication(self, username, password): + def _start_authentication(self, _, username, password): """ Sends the first request for authentication to retrieve the salt and B parameter Might raise SRPAuthenticationError + :param _: IGNORED, output from the previous callback (None) + :type _: IGNORED :param username: username to login :type username: str :param password: password for the username @@ -187,17 +189,15 @@ class SRPAuth(QtCore.QObject): return salt, B - def _process_challenge(self, salt, B, username): + def _process_challenge(self, salt_B, username): """ Given the salt and B processes the auth challenge and generates the M2 parameter Might throw SRPAuthenticationError - :param salt: salt for the username - :type salt: str - :param B: B SRP parameter - :type B: str + :param salt_B: salt and B parameters for the username + :type salt_B: tuple :param username: username for this session :type username: str @@ -206,6 +206,7 @@ class SRPAuth(QtCore.QObject): """ logger.debug("Processing challenge...") try: + salt, B = salt_B unhex_salt = self._safe_unhexlify(salt) unhex_B = self._safe_unhexlify(B) except TypeError as e: @@ -318,17 +319,22 @@ class SRPAuth(QtCore.QObject): :type username: str :param password: password for this user :type password: str + + :returns: A defer on a different thread + :rtype: twisted.internet.defer.Deferred """ leap_assert(self.get_session_id() is None, "Already logged in") - self._authentication_preprocessing(username, password) - salt, B = self._start_authentication(username, password) - M2 = self._process_challenge(salt, B, username) + d = threads.deferToThread(self._authentication_preprocessing, + username=username, + password=password) - self._verify_session(M2) + d.addCallback(self._start_authentication, username=username, + password=password) + d.addCallback(self._process_challenge, username=username) + d.addCallback(self._verify_session) - leap_assert(self.get_session_id(), "Something went wrong because" - " we don't have the auth cookie afterwards") + return d def logout(self): """ @@ -388,10 +394,6 @@ class SRPAuth(QtCore.QObject): authentication_finished = QtCore.Signal(bool, str) logout_finished = QtCore.Signal(bool, str) - DO_NOTHING = 0 - DO_LOGIN = 1 - DO_LOGOUT = 2 - def __init__(self, provider_config): """ Creates a singleton instance if needed @@ -406,8 +408,6 @@ class SRPAuth(QtCore.QObject): # Store instance reference as the only member in the handle self.__dict__['_SRPAuth__instance'] = SRPAuth.__instance - self._should_login = self.DO_NOTHING - self._should_login_lock = QtCore.QMutex() self._username = None self._password = None @@ -423,16 +423,31 @@ class SRPAuth(QtCore.QObject): :type password: str """ - try: - self.__instance.authenticate(username, password) + d = self.__instance.authenticate(username, password) + d.addCallback(self._gui_notify) + d.addErrback(self._errback) + return d - logger.debug("Successful login!") - self.authentication_finished.emit(True, self.tr("Succeeded")) - return True - except Exception as e: - logger.error("Error logging in %s" % (e,)) - self.authentication_finished.emit(False, "%s" % (e,)) - return False + def _gui_notify(self, _): + """ + Callback that notifies the UI with the proper signal. + + :param _: IGNORED, output from the previous callback (None) + :type _: IGNORED + """ + logger.debug("Successful login!") + self.authentication_finished.emit(True, self.tr("Succeeded")) + + def _errback(self, failure): + """ + General errback for the whole login process. Will notify the + UI with the proper signal. + + :param failure: Failure object captured from a callback. + :type failure: twisted.python.failure.Failure + """ + logger.error("Error logging in %s" % (failure,)) + self.authentication_finished.emit(False, "%s" % (failure,)) def get_session_id(self): return self.__instance.get_session_id() -- cgit v1.2.3 From 029b4c2ac07fab41dbed9ab90e04e477938c3c05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Tue, 11 Jun 2013 12:09:30 -0300 Subject: Merge systray icons Also, catch a possible problem with the login answer from the webapp and display a proper message --- src/leap/crypto/srpauth.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 28086279..82525d7f 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -254,9 +254,14 @@ class SRPAuth(QtCore.QObject): (auth_result.status_code,)) json_content = json.loads(content) - M2 = json_content.get("M2", None) - uid = json_content.get("id", None) - token = json_content.get("token", None) + + try: + M2 = json_content.get("M2", None) + uid = json_content.get("id", None) + token = json_content.get("token", None) + except Exception as e: + logger.error(e) + raise Exception("Something went wrong with the login") events_signal(proto.CLIENT_UID, content=uid) -- cgit v1.2.3 From 1ede2af0afb6db2265d7e32428c197605e74589e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 12 Jun 2013 10:57:20 -0300 Subject: Fix SRPAuth error reporting --- src/leap/crypto/srpauth.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index 52267b3b..bcd24de3 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -241,10 +241,17 @@ class SRPAuth(QtCore.QObject): raise SRPAuthenticationError("Bad JSON content in auth result") if auth_result.status_code == 422: + error = "" + try: + error = json.loads(content).get("errors", "") + except ValueError: + logger.error("Problem parsing the received response: %s" + % (content,)) + except AttributeError: + logger.error("Expecting a dict but something else was " + "received: %s", (content,)) logger.error("[%s] Wrong password (HAMK): [%s]" % - (auth_result.status_code, - content. - get("errors", ""))) + (auth_result.status_code, error)) raise SRPAuthenticationError(self.tr("Wrong password")) if auth_result.status_code not in (200,): -- cgit v1.2.3 From 1b670d268ee26fc06115702aff055884327f85ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Fri, 14 Jun 2013 11:08:39 -0300 Subject: Improve error messages in login --- src/leap/crypto/srpauth.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index bcd24de3..d089fa50 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -459,7 +459,8 @@ class SRPAuth(QtCore.QObject): :type failure: twisted.python.failure.Failure """ logger.error("Error logging in %s" % (failure,)) - self.authentication_finished.emit(False, "%s" % (failure,)) + self.authentication_finished.emit(False, "%s" % (failure.value,)) + failure.trap(Exception) def get_session_id(self): return self.__instance.get_session_id() -- cgit v1.2.3 From 8bee5f4e9a1bb0f7069fe41ab37dfec000487d7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Fri, 14 Jun 2013 12:45:08 -0300 Subject: Actually deferToThread all the things we expect to do in parallel --- src/leap/crypto/srpauth.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/srpauth.py b/src/leap/crypto/srpauth.py index d089fa50..0e95ae64 100644 --- a/src/leap/crypto/srpauth.py +++ b/src/leap/crypto/srpauth.py @@ -24,6 +24,7 @@ import json #this error is raised from requests from simplejson.decoder import JSONDecodeError +from functools import partial from PySide import QtCore from twisted.internet import threads @@ -321,6 +322,9 @@ class SRPAuth(QtCore.QObject): self.set_session_id(session_id) + def _threader(self, cb, res, *args, **kwargs): + return threads.deferToThread(cb, res, *args, **kwargs) + def authenticate(self, username, password): """ Executes the whole authentication process for a user @@ -341,10 +345,17 @@ class SRPAuth(QtCore.QObject): username=username, password=password) - d.addCallback(self._start_authentication, username=username, - password=password) - d.addCallback(self._process_challenge, username=username) - d.addCallback(self._verify_session) + d.addCallback( + partial(self._threader, + self._start_authentication), + username=username, + password=password) + d.addCallback( + partial(self._threader, + self._process_challenge), + username=username) + d.addCallback(partial(self._threader, + self._verify_session)) return d -- cgit v1.2.3 From 320909489ad8f5d14e190968098edcded51ee016 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Tue, 25 Jun 2013 15:55:23 -0300 Subject: Properly return the error responseCode when login is already taken --- src/leap/crypto/tests/fake_provider.py | 1 + 1 file changed, 1 insertion(+) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/fake_provider.py b/src/leap/crypto/tests/fake_provider.py index 74a735ff..b943040a 100755 --- a/src/leap/crypto/tests/fake_provider.py +++ b/src/leap/crypto/tests/fake_provider.py @@ -139,6 +139,7 @@ class FakeUsers(Resource): verifier = args['user[password_verifier]'][0] if login in _USERDB: + request.setResponseCode(422) return "%s\n" % json.dumps( {'errors': {'login': 'already taken!'}}) -- cgit v1.2.3 From bc3652f5c51bdd414d85a2388ee6cba757eca19c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Tue, 25 Jun 2013 15:56:09 -0300 Subject: Improve SRPRegister tests --- src/leap/crypto/tests/test_srpregister.py | 139 ++++++++++++++---------------- src/leap/crypto/tests/wrongcert.pem | 33 +++++++ 2 files changed, 100 insertions(+), 72 deletions(-) create mode 100644 src/leap/crypto/tests/wrongcert.pem (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/test_srpregister.py b/src/leap/crypto/tests/test_srpregister.py index 5ba7306f..f70382ce 100644 --- a/src/leap/crypto/tests/test_srpregister.py +++ b/src/leap/crypto/tests/test_srpregister.py @@ -27,8 +27,9 @@ import os import sys from mock import MagicMock -from nose.twistedtools import reactor, threaded_reactor, stop_reactor +from nose.twistedtools import reactor, deferred from twisted.python import log +from twisted.internet import threads from leap.common.testing.https_server import where from leap.config.providerconfig import ProviderConfig @@ -89,19 +90,6 @@ class SRPTestCase(unittest.TestCase): cls.register = srpregister.SRPRegister(provider_config=provider) cls.auth = srpauth.SRPAuth(provider) - cls._auth_instance = cls.auth.__dict__['_SRPAuth__instance'] - cls.authenticate = cls._auth_instance.authenticate - cls.logout = cls._auth_instance.logout - - # run! - threaded_reactor() - - @classmethod - def tearDownClass(cls): - """ - Stops reactor when tearing down the class - """ - stop_reactor() # helper methods @@ -114,6 +102,41 @@ class SRPTestCase(unittest.TestCase): # Register tests + def test_none_port(self): + provider = ProviderConfig() + provider.get_api_uri = MagicMock() + provider.get_api_uri.return_value = "http://localhost/" + loaded = provider.load(path=os.path.join( + _here, "test_provider.json")) + if not loaded: + raise ImproperlyConfiguredError( + "Could not load test provider config") + + register = srpregister.SRPRegister(provider_config=provider) + self.assertEquals(register._port, "443") + + @deferred() + def test_wrong_cert(self): + provider = ProviderConfig() + loaded = provider.load(path=os.path.join( + _here, "test_provider.json")) + provider.get_ca_cert_path = MagicMock() + provider.get_ca_cert_path.return_value = os.path.join( + _here, + "wrongcacert.pem") + provider.get_api_uri = MagicMock() + provider.get_api_uri.return_value = self._get_https_uri() + if not loaded: + raise ImproperlyConfiguredError( + "Could not load test provider config") + + register = srpregister.SRPRegister(provider_config=provider) + d = threads.deferToThread(register.register_user, "foouser_firsttime", + "barpass") + d.addCallback(self.assertFalse) + return d + + @deferred() def test_register_user(self): """ Checks if the registration of an unused name works as expected when @@ -121,17 +144,31 @@ class SRPTestCase(unittest.TestCase): when we request a user that is taken. """ # pristine registration - ok = self.register.register_user("foouser_firsttime", "barpass") - self.assertTrue(ok) - + d = threads.deferToThread(self.register.register_user, + "foouser_firsttime", + "barpass") + d.addCallback(self.assertTrue) + return d + + @deferred() + def test_second_register_user(self): # second registration attempt with the same user should return errors - ok = self.register.register_user("foouser_second", "barpass") - self.assertTrue(ok) + d = threads.deferToThread(self.register.register_user, + "foouser_second", + "barpass") + d.addCallback(self.assertTrue) # FIXME currently we are catching this in an upper layer, # we could bring the error validation to the SRPRegister class - ok = self.register.register_user("foouser_second", "barpass") - + def register_wrapper(_): + return threads.deferToThread(self.register.register_user, + "foouser_second", + "barpass") + d.addCallback(register_wrapper) + d.addCallback(self.assertFalse) + return d + + @deferred() def test_correct_http_uri(self): """ Checks that registration autocorrect http uris to https ones. @@ -151,57 +188,15 @@ class SRPTestCase(unittest.TestCase): raise ImproperlyConfiguredError( "Could not load test provider config") - self.register = srpregister.SRPRegister(provider_config=provider) + register = srpregister.SRPRegister(provider_config=provider) # ... and we check that we're correctly taking the HTTPS protocol # instead - self.assertEquals(self.register._get_registration_uri(), - HTTPS_URI) - ok = self.register.register_user("test_failhttp", "barpass") - self.assertTrue(ok) - - # XXX need to assert that _get_registration_uri was called too - - # Auth tests - - def test_auth(self): - """ - Checks whether a pair of valid credentials is able to be authenticated. - """ - TEST_USER = "register_test_auth" - TEST_PASS = "pass" - - # pristine registration, should go well - ok = self.register.register_user(TEST_USER, TEST_PASS) - self.assertTrue(ok) - - self.authenticate(TEST_USER, TEST_PASS) - with self.assertRaises(AssertionError): - # AssertionError: already logged in - # We probably could take this as its own exception - self.authenticate(TEST_USER, TEST_PASS) - - self.logout() - - # cannot log out two times in a row (there's no session) - with self.assertRaises(AssertionError): - self.logout() - - def test_auth_with_bad_credentials(self): - """ - Checks that auth does not succeed with bad credentials. - """ - TEST_USER = "register_test_auth" - TEST_PASS = "pass" - - # non-existent credentials, should fail - with self.assertRaises(srpauth.SRPAuthenticationError): - self.authenticate("baduser_1", "passwrong") - - # good user, bad password, should fail - with self.assertRaises(srpauth.SRPAuthenticationError): - self.authenticate(TEST_USER, "passwrong") - - # bad user, good password, should fail too :) - with self.assertRaises(srpauth.SRPAuthenticationError): - self.authenticate("myunclejoe", TEST_PASS) + reg_uri = register._get_registration_uri() + self.assertEquals(reg_uri, HTTPS_URI) + register._get_registration_uri = MagicMock(return_value=HTTPS_URI) + d = threads.deferToThread(register.register_user, "test_failhttp", + "barpass") + d.addCallback(self.assertTrue) + + return d diff --git a/src/leap/crypto/tests/wrongcert.pem b/src/leap/crypto/tests/wrongcert.pem new file mode 100644 index 00000000..e6cff38a --- /dev/null +++ b/src/leap/crypto/tests/wrongcert.pem @@ -0,0 +1,33 @@ +-----BEGIN CERTIFICATE----- +MIIFtTCCA52gAwIBAgIJAIWZus5EIXNtMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTMwNjI1MTc0NjExWhcNMTgwNjI1MTc0NjExWjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEA2ObM7ESjyuxFZYD/Y68qOPQgjgggW+cdXfBpU2p4n7clsrUeMhWdW40Y +77Phzor9VOeqs3ZpHuyLzsYVp/kFDm8tKyo2ah5fJwzL0VCSLYaZkUQQ7GNUmTCk +furaxl8cQx/fg395V7/EngsS9B3/y5iHbctbA4MnH3jaotO5EGeo6hw7/eyCotQ9 +KbBV9GJMcY94FsXBCmUB+XypKklWTLhSaS6Cu4Fo8YLW6WmcnsyEOGS2F7WVf5at +7CBWFQZHaSgIBLmc818/mDYCnYmCVMFn/6Ndx7V2NTlz+HctWrQn0dmIOnCUeCwS +wXq9PnBR1rSx/WxwyF/WpyjOFkcIo7vm72kS70pfrYsXcZD4BQqkXYj3FyKnPt3O +ibLKtCxL8/83wOtErPcYpG6LgFkgAAlHQ9MkUi5dbmjCJtpqQmlZeK1RALdDPiB3 +K1KZimrGsmcE624dJxUIOJJpuwJDy21F8kh5ZAsAtE1prWETrQYNElNFjQxM83rS +ZR1Ql2MPSB4usEZT57+KvpEzlOnAT3elgCg21XrjSFGi14hCEao4g2OEZH5GAwm5 +frf6UlSRZ/g3tLTfI8Hv1prw15W2qO+7q7SBAplTODCRk+Yb0YoA2mMM/QXBUcXs +vKEDLSSxzNIBi3T62l39RB/ml+gPKo87ZMDivex1ZhrcJc3Yu3sCAwEAAaOBpzCB +pDAdBgNVHQ4EFgQUPjE+4pun+8FreIdpoR8v6N7xKtUwdQYDVR0jBG4wbIAUPjE+ +4pun+8FreIdpoR8v6N7xKtWhSaRHMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpT +b21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGSCCQCF +mbrORCFzbTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4ICAQCpvCPdtvXJ +muTj379TZuCJs7/l0FhA7AHa1WAlHjsXHaA7N0+3ZWAbdtXDsowal6S+ldgU/kfV +Lq7NrRq+amJWC7SYj6cvVwhrSwSvu01fe/TWuOzHrRv1uTfJ/VXLonVufMDd9opo +bhqYxMaxLdIx6t/MYmZH4Wpiq0yfZuv//M8i7BBl/qvaWbLhg0yVAKRwjFvf59h6 +6tRFCLddELOIhLDQtk8zMbioPEbfAlKdwwP8kYGtDGj6/9/YTd/oTKRdgHuwyup3 +m0L20Y6LddC+tb0WpK5EyrNbCbEqj1L4/U7r6f/FKNA3bx6nfdXbscaMfYonKAKg +1cRrRg45sErmCz0QyTnWzXyvbjR4oQRzyW3kJ1JZudZ+AwOi00J5FYa3NiLuxl1u +gIGKWSrASQWhEdpa1nlCgX7PhdaQgYjEMpQvA0GCA0OF5JDu8en1yZqsOt1hCLIN +lkz/5jKPqrclY5hV99bE3hgCHRmIPNHCZG3wbZv2yJKxJX1YLMmQwAmSh2N7YwGG +yXRvCxQs5ChPHyRairuf/5MZCZnSVb45ppTVuNUijsbflKRUgfj/XvfqQ22f+C9N +Om2dmNvAiS2TOIfuP47CF2OUa5q4plUwmr+nyXQGM0SIoHNCj+MBdFfb3oxxAtI+ +SLhbnzQv5e84Doqz3YF0XW8jyR7q8GFLNA== +-----END CERTIFICATE----- -- cgit v1.2.3 From 503ec0d1b02e802191981041ead4b823c858bd75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 26 Jun 2013 21:28:25 -0300 Subject: Improve fake_provider to support the modified-if-needed feature --- src/leap/crypto/tests/fake_provider.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/fake_provider.py b/src/leap/crypto/tests/fake_provider.py index b943040a..f86d5ca9 100755 --- a/src/leap/crypto/tests/fake_provider.py +++ b/src/leap/crypto/tests/fake_provider.py @@ -31,6 +31,7 @@ import binascii import json import os import sys +import time import srp @@ -39,7 +40,7 @@ from OpenSSL import SSL from zope.interface import Interface, Attribute, implements from twisted.web.server import Site, Request -from twisted.web.static import File +from twisted.web.static import File, Data from twisted.web.resource import Resource from twisted.internet import reactor @@ -300,6 +301,22 @@ class API_Sessions(Resource): return FakeSession(name) +class FileModified(File): + def render_GET(self, request): + since = request.getHeader('if-modified-since') + if since: + tsince = time.strptime(since.replace(" GMT", "")) + tfrom = time.strptime(time.ctime(os.path.getmtime( + os.path.join(_here, + "test_provider.json")))) + if tfrom > tsince: + return File.render_GET(self, request) + else: + request.setResponseCode(304) + return "" + return File.render_GET(self, request) + + class OpenSSLServerContextFactory(object): def getContext(self): @@ -325,8 +342,9 @@ def get_provider_factory(): :rparam: factory for a site :rtype: Site instance """ - root = Resource() - root.putChild("provider.json", File( + root = Data("", "") + root.putChild("", root) + root.putChild("provider.json", FileModified( os.path.join(_here, "test_provider.json"))) config = Resource() -- cgit v1.2.3 From 4000450fc563c7d5425cdf8531cfd5f716960036 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Wed, 26 Jun 2013 21:29:21 -0300 Subject: Fix problem with an SRPRegister test --- src/leap/crypto/tests/test_srpregister.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/test_srpregister.py b/src/leap/crypto/tests/test_srpregister.py index f70382ce..6d2b52e8 100644 --- a/src/leap/crypto/tests/test_srpregister.py +++ b/src/leap/crypto/tests/test_srpregister.py @@ -123,7 +123,7 @@ class SRPTestCase(unittest.TestCase): provider.get_ca_cert_path = MagicMock() provider.get_ca_cert_path.return_value = os.path.join( _here, - "wrongcacert.pem") + "wrongcert.pem") provider.get_api_uri = MagicMock() provider.get_api_uri.return_value = self._get_https_uri() if not loaded: -- cgit v1.2.3 From 6b4954c88e8106de355eb6a5889fc487dd816173 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Thu, 27 Jun 2013 09:57:03 -0300 Subject: Add missing openvpn.pem certificate for tests --- src/leap/crypto/tests/openvpn.pem | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/leap/crypto/tests/openvpn.pem (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/openvpn.pem b/src/leap/crypto/tests/openvpn.pem new file mode 100644 index 00000000..a95e9370 --- /dev/null +++ b/src/leap/crypto/tests/openvpn.pem @@ -0,0 +1,33 @@ +-----BEGIN CERTIFICATE----- +MIIFtTCCA52gAwIBAgIJAIGJ8Dg+DtemMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTMwNjI2MjAyMDIyWhcNMTgwNjI2MjAyMDIyWjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEAxJaN0lWjFu+3j48c0WG8BvmPUf026Xli5d5NE4EjGsirwfre0oTeWZT9 +WRxqLGd2wDh6Mc9r6UqH6dwqLZKbsgwB5zI2lag7UWFttJF1U1c6AJynhaLMoy73 +sL9USTmQ57iYRFrVP/nGj9/L6I1XnV6midPi7a5aZreH9q8dWaAhmc9eFDU+Y4vS +sTFS6aomajLrI6YWo5toKqLq8IMryD03IM78a7gJtLgfWs+pYZRUBlM5JaYX98eX +mVPAYYH9krWxLVN3hTt1ngECzK+epo275zQJh960/2fNCfVJSXqSXcficLs+bR7t +FEkNuOP1hFV6LuoLL+k5Su+hp5kXMYZTvYYDpW4nPJoBdSG1w5O5IxO6zh+9VLB7 +oLrlgoyWvBoou5coCBpZVU6UyWcOx58kuZF8wNr0GgdvWAFwOGVuVG5jmcVdhaKC +0C8NxHrxlhcrcp0zwtDaOxfmZfcxiXs35iwUip5vS18Nv+XBK8ad9T79Ox8nSzP3 +RGPVDpExz7gPbZglqSe47XBIk0ZuIzgOgYpJj4JrpoewoIYb+OmUgI7UZjoGsMrV ++B2BqOKs7kF0HW3i5bR9YAi0ZYvnhQgjBtwCKm4zvLqwuPZHz9VWgIk6uezgStCP +WyzQ8IcopK49fOjcKa6JT5JRU+27paIZf1BkQsTkJy/Nti4TvwMCAwEAAaOBpzCB +pDAdBgNVHQ4EFgQUEgXSd3Yl3xAzbkWa7xeNe27d99cwdQYDVR0jBG4wbIAUEgXS +d3Yl3xAzbkWa7xeNe27d99ehSaRHMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpT +b21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGSCCQCB +ifA4Pg7XpjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4ICAQA6Vl9Ve4Qe +ewzXAxr0BabFRhtIuF7DV+/niT46qJhW2KgYe6rwZqdAhEbgH3kTPJ5JmmcUnAEH +nmrfoku/YAb5ObfdHUACsHy4cvSvFwBUQ9vXP6+oOFJhrGW4uzRI2pHGvnqB3lQ0 +JEPmPwduBCI5reRYauPbd4Wl4VhLGrjELb4JQZL24Q5ehXMnv415m7+aMkLzT2IA +p6B2xgRR+JAeUdyCNOV1f5AqJWyAUJPWGR0e1OTKNfc49+2skK0NmzrpGsoktSHa +uN6vGBCVGiZh7BTYblWMG5q9Am7idcdmC2fdpIf5yj7CKzV7WIPxPs0I7TuRcr41 +pUBLCAElcyCPB89lySol2BDs4gk4wZs4y2shUs3o0+mIpw/6o8tQF/9IL8ALkLqr +q9SuND7O1RXcg74o3HeVmRKtoI/KdgaVhJ0rFvcq83ftfu3KMyWB6SOKOu6ZYON8 +AcSjsDDpnDrwGFvjAYHiTkS9NaaJC1/g7Y6jjhxmbTkXPA6V8MvLKQiOvqk/9gCh +85FHsFkElIYnH6fbHIRxg20cnqmddTd+H5HgBIlhiKWuydtuoQFwzR/D3ypgLBaB +OWLcBP7I+RYhKlJFIWnfiyB0xbyI4W/UfL8p8jQI8TE9oIlm3WqxJXfebDEDEstj +8nS4Fb3G5Wr4pZMjfbtmBSAgHeWH6B90jg== +-----END CERTIFICATE----- -- cgit v1.2.3 From 20875f7a7abcd4b2403add47b5565f1098bb342a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Thu, 27 Jun 2013 17:50:32 -0300 Subject: Improve fake provider implementation --- src/leap/crypto/tests/fake_provider.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/fake_provider.py b/src/leap/crypto/tests/fake_provider.py index f86d5ca9..54af485d 100755 --- a/src/leap/crypto/tests/fake_provider.py +++ b/src/leap/crypto/tests/fake_provider.py @@ -306,9 +306,7 @@ class FileModified(File): since = request.getHeader('if-modified-since') if since: tsince = time.strptime(since.replace(" GMT", "")) - tfrom = time.strptime(time.ctime(os.path.getmtime( - os.path.join(_here, - "test_provider.json")))) + tfrom = time.strptime(time.ctime(os.path.getmtime(self.path))) if tfrom > tsince: return File.render_GET(self, request) else: @@ -350,12 +348,13 @@ def get_provider_factory(): config = Resource() config.putChild( "eip-service.json", - File("./eip-service.json")) + FileModified( + os.path.join(_here, "eip-service.json"))) apiv1 = Resource() apiv1.putChild("config", config) apiv1.putChild("sessions", API_Sessions()) apiv1.putChild("users", FakeUsers(None)) - apiv1.putChild("cert", File( + apiv1.putChild("cert", FileModified( os.path.join(_here, 'openvpn.pem'))) root.putChild("1", apiv1) -- cgit v1.2.3 From 0c836c3e474b88f39ce88ad9fadb0a13ee75189a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Touceda?= Date: Thu, 27 Jun 2013 17:51:05 -0300 Subject: Add missing eip-service.json sample file for the fake provider --- src/leap/crypto/tests/eip-service.json | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/leap/crypto/tests/eip-service.json (limited to 'src/leap/crypto') diff --git a/src/leap/crypto/tests/eip-service.json b/src/leap/crypto/tests/eip-service.json new file mode 100644 index 00000000..24df42a2 --- /dev/null +++ b/src/leap/crypto/tests/eip-service.json @@ -0,0 +1,43 @@ +{ + "gateways": [ + { + "capabilities": { + "adblock": false, + "filter_dns": false, + "limited": true, + "ports": [ + "1194", + "443", + "53", + "80" + ], + "protocols": [ + "tcp", + "udp" + ], + "transport": [ + "openvpn" + ], + "user_ips": false + }, + "host": "harrier.cdev.bitmask.net", + "ip_address": "199.254.238.50", + "location": "seattle__wa" + } + ], + "locations": { + "seattle__wa": { + "country_code": "US", + "hemisphere": "N", + "name": "Seattle, WA", + "timezone": "-7" + } + }, + "openvpn_configuration": { + "auth": "SHA1", + "cipher": "AES-128-CBC", + "tls-cipher": "DHE-RSA-AES128-SHA" + }, + "serial": 1, + "version": 1 +} \ No newline at end of file -- cgit v1.2.3