From: <Blu...@us...> - 2009-12-14 19:48:21
|
Revision: 314 http://virtplayground.svn.sourceforge.net/virtplayground/?rev=314&view=rev Author: BlueWolf_ Date: 2009-12-14 19:48:14 +0000 (Mon, 14 Dec 2009) Log Message: ----------- Client can now log it to the server. It uses RSA to protect the password Modified Paths: -------------- trunk/client/core/callback.py trunk/client/core/client.py trunk/client/core/parser.py Added Paths: ----------- trunk/client/core/rsa.py Modified: trunk/client/core/callback.py =================================================================== --- trunk/client/core/callback.py 2009-12-14 19:46:21 UTC (rev 313) +++ trunk/client/core/callback.py 2009-12-14 19:48:14 UTC (rev 314) @@ -18,15 +18,33 @@ class Callback: def connected(self): """ - This will be called when a connection with the server is made. - `con` contains the core's `Client` class, so you can use it to - send stuff. + When the connection is made, this will be called. Note that the + server can still kick the connection because it is full. You + should not client.login here, because the server still has to + send a rsa-key. See callback.received_rsa for this event. - This is placeholder. If you want to catch this event, + This is a placeholder. If you want to catch this event, overwrite this in your own callback """ pass + + def received_rsa(self, public): + """ + When a connection is made, the server will generate a rsa-key. + The client has to wait for this, before logging in. After this + event, you can use client.login (if you haven't specified a + login at client.connect) + public: + The generated public rsa-key. It is a dict with 2 + values: e and n. It's used for encoding the password + + + This is a placeholder. If you want to catch this event, + overwrite this in your own callback + """ + pass + def disconnected(self, reason): """ This is called when the connection dies. For example when you @@ -42,12 +60,17 @@ - more connections * "manual" - Client (you) closed the connection with .close() + * "duplicate" - Another client has logged in on this + account. This connection has been + kicked - Return True if you want it to reconnect. Be warned that this - event also will be raised when you do .close()! + Return True if you want it to reconnect. To avoid unexpected + behaviour, you should *only* do this when reason is "closed"! + If you provided the login in client.connect, it logs in + automatically. - This is placeholder. If you want to catch this event, + This is a placeholder. If you want to catch this event, overwrite this in your own callback """ pass @@ -61,7 +84,7 @@ Dict with the data that has been received - This is placeholder. If you want to catch this event, + This is a placeholder. If you want to catch this event, overwrite this in your own callback """ pass @@ -75,8 +98,40 @@ Dict with the data that will be send. - This is placeholder. If you want to catch this event, + This is a placeholder. If you want to catch this event, overwrite this in your own callback """ pass - + + def logged_in(self, username, uid, cid): + """ + Called when we are logged in. + + username: + The username for this user. Use this, instead what the + user typed in, because this has the right caps. Also + available in client.username. + uid: + The unique user-id for this user. Also available in + client.uid + cid: + The unique client-id for this connection. Also available + in client.cid + + This is a placeholder. If you want to catch this event, + overwrite this in your own callback + """ + + pass + + def failed_logging_in(self, reason): + """ + This happens when the user could not log in. You can safely use + client.login again. + + reason: + The reason why the user could not log in: + * "bad login" - The username and/or password is wrong. + """ + + pass Modified: trunk/client/core/client.py =================================================================== --- trunk/client/core/client.py 2009-12-14 19:46:21 UTC (rev 313) +++ trunk/client/core/client.py 2009-12-14 19:48:14 UTC (rev 314) @@ -17,7 +17,12 @@ import simplejson, socket, threading, time from parser import Parser +import rsa +__name__ = "VirtualCore" +__version__ = "0.0.1" + + class Client(threading.Thread): """ This is the client-core for Virtual Playground. This will handle the @@ -40,9 +45,11 @@ -------- The settings: - Currently, the config is a bit lonely and quiet. Do you want to - fill it? :-( - + -app_name + The name of your program. Will be send when logging in. + -app_name + The version of your program. Will be send when logging. + Should be a string. """ def __init__(self, config, callback_class): @@ -55,12 +62,29 @@ self.__config_default(config) self.__config = config + # Class that parsers all incomming data self.__parse = Parser(self.__call, self) + + # So the client knows if we are online. Is used for + # disconnecting self.__is_online = False + # Treading-event so that run() waits before it's allowed to + # connect self.__do_connect = threading.Event() self.__do_connect.clear() + # Auto log in after connecting. Used by self.connect + self.__login_after_connecting = () + + # RSA + self.__rsakey = None + + # Info after logging in + self.username = None + self.uid = None # User-id + self.cid = None # Connection-id + threading.Thread.__init__(self) self.setDaemon(True) @@ -68,15 +92,18 @@ def __config_default(self, config): - #config.setdefault('whatever', 'duh') - pass + config.setdefault('app_name', __name__) + config.setdefault('app_version', __version__) - def connect(self, host, port): + def connect(self, host, port, usr = None, pwd = None, bot = False): """ Will (try to) connect to the server on `host`:`port`. If you want to reconnect, you have to close the connection first, if it's still open. + + You can optionally let it login automatically. See client.login + for the usr, pwd and bot variables. """ self.__host = host @@ -85,9 +112,16 @@ if self.__sock: raise ConnectionError("You are already connected!") - self.__do_connect.set() # Release the hounds + # Should we login after connecting? + if usr and pwd: + self.__login_after_connecting = (usr, pwd, bot) + else: + self.__login_after_connecting = (); + self.__do_connect.set() # Releasing the hounds + + def run(self): """ Used by threading, not for external usage. @@ -141,6 +175,47 @@ if self.__is_online: self.close(disconnect_reason) + def login(self, usr, pwd, bot = False): + """ + Log in to the server. You should have received the RSA-key + before calling this! + pwd is expected to be sha. Bot should be True or False. Bots + have different functions in VP. + + >>> import sha + >>> sha.new("MyVerySecretPassword").hexdigest() + 'dc2275e9f1e53926dce503ec7d9df9ac9ce07dfc' + """ + + if self.cid != None: + raise LoginError("You are already logged in") + + # Get our login + if not (usr and pwd): + if self.__login_after_connecting: + usr, pwd, bot = self.__login_after_connecting + else: + return # Just ignore it.. + + if not self.__sock: + raise ConnectionError("You are not connected!") + + if not self.__rsakey: + raise LoginError("No rsa-key available") + + # Convert pwd + pwd = rsa.encrypt(pwd, self.__rsakey) + + # Log in + self.send("login", { + "usr": usr, + "pwd": pwd, + "bot": bool(bot), + "for": "VP", + "client": ( self.__config['app_name'], + self.__config['app_version'] + ) + }) def send(self, data_header, data_body = {}): @@ -181,6 +256,12 @@ self.__pinger.cancel() self.__pinger = None + # Reset variables + self.__rsa = None + self.username = None + self.cid = None + self.uid = None + try: self.__sock.shutdown(0) except: pass self.__sock.close() @@ -223,3 +304,6 @@ class ConnectionError(Exception): pass + +class LoginError(Exception): + pass Modified: trunk/client/core/parser.py =================================================================== --- trunk/client/core/parser.py 2009-12-14 19:46:21 UTC (rev 313) +++ trunk/client/core/parser.py 2009-12-14 19:48:14 UTC (rev 314) @@ -18,14 +18,13 @@ class Parser(): def __init__(self, callback, client): """ - This class parses all received messages from client. - It may need a better name... + This class parses all received messages from the server. """ - self.__call = callback - self.__client = client + self.callback = callback + self.client = client def __call__(self, msg): - self.__call.data_received(msg) + self.callback.data_received(msg) head = msg.keys()[0] body = msg[head] @@ -36,9 +35,51 @@ def disconnect(self, msg): """ - Called just before the server closes our connection + Called just before the server closes our connection. + * reason - Why the server disconnected us + "full" - Because the server is full + "duplicate" - Because another client has logged in + on the same account """ # reason - Why it's going to disconnect us - if msg['reason'] == 'full': - self.__client.close("full") + self.client.close(msg["reason"]) + + def rsa(self, msg): + """ + Called when the connection has been made and a rsa-key has been + generated. We can now log in using this key + * public - The public rsa-key, which contains e & n + """ + + self.client._Client__rsakey = msg['public'] + + self.callback.received_rsa(msg['public']) + + self.client.login(None, None) + + def login(self, msg): + """ + Called as answer for our login + * succeed - If we logged in + + if succeed is False: + * reason - Why we didn't log in + "bad login" - Username/password incorrect + + if succeed is True: + * username - The username (with right caps) + * id - The user-id + * uid - The server's connection-id + """ + + if msg['succeed'] == True: + self.client.username = msg['username'] + self.client.uid = msg['id'] + self.client.cid = msg['uid'] + + self.callback.logged_in(msg['username'], msg['id'], + msg['uid']) + + else: + self.callback.failed_logging_in(msg['reason']) Added: trunk/client/core/rsa.py =================================================================== --- trunk/client/core/rsa.py (rev 0) +++ trunk/client/core/rsa.py 2009-12-14 19:48:14 UTC (rev 314) @@ -0,0 +1,427 @@ +"""RSA module + +Module for calculating large primes, and RSA encryption, decryption, +signing and verification. Includes generating public and private keys. +""" + +__author__ = "Sybren Stuvel, Marloes de Boer and Ivo Tamboer" +__date__ = "2009-01-22" + +# NOTE: Python's modulo can return negative numbers. We compensate for +# this behaviour using the abs() function + +from cPickle import dumps, loads +import base64 +import math +import os +import random +import sys +import types +import zlib + +def gcd(p, q): + """Returns the greatest common divisor of p and q + + + >>> gcd(42, 6) + 6 + """ + if p<q: return gcd(q, p) + if q == 0: return p + return gcd(q, abs(p%q)) + +def bytes2int(bytes): + """Converts a list of bytes or a string to an integer + + >>> (128*256 + 64)*256 + + 15 + 8405007 + >>> l = [128, 64, 15] + >>> bytes2int(l) + 8405007 + """ + + if not (type(bytes) is types.ListType or type(bytes) is types.StringType): + raise TypeError("You must pass a string or a list") + + # Convert byte stream to integer + integer = 0 + for byte in bytes: + integer *= 256 + if type(byte) is types.StringType: byte = ord(byte) + integer += byte + + return integer + +def int2bytes(number): + """Converts a number to a string of bytes + + >>> bytes2int(int2bytes(123456789)) + 123456789 + """ + + if not (type(number) is types.LongType or type(number) is types.IntType): + raise TypeError("You must pass a long or an int") + + string = "" + + while number > 0: + string = "%s%s" % (chr(number & 0xFF), string) + number /= 256 + + return string + +def fast_exponentiation(a, p, n): + """Calculates r = a^p mod n + """ + result = a % n + remainders = [] + while p != 1: + remainders.append(p & 1) + p = p >> 1 + while remainders: + rem = remainders.pop() + result = ((a ** rem) * result ** 2) % n + return result + +def read_random_int(nbits): + """Reads a random integer of approximately nbits bits rounded up + to whole bytes""" + + nbytes = ceil(nbits/8) + randomdata = os.urandom(nbytes) + return bytes2int(randomdata) + +def ceil(x): + """ceil(x) -> int(math.ceil(x))""" + + return int(math.ceil(x)) + +def randint(minvalue, maxvalue): + """Returns a random integer x with minvalue <= x <= maxvalue""" + + # Safety - get a lot of random data even if the range is fairly + # small + min_nbits = 32 + + # The range of the random numbers we need to generate + range = maxvalue - minvalue + + # Which is this number of bytes + rangebytes = ceil(math.log(range, 2) / 8) + + # Convert to bits, but make sure it's always at least min_nbits*2 + rangebits = max(rangebytes * 8, min_nbits * 2) + + # Take a random number of bits between min_nbits and rangebits + nbits = random.randint(min_nbits, rangebits) + + return (read_random_int(nbits) % range) + minvalue + +def fermat_little_theorem(p): + """Returns 1 if p may be prime, and something else if p definitely + is not prime""" + + a = randint(1, p-1) + return fast_exponentiation(a, p-1, p) + +def jacobi(a, b): + """Calculates the value of the Jacobi symbol (a/b) + """ + + if a % b == 0: + return 0 + result = 1 + while a > 1: + if a & 1: + if ((a-1)*(b-1) >> 2) & 1: + result = -result + b, a = a, b % a + else: + if ((b ** 2 - 1) >> 3) & 1: + result = -result + a = a >> 1 + return result + +def jacobi_witness(x, n): + """Returns False if n is an Euler pseudo-prime with base x, and + True otherwise. + """ + + j = jacobi(x, n) % n + f = fast_exponentiation(x, (n-1)/2, n) + + if j == f: return False + return True + +def randomized_primality_testing(n, k): + """Calculates whether n is composite (which is always correct) or + prime (which is incorrect with error probability 2**-k) + + Returns False if the number if composite, and True if it's + probably prime. + """ + + q = 0.5 # Property of the jacobi_witness function + + # t = int(math.ceil(k / math.log(1/q, 2))) + t = ceil(k / math.log(1/q, 2)) + for i in range(t+1): + x = randint(1, n-1) + if jacobi_witness(x, n): return False + + return True + +def is_prime(number): + """Returns True if the number is prime, and False otherwise. + + >>> is_prime(42) + 0 + >>> is_prime(41) + 1 + """ + + """ + if not fermat_little_theorem(number) == 1: + # Not prime, according to Fermat's little theorem + return False + """ + + if randomized_primality_testing(number, 5): + # Prime, according to Jacobi + return True + + # Not prime + return False + + +def getprime(nbits): + """Returns a prime number of max. 'math.ceil(nbits/8)*8' bits. In + other words: nbits is rounded up to whole bytes. + + >>> p = getprime(8) + >>> is_prime(p-1) + 0 + >>> is_prime(p) + 1 + >>> is_prime(p+1) + 0 + """ + + nbytes = int(math.ceil(nbits/8)) + + while True: + integer = read_random_int(nbits) + + # Make sure it's odd + integer |= 1 + + # Test for primeness + if is_prime(integer): break + + # Retry if not prime + + return integer + +def are_relatively_prime(a, b): + """Returns True if a and b are relatively prime, and False if they + are not. + + >>> are_relatively_prime(2, 3) + 1 + >>> are_relatively_prime(2, 4) + 0 + """ + + d = gcd(a, b) + return (d == 1) + +def find_p_q(nbits): + """Returns a tuple of two different primes of nbits bits""" + + p = getprime(nbits) + while True: + q = getprime(nbits) + if not q == p: break + + return (p, q) + +def extended_euclid_gcd(a, b): + """Returns a tuple (d, i, j) such that d = gcd(a, b) = ia + jb + """ + + if b == 0: + return (a, 1, 0) + + q = abs(a % b) + r = long(a / b) + (d, k, l) = extended_euclid_gcd(b, q) + + return (d, l, k - l*r) + +# Main function: calculate encryption and decryption keys +def calculate_keys(p, q, nbits): + """Calculates an encryption and a decryption key for p and q, and + returns them as a tuple (e, d)""" + + n = p * q + phi_n = (p-1) * (q-1) + + while True: + # Make sure e has enough bits so we ensure "wrapping" through + # modulo n + e = getprime(max(8, nbits/2)) + if are_relatively_prime(e, n) and are_relatively_prime(e, phi_n): break + + (d, i, j) = extended_euclid_gcd(e, phi_n) + + if not d == 1: + raise Exception("e (%d) and phi_n (%d) are not relatively prime" % (e, phi_n)) + + if not (e * i) % phi_n == 1: + raise Exception("e (%d) and i (%d) are not mult. inv. modulo phi_n (%d)" % (e, i, phi_n)) + + return (e, i) + + +def gen_keys(nbits): + """Generate RSA keys of nbits bits. Returns (p, q, e, d). + + Note: this can take a long time, depending on the key size. + """ + + while True: + (p, q) = find_p_q(nbits) + (e, d) = calculate_keys(p, q, nbits) + + # For some reason, d is sometimes negative. We don't know how + # to fix it (yet), so we keep trying until everything is shiny + if d > 0: break + + return (p, q, e, d) + +def gen_pubpriv_keys(nbits): + """Generates public and private keys, and returns them as (pub, + priv). + + The public key consists of a dict {e: ..., , n: ....). The private + key consists of a dict {d: ...., p: ...., q: ....). + """ + + (p, q, e, d) = gen_keys(nbits) + + return ( {'e': e, 'n': p*q}, {'d': d, 'p': p, 'q': q} ) + +def encrypt_int(message, ekey, n): + """Encrypts a message using encryption key 'ekey', working modulo + n""" + + if type(message) is types.IntType: + return encrypt_int(long(message), ekey, n) + + if not type(message) is types.LongType: + raise TypeError("You must pass a long or an int") + + if message > 0 and \ + math.floor(math.log(message, 2)) > math.floor(math.log(n, 2)): + raise OverflowError("The message is too long") + + return fast_exponentiation(message, ekey, n) + +def decrypt_int(cyphertext, dkey, n): + """Decrypts a cypher text using the decryption key 'dkey', working + modulo n""" + + return encrypt_int(cyphertext, dkey, n) + +def sign_int(message, dkey, n): + """Signs 'message' using key 'dkey', working modulo n""" + + return decrypt_int(message, dkey, n) + +def verify_int(signed, ekey, n): + """verifies 'signed' using key 'ekey', working modulo n""" + + return encrypt_int(signed, ekey, n) + +def picklechops(chops): + """Pickles and base64encodes it's argument chops""" + + value = zlib.compress(dumps(chops)) + encoded = base64.encodestring(value) + return encoded.strip() + +def unpicklechops(string): + """base64decodes and unpickes it's argument string into chops""" + + return loads(zlib.decompress(base64.decodestring(string))) + +def chopstring(message, key, n, funcref): + """Splits 'message' into chops that are at most as long as n, + converts these into integers, and calls funcref(integer, key, n) + for each chop. + + Used by 'encrypt' and 'sign'. + """ + + msglen = len(message) + mbits = msglen * 8 + nbits = int(math.floor(math.log(n, 2))) + nbytes = nbits / 8 + blocks = msglen / nbytes + + if msglen % nbytes > 0: + blocks += 1 + + cypher = [] + + for bindex in range(blocks): + offset = bindex * nbytes + block = message[offset:offset+nbytes] + value = bytes2int(block) + cypher.append(funcref(value, key, n)) + + return picklechops(cypher) + +def gluechops(chops, key, n, funcref): + """Glues chops back together into a string. calls + funcref(integer, key, n) for each chop. + + Used by 'decrypt' and 'verify'. + """ + message = "" + + chops = unpicklechops(chops) + + for cpart in chops: + mpart = funcref(cpart, key, n) + message += int2bytes(mpart) + + return message + +def encrypt(message, key): + """Encrypts a string 'message' with the public key 'key'""" + + return chopstring(message, key['e'], key['n'], encrypt_int) + +def sign(message, key): + """Signs a string 'message' with the private key 'key'""" + + return chopstring(message, key['d'], key['p']*key['q'], decrypt_int) + +def decrypt(cypher, key): + """Decrypts a cypher with the private key 'key'""" + + return gluechops(cypher, key['d'], key['p']*key['q'], decrypt_int) + +def verify(cypher, key): + """Verifies a cypher with the public key 'key'""" + + return gluechops(cypher, key['e'], key['n'], encrypt_int) + +# Do doctest if we're not imported +if __name__ == "__main__": + import doctest + doctest.testmod() + +__all__ = ["gen_pubpriv_keys", "encrypt", "decrypt", "sign", "verify"] + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |