def delete(filename_rand):
    """
    Upload the file to server.
    """
    url = base_url
    data = {
        'token': token,
        'file': filename_rand
    }
    try:
        r = requests.delete(url, params=data, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False
    # Parse result
    try:
        response = json.loads(r.text)
    except Exception as e:
        log.print_exception(e)
        log.print_error("authentication failure", "failed to decode server message '%s'" % (r.text))
        return False
    if response.get("status"):
        return True
    else:
        return False
def download_file(filename_ori, saveas=None):
    """
    Download and decrypt the file. Output the file.

    Raise when filename_ori is not in filelist
    """

    # Get the key, iv and tag from list
    record = None
    if filename_ori in filelist.mylist:
        record = filelist.mylist[filename_ori]
        r = download(record["filename_rand"])
    elif filename_ori in filelist.mylist_share:
        record = filelist.mylist_share[filename_ori]
        r = download(record["filename_rand"], record["shared_by"])
    else:
        log.print_error("error", "file '%s' not in record" % (filename_ori))
        return False

    if saveas == None:
        outputfile = filename_ori
    else:
        outputfile = saveas

    # Try decryption
    try:
        encrypt.decrypt_file(outputfile, record["filename_rand"],
                             record["key"], record["iv"], record["tag"])
    except:
        log.print_error("error", "failed to decrypt '%s'" % (filename_ori))
        return False
    return True
def download(filename_rand, saveas=None, shared_by=None):
    '''
    Download and save the file from server.
    '''
    if saveas == None:
        saveas = filename_rand
    url = base_url+"download"
    data = {
        'token': token,
        'file': filename_rand
    }
    if shared_by != None:
        data['shared_by'] = shared_by
    #r = requests.get(url, data=data, verify=True)
    try:
        r = requests.get(url, params=data, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False
    if r.content == b'404 page not found\n':
        return False
    try:
        with open(saveas, "wb") as f:
            f.write(r.content)
        return True
    except Exception as e:
        log.print_exception(e)
        log.print_error("IO error", "cannot open file '%s'" % (filename_rand))
        raise
def upload(filename_rand):
    """
    Upload the file to server.
    """
    url = base_url+"upload"
    data = {'token': token}
    files = {'document': open(filename_rand, 'rb')}
    #r = requests.post(url, data=data, files=files, verify=True)
    try:
        r = requests.post(url, data=data, files=files, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False
    files['document'].close()
    # Parse result
    try:
        response = json.loads(r.text)
    except Exception as e:
        log.print_exception(e)
        log.print_error("authentication failure", "failed to decode server message '%s'" % (r.text))
        return False
    if response.get("status"):
        return True
    else:
        return False
def share(recipient, data):
    """
    Upload the file to server.
    """
    url = base_url+"share"
    print(token)
    print(recipient)
    print(data)
    data = {
        'token': token,
        'recipient': recipient,
        'data': data
    }
    try:
        r = requests.post(url, data=data, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False
    # Parse result
    try:
        response = json.loads(r.text)
        print(response)
    except Exception as e:
        log.print_exception(e)
        log.print_error("authentication failure", "failed to decode server message '%s'" % (r.text))
        return False
    if response.get("status"):
        return True
    else:
        return False
Exemple #6
0
def ui_share():
    if not client_conn.is_login():
        print("Please login first")
        return
    # Enter recipient username
    print("Invite people (username): ", end='')
    recipient = input().strip()
    # Recipient's email
    recv_email = None
    print("Recipient's email address: ", end='')
    recv_email = input().strip()

    # Get target's public key
    choice = None
    while choice != "1" and choice != "2":
        print("Obtain the recipent's public key:")
        print(" 1) Download from Hong Kong Post")
        print(" 2) Input from file (debug)")
        print("Choice [1,2]: ", end='')
        choice = input().strip()
    public_key = None
    try:
        if choice == "1":
            # Download from HK Post
            public_key = rsa.get_cert(recv_email, True)
            sender = "*****@*****.**"
        if choice == "2":
            # Import from file
            sender = "*****@*****.**"
            filename = "key/public_key.pem"
            public_key = rsa.load_public_cert_from_file(filename)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "failed to load cert")
        return 

    # Get user's private key to signoff
    if os.path.isfile("/home/star/.ssh/me.key.pem2"):
        private_key = rsa.load_private_cert_from_file("/home/star/.ssh/me.key.pem2")
    else:
        private_key = rsa.load_private_cert_from_file("key/private_key.pem")

    # Encrypt the filelist record
    print("File to share: ", end='')
    filename = input()
    record = filelist.export_record(filename, sender, recv_email, public_key, private_key)
    if record == None:
        print("Failed to share file")
        return
    # Send to server
    client_conn.share(recipient, record)
def get_share():
    """
    Upload the file to server.
    """
    url = base_url+"listshare"
    data = {
        'token': token,
    }
    data = {"token": token}
    try:
        r = requests.get(url, params=data, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False
    # Parse result
    try:
        response = json.loads(r.text)
        print(response)
    except Exception as e:
        log.print_exception(e)
        log.print_error("authentication failure", "failed to decode server message '%s'" % (r.text))
        return False
    if not response.get("status"):
        return False
    if response["records"] == None:
        return False
    for i in response["records"]:
        sender = i['Sender']
        record = i['Record']
        print("Sender:",sender)
        print("Record:",record)
        try:
            if os.path.isfile("/home/star/.ssh/me.key.pem2"):
                public_key = rsa.get_cert("*****@*****.**")
            else:
                public_key = rsa.load_public_cert_from_file("key/public_key.pem")
            if os.path.isfile("/home/star/.ssh/me.key.pem2"):
                private_key = rsa.load_private_cert_from_file("/home/star/.ssh/me.key.pem2")
            else:
                private_key = rsa.load_private_cert_from_file("key/private_key.pem")
            share = filelist.import_record(record, public_key, private_key)
            print(share)
            if share != None:
                filelist.append_share(share['filename_ori'], share['filename_rand'],
                            share['key'], share['iv'], share['tag'], sender)
        except:
            print("Failed to decrypt message")
            pass
Exemple #8
0
def load_public_cert_from_file(filename):
    """
    Load pem public key from file
    """
    try:
        with open(filename, "rb") as key_file:
            public_key = serialization.load_pem_public_key(
                    key_file.read(),
                    backend=default_backend()
            )
            return public_key
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "failed to open file '%s'" % (r.text))
        return False
def upload_file(filename_ori):
    """
    Encrypt and upload the file using random filename, also add record in list.
    """
    # Encrypt the file
    data = None
    try:
        data = encrypt.encrypt_file(filename_ori)
    except:
        log.print_error("error", "failed to encrypt file '%s'" % (filename_ori))
        return False

    # Store the filename, key, iv and tag to list
    filelist.append(data["filename_ori"], data["filename_rand"], data["key"],
                    data["iv"], data["tag"])
    # Upload cipher text to server
    return upload(data["filename_rand"])
Exemple #10
0
def encrypt_file(filename_ori):
    '''
    Encrypt a file and store the ciphertext into another file.

    This function will generate a random key and iv for encryption.
    The filename of the output file will be randomly generated.
    
    Return a dict containing:
    {original filename, randomly generated filename, key, iv, tag}

    Raise IOError when failed to open the file.
    '''

    # Read file
    data = None
    try:
        with open(filename_ori, "rb") as f:
            data = f.read()
    except Exception as e:
        log.print_exception(e)
        log.print_error("IO error", "cannot open file '%s'" % (filename_ori))
        raise

    # Encrypt using random key and iv
    ret = encrypt_rand(data)

    # Write ciphertext using random filename
    filename_rand = str(uuid.uuid4())+".data"
    try:
        with open(filename_rand, "wb") as f:
            f.write(ret['cipher'])
    except Exception as e:
        log.print_exception(e)
        log.print_error("IO error", "cannot write to file '%s'"
						% (filename_rand))
        raise
    
    # Store original filename and the generated filename
    ret.pop("cipher", None)
    ret['filename_ori'] = filename_ori
    ret['filename_rand'] = filename_rand
    return ret
Exemple #11
0
def decrypt_file(filename_ori, filename_rand, key, iv, tag):
    '''
    Decrypt a file and write the plaintext to filename_ori.

    Raise error when failed to open/write file or decryption error.
    Any modification to the cipher will cause the decryption to fail.
    '''
    ret = None
    # Read file
    try:
        with open(filename_rand, "rb") as f:
            data = f.read()
    except Exception as e:
        log.print_exception(e)
        log.print_error("IO error", "cannot open file '%s'" % (filename_rand))
        raise

    # Decrypt
    try:
        ret = decrypt(key, iv, tag, data)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "failed to decrypt message")
        raise

    # Write to filename_ori
    try:
        with open(filename_ori, "wb") as f:
            data = f.write(ret)
    except Exception as e:
        log.print_exception(e)
        log.print_error("IO error", "cannot write to file '%s'"
						% (filename_rand))
        raise
def logout():
    global token
    if token == None:
        return False
    url = base_url + "logout"
    data = {"token": token}
    #r = requests.get(url, data=data, verify=True)
    try:
        r = requests.get(url, params=data, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False
    # Parse result
    try:
        response = json.loads(r.text)
    except Exception as e:
        log.print_exception(e)
        log.print_error("logout failed", "failed to decode server message '%s'" % (r.text))
        return False

    if response.get("status", False):
        token = None
        # Logout successful
        return True
    else:
        # Logout failure
        log.print_error("logout failed", "failed to logout '%s'" % (r.text))
        print("d")
        return False
def authenticate(username, password):
    url = base_url + "login"
    payload = {
            'client_id': username,
            'client_secret': password
    }
    # Request to server
    # For real cert
    # r = requests.get(url, data=data, verify=True)
    # For self cert
    try:
        r = requests.post(url, data=payload, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False

    # Parse result
    try:
        response = json.loads(r.text)
    except Exception as e:
        log.print_exception(e)
        log.print_error("authentication failure", "failed to decode server message '%s'" % (r.text))
        return False
    if response.get("status", False) and response.get("token", None) != None:
        # Authentication success
        global token
        global client_id
        token = response.get("token")
        client_id = username
        return True
    else:
        # Authentication failure
        log.print_error("authentication failure", "wrong username or password")
        return False
Exemple #14
0
def decrypt(key, iv, tag, cipherText):
    '''
    Decrypt byte data using the given key, iv and tag.

    Return the decrypted byte data.

    Raise exception when MAC tag didn't match.
    '''
    decryptor = Cipher(
        algorithms.AES(key),
        modes.GCM(iv, tag),
        backend=default_backend()
    ).decryptor()

    # Decryption gets us the authenticated plaintext.
    # If the tag does not match an InvalidTag exception will be raised.
    ret = None
    try:
        ret = decryptor.update(cipherText) + decryptor.finalize()
    except exceptions.InvalidTag:
        log.print_error("decrytion error", "message have been modified")
        raise
    return ret
def registrate(username, password):
    url = base_url + "registration"
    payload = {
            'client_id': username,
            'client_secret': password
    }
    try:
        r = requests.post(url, data=payload, verify=cert)
    except Exception as e:
        log.print_exception(e)
        log.print_error("error", "connection failure")
        return False

    # Parse result
    try:
        response = json.loads(r.text)
    except Exception as e:
        log.print_exception(e)
        log.print_error("authentication failure", "failed to decode server message '%s'" % (r.text))
        return False
    if response.get("status"):
        return True
    else:
        return False
Exemple #16
0
    print("=============================")
    print("Encrypt / Decrypt byte string")
    ret = encrypt_rand(b"Testing Encryption")
    ret2 = decrypt(ret['key'], ret['iv'], ret['tag'], ret['cipher'])
    print(ret['cipher'])
    print(ret2)
    print(ret2.decode(encoding='UTF-8'))

    print("=============================")
    print("Try modify data + decrypt")
    # Try modify + decrypt
    try:
        ret = decrypt(ret['key'], ret['iv'], ret['tag'], b"Fake message")
        print(ret)
    except:
        log.print_error("error", "failed to decrypt file")

    print("=============================")
    print("Encrypt non-existing file")
    # Encrypt non-existing file
    try:
        ret = encrypt_file("testing.t")
        print(ret)
    except:
        log.print_error("error", "failed to encrypt file")

    print("=============================")
    print("Encrypt / Decrypt file")
    try:
        ret = encrypt_file("testing.txt")
        print(ret)
Exemple #17
0
def run(last_valid_frame, frame):
    # start_btn_x,start_btn_y = feature_detetor.detect_start_btn(last_valid_frame,frame)

    # hand_x,hand_y = feature_detetor.detect_hand(last_valid_frame,frame)

    # print hand_x, hand_y
    print "stage-1"
    global is_hand_appearing
    global hand_disappear_cnt
    global detected_x
    global detected_y
    global org_size
    global failed_counter
    global success_counter
    global current_image
    global filter_image

    is_hand_appearing = True

    # if abs(hand_x - start_btn_x) < 200 and abs(hand_y - start_btn_y) < 200:
    #     # the hand is right above the btn
    #     is_hand_appearing = True
    #     hand_disappear_cnt = 0
    # else:
    #     hand_disappear_cnt += 1
    #     if hand_disappear_cnt > 5:
    #         is_hand_appearing = False
    is_flash_detected = False

    # dynamically update the orange button location, pass it into the flash detection
    x, y, size, is_success = feature_detetor.detect_orange_btn(
        last_valid_frame, frame, detected_x, detected_y, org_size, 0)
    #current_image, filter_image = feature_detetor.get_two_image()
    detected_x = x
    detected_y = y
    org_size = size

    # if we detect the aed device is not within the screen or orange button is missing for
    if is_success == False:
        # using a tolerate false detection range
        log.print_error(TAG, "fail to find orange button")
        failed_counter += 1
        if failed_counter > Failed_Tolerant:
            # the aed device is missing, start the refind process
            print "-------------------------------------------------------------------------------------------"
            log.print_error(TAG,
                            "The AED device is missing, preparation again")
            is_find = stage_pre_main.prepare(last_valid_frame, frame)
            if is_find:
                failed_counter = 0
                detected_x, detected_y, org_size = stage_pre_main.retrieve_org_btn_params(
                )

    if is_hand_appearing:
        is_detect = flash_detetor.flash_detection(last_valid_frame, frame,
                                                  detected_x, detected_y,
                                                  org_size, 0)
        current_image, filter_image = flash_detetor.get_two_image()
        if is_detect:
            return True
    return False