Ejemplo n.º 1
0
def download(filename, destination, privpath, user):
    """Download function, creates a temporary file to
    where the encrypted file is streamed to, then it is read
    chunk by chunk and decrypted.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    message = {'filename': filename}
    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/download', datagen,
                               headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader('filename')
        date = json.loads(
            security.decryptS_AES(data.info().getheader('data').decode('hex'),
                                  session.decode('hex')))
        aes = data.info().getheader('aes').decode('hex')
        iv = date['iv'].decode('hex')
        signature = date['sign'].decode('hex')

        with open(privpath, 'rb') as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)

        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        with open(os.path.join(str(destination), filename), 'wb') as out:
            security.decrypt_AES(decipher, tf, out, hasher)
        new = hasher.get()
        if security.verifyFile(pub, new, signature):
            print 'The File was not changed!'
        else:
            print 'The File was changed!'
        tf.close()
    except urllib2.HTTPError as e:
        print str(e.code) + ': ' + e.reason
        print 'Currently, you are not a valid user!\nSafeBox Team'
Ejemplo n.º 2
0
def diff(user, filename, privpath, filefp):
    """Function for getting the difference between a file in
    the server and a user file, works like download except no file
    is written.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"   """
    (username, session) = user.getInfo()
    message = {'filename': filename}
    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/download', datagen,
                               headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader('filename')
        date = json.loads(
            security.decryptS_AES(data.info().getheader('data').decode('hex'),
                                  session.decode('hex')))
        aes = data.info().getheader('aes').decode('hex')
        iv = date['iv'].decode('hex')
        signature = date['sign'].decode('hex')
        with open(privpath, 'rb') as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)
        out = tempfile.NamedTemporaryFile(delete=True)
        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        security.decrypt_AES(decipher, tf, out, hasher)
        out.seek(0)
        new = hasher.get()
        comp = open(filefp, 'rb').readlines()
        cenas = out.readlines()
        return diffchecker(comp, cenas)
    except urllib2.HTTPError as e:
        print str(e.code) + ': ' + e.reason
        print 'Currently, you are not a valid user!\nSafeBox Team'
Ejemplo n.º 3
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'
Ejemplo n.º 4
0
def download(filename, destination, privpath, user):
    """Download function, creates a temporary file to
    where the encrypted file is streamed to, then it is read
    chunk by chunk and decrypted.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    message = {"filename": filename}
    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/download", datagen, headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader("filename")
        date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex")))
        aes = data.info().getheader("aes").decode("hex")
        iv = date["iv"].decode("hex")
        signature = date["sign"].decode("hex")

        with open(privpath, "rb") as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)

        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        with open(os.path.join(str(destination), filename), "wb") as out:
            security.decrypt_AES(decipher, tf, out, hasher)
        new = hasher.get()
        if security.verifyFile(pub, new, signature):
            print "The File was not changed!"
        else:
            print "The File was changed!"
        tf.close()
    except urllib2.HTTPError as e:
        print str(e.code) + ": " + e.reason
        print "Currently, you are not a valid user!\nSafeBox Team"
Ejemplo n.º 5
0
def diff(user, filename, privpath, filefp):
    """Function for getting the difference between a file in
    the server and a user file, works like download except no file
    is written.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"   """
    (username, session) = user.getInfo()
    message = {"filename": filename}
    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/download", datagen, headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader("filename")
        date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex")))
        aes = data.info().getheader("aes").decode("hex")
        iv = date["iv"].decode("hex")
        signature = date["sign"].decode("hex")
        with open(privpath, "rb") as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)
        out = tempfile.NamedTemporaryFile(delete=True)
        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        security.decrypt_AES(decipher, tf, out, hasher)
        out.seek(0)
        new = hasher.get()
        comp = open(filefp, "rb").readlines()
        cenas = out.readlines()
        return diffchecker(comp, cenas)
    except urllib2.HTTPError as e:
        print str(e.code) + ": " + e.reason
        print "Currently, you are not a valid user!\nSafeBox Team"
Ejemplo n.º 6
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"
Ejemplo n.º 7
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
Ejemplo n.º 8
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
Ejemplo n.º 9
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"
Ejemplo n.º 10
0
def logInUser(userID, password, card):
    """Function for Logging into the server. handled server-side
    Security: Encrypted with Server Public Key
    """
    register_openers().add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
    try:
        pwd = security.PBKDKF2.pwsend(password)
        params = {"userID": userID, "password": pwd}
        sendparam = encryptMessageToSendRSA(params)
        datagen, headers = multipart_encode(sendparam)
        request = urllib2.Request("https://localhost:8080/logInUser", datagen, headers)
        result = urllib2.urlopen(request).read()
        if result == "ERROR":
            return False
        elif result == "REGIST_AGAIN":
            return False
        else:
            clientSession = DiffieHellman.DiffieHellman()
            # receive token and decrypt it with
            private_file = os.path.join("PrivateKeys", "Private_key_" + str(userID))
            with open(private_file, "rb") as f:
                private_key = security.importkey_RSA(f.read())
                loginMessage = json.loads(result)
                receivedMessage = security.decrypt_RSA(private_key, loginMessage["token"].decode("hex"))
                # sign token
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                reply = card.connect(0L)
                if reply:
                    tokenSigned = card.sign(receivedMessage)
                    card.disconnect()
                else:
                    tokenSigned = ""
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                message = {"userID": userID, "password": pwd}
                # send token back
                tokenchiphered = encryptMessageToSendRSA({"token": tokenSigned})
                sendparam = encryptMessageToSendRSA(message)
                messageToSend = {
                    "message": sendparam,
                    "session": json.dumps(clientSession.publicKey),
                    "token": tokenchiphered,
                }
                datagen, headers = multipart_encode(messageToSend)
                request = urllib2.Request("https://localhost:8080/authTokenValidation", datagen, headers)
                result = urllib2.urlopen(request).read()
                if result == "OK":
                    # Establish Session
                    clientSession.genKey(loginMessage["session"])
                    destination = os.path.join("download", "session.txt")
                    user = User(userID, clientSession.getKey().encode("hex"))
                    print "Logged In: " + str(userID)

                    return user
                return False
    except urllib2.URLError as e:
        print e.reason
        print "Currently, you are not a valid user!\nSafeBox Team"
        return False
Ejemplo n.º 11
0
def registUser(username, password, mail, card):
    """Function for contact the server and send the information
    of the user.
    Security: Encrypted with Server Public Key
    """
    register_openers().add_handler(
        urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
    try:
        if card.connect(0l) == True:
            pwd = security.PBKDKF2.pwsend(password)
            mod, exp = card.getAuth()
            userID = username
            public_key, private_key = security.generate_RSA()
            params = {'userID': userID, 'username': username, 'password': pwd}
            sendparam = encryptMessageToSendRSA(params)
            sendparam['pub_key'] = public_key.encode('hex')
            sendparam['mod'] = mod
            sendparam['exp'] = exp
            datagen, headers = multipart_encode(sendparam)
            request = urllib2.Request('https://localhost:8080/registUser',
                                      datagen, headers)
            result = urllib2.urlopen(request).read()
            if result != "ERROR":
                token = security.decrypt_RSA(
                    security.importkey_RSA(private_key), result.decode('hex'))
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                tokenSigned = card.sign(token)
                card.disconnect()
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                # send token back
                message = {'userID': userID, 'password': pwd}
                # send token back
                tokenchiphered = encryptMessageToSendRSA(
                    {'token': tokenSigned})
                sendparam = encryptMessageToSendRSA(message)
                messageToSend = {'message': sendparam, 'token': tokenchiphered}
                datagen, headers = multipart_encode(messageToSend)
                request = urllib2.Request(
                    'https://localhost:8080/registTokenValidation', datagen,
                    headers)
                result = urllib2.urlopen(request).read()
                if result != "ERROR":
                    # Verify if the token was correct
                    """ SAVE PRIVATE KEY FILE -----> Cipher with Password"""
                    private_file = os.path.join('PrivateKeys',
                                                'Private_key_' + str(userID))
                    #messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex')
                    #ciphered_priv_key = security.encryptS_AES(json.dumps(private_key), pwd).encode('hex')
                    with open(private_file, 'wb') as f:
                        f.write(private_key)
                    return True
        return False
Ejemplo n.º 12
0
def registUser(username, password, mail, card):
    """Function for contact the server and send the information
    of the user.
    Security: Encrypted with Server Public Key
    """
    register_openers().add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
    try:
        if card.connect(0L) == True:
            pwd = security.PBKDKF2.pwsend(password)
            mod, exp = card.getAuth()
            userID = username
            public_key, private_key = security.generate_RSA()
            params = {"userID": userID, "username": username, "password": pwd}
            sendparam = encryptMessageToSendRSA(params)
            sendparam["pub_key"] = public_key.encode("hex")
            sendparam["mod"] = mod
            sendparam["exp"] = exp
            datagen, headers = multipart_encode(sendparam)
            request = urllib2.Request("https://localhost:8080/registUser", datagen, headers)
            result = urllib2.urlopen(request).read()
            if result != "ERROR":
                token = security.decrypt_RSA(security.importkey_RSA(private_key), result.decode("hex"))
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                tokenSigned = card.sign(token)
                card.disconnect()
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                # send token back
                message = {"userID": userID, "password": pwd}
                # send token back
                tokenchiphered = encryptMessageToSendRSA({"token": tokenSigned})
                sendparam = encryptMessageToSendRSA(message)
                messageToSend = {"message": sendparam, "token": tokenchiphered}
                datagen, headers = multipart_encode(messageToSend)
                request = urllib2.Request("https://localhost:8080/registTokenValidation", datagen, headers)
                result = urllib2.urlopen(request).read()
                if result != "ERROR":
                    # Verify if the token was correct
                    """ SAVE PRIVATE KEY FILE -----> Cipher with Password"""
                    private_file = os.path.join("PrivateKeys", "Private_key_" + str(userID))
                    # messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex')
                    # ciphered_priv_key = security.encryptS_AES(json.dumps(private_key), pwd).encode('hex')
                    with open(private_file, "wb") as f:
                        f.write(private_key)
                    return True
        return False
    except urllib2.URLError as e:
        print e.reason
        print "Currently, you are not a valid user!\nSafeBox Team"
        return False
Ejemplo n.º 13
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"
Ejemplo n.º 14
0
 def signToken(self, token):
     with open('PrivateKey', 'rb') as f:
         serverPrivateKey = security.importkey_RSA(f.read())
     return security.signFile(serverPrivateKey, token)
Ejemplo n.º 15
0
 def decryptMessageReceived(self, receivedCipheredData):
     with open('PrivateKey', 'rb') as f:
         serverPrivateKey = security.importkey_RSA(f.read())
     return json.loads(
         security.decrypt_RSA(serverPrivateKey, receivedCipheredData))
Ejemplo n.º 16
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)
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
def logInUser(userID, password, card):
    """Function for Logging into the server. handled server-side
    Security: Encrypted with Server Public Key
    """
    register_openers().add_handler(
        urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
    try:
        pwd = security.PBKDKF2.pwsend(password)
        params = {'userID': userID, 'password': pwd}
        sendparam = encryptMessageToSendRSA(params)
        datagen, headers = multipart_encode(sendparam)
        request = urllib2.Request('https://localhost:8080/logInUser', datagen,
                                  headers)
        result = urllib2.urlopen(request).read()
        if result == "ERROR":
            return False
        elif result == "REGIST_AGAIN":
            return False
        else:
            clientSession = DiffieHellman.DiffieHellman()
            # receive token and decrypt it with
            private_file = os.path.join('PrivateKeys',
                                        'Private_key_' + str(userID))
            with open(private_file, 'rb') as f:
                private_key = security.importkey_RSA(f.read())
                loginMessage = json.loads(result)
                receivedMessage = security.decrypt_RSA(
                    private_key, loginMessage['token'].decode('hex'))
                # sign token
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                reply = card.connect(0l)
                if reply:
                    tokenSigned = card.sign(receivedMessage)
                    card.disconnect()
                else:
                    tokenSigned = ""
                """ -----------------SIGN CC/PrivateKey By PWD -------------------- """
                message = {'userID': userID, 'password': pwd}
                # send token back
                tokenchiphered = encryptMessageToSendRSA(
                    {'token': tokenSigned})
                sendparam = encryptMessageToSendRSA(message)
                messageToSend = {
                    'message': sendparam,
                    'session': json.dumps(clientSession.publicKey),
                    'token': tokenchiphered
                }
                datagen, headers = multipart_encode(messageToSend)
                request = urllib2.Request(
                    'https://localhost:8080/authTokenValidation', datagen,
                    headers)
                result = urllib2.urlopen(request).read()
                if result == "OK":
                    # Establish Session
                    clientSession.genKey(loginMessage['session'])
                    destination = os.path.join('download', 'session.txt')
                    user = User(userID, clientSession.getKey().encode('hex'))
                    print "Logged In: " + str(userID)

                    return user
                return False
    except urllib2.URLError as e:
        print e.reason
        print 'Currently, you are not a valid user!\nSafeBox Team'
        return False