Exemplo n.º 1
0
def encryptMessageToSendRSA(params):
    with open("PublicKey", "rb") as f:
        serverPublicKey = security.importkey_RSA(f.read())
    tf = tempfile.NamedTemporaryFile(delete=True)
    security.encrypt_RSA(serverPublicKey, json.dumps(params), tf)
    sendparam = {"data": tf.read().encode("hex")}
    return sendparam
Exemplo n.º 2
0
 def logInUser(self, **kwargs):
     """Server Side logIn User
     User sends his username (Unique Identifier) and his password
     Security: Message from user ciphered with Server Public Key
     Session Management: Create a Public Key with DiffieHellman"""
     # Decipher the Message with Server Private Key
     receivedData = dm.decryptMessageReceived(kwargs['data'].decode('hex'))
     print receivedData['userID']
     # Verify if the user exists and has finished the regist process
     if DBmodule.db_registAuthenticate(receivedData['userID']) and \
         DBmodule.db_getLogIn(receivedData['userID'], receivedData['password']) == 1:
         # Create Session
         print receivedData['userID']
         print receivedData['password']
         serverSession = DiffieHellman.DiffieHellman()
         # Create challenge
         token = os.urandom(20)
         um.addSession(receivedData['userID'], serverSession, token)
         # Send to client the Token and the session public key
         tf = tempfile.NamedTemporaryFile(delete=True)
         pub_key = DBmodule.db_getUserPubKey(
             DBmodule.db_getUserID(receivedData['userID'])).decode('hex')
         security.encrypt_RSA(security.importkey_RSA(pub_key), token, tf)
         messageToSend = {
             'token': tf.read().encode('hex'),
             'session': serverSession.publicKey
         }
         return json.dumps(messageToSend)
     elif DBmodule.db_registNotAuthenticate(receivedData['userID']):
         return "REGIST_AGAIN"
     else:
         return "ERROR"
Exemplo n.º 3
0
def encryptMessageToSendRSA(params):
    with open('PublicKey', 'rb') as f:
        serverPublicKey = security.importkey_RSA(f.read())
    tf = tempfile.NamedTemporaryFile(delete=True)
    security.encrypt_RSA(serverPublicKey, json.dumps(params), tf)
    sendparam = {'data': tf.read().encode('hex')}
    return sendparam
Exemplo n.º 4
0
def shareFile(user, filename, usr_dest, permission):
    """Share function, allows a file to be shared
    with another user. The file with the AES used to encrypt
    the file to be shared is sent from the server, it is
    decrypted and encrypted with the target user's public key

    Security:
        - Sharing user's private key is used for decrypting
        file with AES key
        - Target user's public key is used for encrypting
        file with AES key
        - Sharing client receives no information from the
        other user except username and public key
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    message = {
        'filename': filename,
        'usrdstname': usr_dest,
    }
    messageToSend = security.encryptS_AES(json.dumps(message),
                                          session.decode('hex')).encode('hex')
    params = {'data': messageToSend, 'username': username}
    datagen, headers = multipart_encode(params)
    try:
        resp = urllib2.Request('https://localhost:8080/share', datagen,
                               headers)
        data = urllib2.urlopen(resp)
        date = json.loads(
            security.decryptS_AES(data.info().getheader('data').decode('hex'),
                                  session.decode('hex')))
        aes = date['aes'].decode('hex')
        pub_key = date['pubkey'].decode('hex')
        with open('PrivateKeys/Private_key_' + str(username), 'rb') as f:
            priv = security.importkey_RSA(f.read())
        RsaAES = security.decrypt_RSA(priv, aes)
        tf = tempfile.NamedTemporaryFile(delete=True)
        security.encrypt_RSA(security.importkey_RSA(pub_key), RsaAES, tf)
        message = {
            'filename': filename,
            'usrdstname': usr_dest,
            'filekey': tf.read().encode('hex'),
            'permission': permission
        }
        messageToSend = security.encryptS_AES(
            json.dumps(message), session.decode('hex')).encode('hex')
        request = urllib2.Request('https://localhost:8080/shareFile')
        request.add_header('username', username)
        request.add_header('data', messageToSend)
        response = urllib2.urlopen(request)
        tf.close()
        print response.read()
    except urllib2.HTTPError as e:
        print str(e.code) + ': ' + e.reason
        print 'Currently, you are not a valid user!\nSafeBox Team'
Exemplo n.º 5
0
def shareFile(user, filename, usr_dest, permission):
    """Share function, allows a file to be shared
    with another user. The file with the AES used to encrypt
    the file to be shared is sent from the server, it is
    decrypted and encrypted with the target user's public key

    Security:
        - Sharing user's private key is used for decrypting
        file with AES key
        - Target user's public key is used for encrypting
        file with AES key
        - Sharing client receives no information from the
        other user except username and public key
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    message = {"filename": filename, "usrdstname": usr_dest}
    messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex")
    params = {"data": messageToSend, "username": username}
    datagen, headers = multipart_encode(params)
    try:
        resp = urllib2.Request("https://localhost:8080/share", datagen, headers)
        data = urllib2.urlopen(resp)
        date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex")))
        aes = date["aes"].decode("hex")
        pub_key = date["pubkey"].decode("hex")
        with open("PrivateKeys/Private_key_" + str(username), "rb") as f:
            priv = security.importkey_RSA(f.read())
        RsaAES = security.decrypt_RSA(priv, aes)
        tf = tempfile.NamedTemporaryFile(delete=True)
        security.encrypt_RSA(security.importkey_RSA(pub_key), RsaAES, tf)
        message = {
            "filename": filename,
            "usrdstname": usr_dest,
            "filekey": tf.read().encode("hex"),
            "permission": permission,
        }
        messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex")
        request = urllib2.Request("https://localhost:8080/shareFile")
        request.add_header("username", username)
        request.add_header("data", messageToSend)
        response = urllib2.urlopen(request)
        tf.close()
        print response.read()
    except urllib2.HTTPError as e:
        print str(e.code) + ": " + e.reason
        print "Currently, you are not a valid user!\nSafeBox Team"
Exemplo n.º 6
0
 def registUser(self, **kwargs):
     """Server Side Regist User
     User sends his username (Unique Identifier) and his Smart Card 
     Public Key information (MOD and EXP).
     Security: Message from user ciphered with Server Public Key"""
     # Decipher the Message with Server Private Key
     receivedData = dm.decryptMessageReceived(kwargs['data'].decode('hex'))
     # Verify if the user exists or has not finished the regist process
     if not DBmodule.db_existingUserBI(receivedData['userID']) or \
         DBmodule.db_registNotAuthenticate(receivedData['userID']):
         # Save User Public Key in a File
         destination = os.path.join('publicKey',
                                    str(receivedData['userID']) + '.pub')
         with open(destination, 'wb') as f:
             f.write("%s:%s" % (str(kwargs['exp']), str(kwargs['mod'])))
         # Update DB
         if not DBmodule.db_existingUserBI(receivedData['userID']):
             DBmodule.db_addNewUser(receivedData['username'],
                                    receivedData['userID'],
                                    pw.make_hash(receivedData['password']),
                                    kwargs['pub_key'])
         else:
             DBmodule.db_UserInfoUpdate(
                 receivedData['username'], receivedData['userID'],
                 pw.make_hash(receivedData['password']), kwargs['pub_key'])
         # Ask PAM what it needs to validate the user identity
         """ ----------------- PAM -------------------- """
         token = os.urandom(20)
         um.addRegist(receivedData['userID'], token)
         """ ----------------- PAM -------------------- """
         # Send to client the Token encrypted by User Public Key
         tf = tempfile.NamedTemporaryFile(delete=True)
         security.encrypt_RSA(
             security.importkey_RSA(kwargs['pub_key'].decode('hex')), token,
             tf)
         return tf.read().encode('hex')
     else:
         return "ERROR"
Exemplo n.º 7
0
def upload(fp, user):
    """Upload function, creates a temporary file to which
    the data of the user file is encrypted to. That temp file
    is then read by chunks and sent to the CherryPy server

    Security:
        - Authentication
        - File is encrypt with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for creating a signature
        - Private Key is accessed for encrypting the AES
          key
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    tf = tempfile.NamedTemporaryFile(delete=False)
    filesize = os.stat(fp).st_size
    hasher = security.Hasher()
    pu_key = getPubKey(username)
    enc, iv, aes = security.getCipher(security.importkey_RSA(pu_key))
    with open("PrivateKeys/Private_key_" + str(username), "rb") as f:
        priv = security.importkey_RSA(f.read())
    security.encrypt_AES(open(fp, "rb"), tf, enc, hasher, filesize)
    h = hasher.get()
    signature = security.signFile(priv, h)
    tf.close()
    f = FileLenIO(tf.name, "rb")
    list_pu_key = getUsersPubkey(fp.split("/")[-1], username)
    message = {"filename": fp.split("/")[-1], "iv": iv, "sign": signature.encode("hex")}
    messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex")
    # New File
    if list_pu_key == []:
        try:
            request = urllib2.Request("https://localhost:8080/upload", f)
            request.add_header("Content-Type", "application/octet-stream")
            request.add_header("username", username)
            request.add_header("aes", aes)
            request.add_header("data", messageToSend)
            request.add_header("Content-Length", os.stat(tf.name).st_size)
            response = urllib2.urlopen(request)
        except urllib2.URLError as e:
            print e.reason
            print "Currently, you are not a valid user!\nSafeBox Team"
    # New File Version
    else:
        RsaAES = security.decrypt_RSA(priv, aes.decode("hex"))
        fileList = []
        for publickey in list_pu_key:
            tf2 = tempfile.NamedTemporaryFile(delete=True)
            security.encrypt_RSA(security.importkey_RSA(publickey.decode("hex")), RsaAES, tf2)
            fileList += [tf2.read().encode("hex")]
        try:
            request = urllib2.Request("https://localhost:8080/uploadExistingFile", f)
            request.add_header("Content-Type", "application/octet-stream")
            request.add_header("username", username)
            request.add_header("aes", json.dumps(fileList))
            request.add_header("data", messageToSend)
            request.add_header("Content-Length", os.stat(tf.name).st_size)
            response = urllib2.urlopen(request)
        except urllib2.URLError as e:
            print e.reason
            print "Currently, you are not a valid user!\nSafeBox Team"
    os.remove(tf.name)
Exemplo n.º 8
0
def upload(fp, user):
    """Upload function, creates a temporary file to which
    the data of the user file is encrypted to. That temp file
    is then read by chunks and sent to the CherryPy server

    Security:
        - Authentication
        - File is encrypt with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for creating a signature
        - Private Key is accessed for encrypting the AES
          key
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    tf = tempfile.NamedTemporaryFile(delete=False)
    filesize = os.stat(fp).st_size
    hasher = security.Hasher()
    pu_key = getPubKey(username)
    enc, iv, aes = security.getCipher(security.importkey_RSA(pu_key))
    with open('PrivateKeys/Private_key_' + str(username), 'rb') as f:
        priv = security.importkey_RSA(f.read())
    security.encrypt_AES(open(fp, 'rb'), tf, enc, hasher, filesize)
    h = hasher.get()
    signature = security.signFile(priv, h)
    tf.close()
    f = FileLenIO(tf.name, 'rb')
    list_pu_key = getUsersPubkey(fp.split('/')[-1], username)
    message = {
        'filename': fp.split('/')[-1],
        'iv': iv,
        'sign': signature.encode('hex')
    }
    messageToSend = security.encryptS_AES(json.dumps(message),
                                          session.decode('hex')).encode('hex')
    # New File
    if list_pu_key == []:
        try:
            request = urllib2.Request('https://localhost:8080/upload', f)
            request.add_header('Content-Type', 'application/octet-stream')
            request.add_header('username', username)
            request.add_header('aes', aes)
            request.add_header('data', messageToSend)
            request.add_header('Content-Length', os.stat(tf.name).st_size)
            response = urllib2.urlopen(request)
        except urllib2.URLError as e:
            print e.reason
            print 'Currently, you are not a valid user!\nSafeBox Team'
    # New File Version
    else:
        RsaAES = security.decrypt_RSA(priv, aes.decode('hex'))
        fileList = []
        for publickey in list_pu_key:
            tf2 = tempfile.NamedTemporaryFile(delete=True)
            security.encrypt_RSA(
                security.importkey_RSA(publickey.decode('hex')), RsaAES, tf2)
            fileList += [tf2.read().encode('hex')]
        try:
            request = urllib2.Request(
                'https://localhost:8080/uploadExistingFile', f)
            request.add_header('Content-Type', 'application/octet-stream')
            request.add_header('username', username)
            request.add_header('aes', json.dumps(fileList))
            request.add_header('data', messageToSend)
            request.add_header('Content-Length', os.stat(tf.name).st_size)
            response = urllib2.urlopen(request)
        except urllib2.URLError as e:
            print e.reason
            print 'Currently, you are not a valid user!\nSafeBox Team'
    os.remove(tf.name)