Beispiel #1
0
def attr_auth_device_keygen(device_id, attr_list, token):
    if device_id not in " ".join(attr_list):
        click.echo(
            f"attr_list argument should contain device_id ({device_id})")
        return
    doc = search_tinydb_doc(path, 'aa_keys', where('public_key').exists())
    if not doc:
        with click.Context(get_attr_auth_keys) as ctx:
            click.echo(
                f"Public key not present, please use: {ctx.command.name}")
            click.echo(get_attr_auth_keys.get_help(ctx))
            return

    data = {"attr_list": " ".join(attr_list)}
    r = requests.post(AA_URL_DEVICE_KEYGEN,
                      headers={"Authorization": token},
                      data=data,
                      verify=VERIFY_CERTS)
    content = r.content.decode('unicode-escape')
    json_content = json_string_with_bytes_to_dict(content)
    if not json_content["success"]:
        click.echo(json_content)
        return

    t = get_tinydb_table(path, "device_keys")
    device_data_doc = {
        "private_key": json_content["private_key"],
        "attr_list": attr_list,
    }
    t.update(set("device_data:data", device_data_doc),
             Query().device_id == device_id)
Beispiel #2
0
def get_foreign_device_data(device_id, data):
    doc = search_tinydb_doc(path, 'device_keys',
                            Query().device_id == str(device_id))
    if not doc:
        click.echo(
            f"Keys for device: {device_id} are missing. You are probably not authorized to use it."
        )

    decrypted = []
    for row in data["device_data"]:
        try:
            decrypted.append(
                decrypt_using_abe_serialized_key(
                    row["data"], doc["device_data:data"]["public_key"],
                    doc["device_data:data"]["private_key"]))
        except:
            click.echo("Cannot decrypt row.")

    result = []
    for val in decrypted:
        try:
            if val.endswith("0"):
                result.append(unpad_payload_attr(val))
        except Exception as e:
            click.echo(str(e))
    click.echo(result)
Beispiel #3
0
def is_global_bi_key_missing(command, message):
    doc = search_tinydb_doc(path, 'global', Query().bi_key.exists())
    if not doc:
        with click.Context(command) as ctx:
            click.echo(f"{message}, please use: {ctx.command.name}")
            click.echo(command.get_help(ctx))
            return True
    return False
Beispiel #4
0
def is_device_bi_key_missing(device_id, command, message):
    doc = search_tinydb_doc(path, 'device_keys',
                            Query().device_id == str(device_id))
    if doc is None or "bi_key" not in doc:
        with click.Context(command) as ctx:
            click.echo(f"{message}, please use: {ctx.command.name}")
            click.echo(command.get_help(ctx))
            return True
    return False
Beispiel #5
0
def get_encryption_keys(device_id, db_keys):
    """
    Retrieves encryption (decryption) keys corresponding to :param db_keys from TinyDB file
    :param device_id
    :param db_keys: list of TinyDB key names, e.g.: ["device_type:description", "action:name"]
    :return: dictionary of key, value pair of column name and encryption string, e.g.: {"action:name": "9dd1a57836a5...858372a8c0c42515", ...}
    """
    doc = search_tinydb_doc(path, 'device_keys',
                            Query().device_id == str(device_id))
    result = {}
    for key in db_keys:
        if ":" in key:
            if key == "device_data:data":
                result[key] = [get_aa_public_key(), doc[key]["private_key"]]
            else:
                result[key] = doc[key]
    return result
Beispiel #6
0
def attr_auth_keygen(api_username, device_id, attr_list, token):
    doc = search_tinydb_doc(path, 'aa_keys', where('public_key').exists())
    if not doc:
        with click.Context(get_attr_auth_keys) as ctx:
            click.echo(
                f"Public key not present, please use: {ctx.command.name}")
            click.echo(get_attr_auth_keys.get_help(ctx))
            return
    data = {
        "attr_list": " ".join(attr_list),
        "api_username": api_username,
        "device_id": device_id
    }
    r = requests.post(AA_URL_KEYGEN,
                      headers={"Authorization": token},
                      data=data,
                      verify=VERIFY_CERTS)
    click.echo(r.content.decode('unicode-escape'))
Beispiel #7
0
def _setup_client(user_id):
    def on_publish(client, userdata, result):
        click.echo("Data published")

    client = paho.Client(user_id)
    client.on_publish = on_publish
    client.tls_set(ca_certs=os.path.join(os.path.dirname(__file__),
                                         "certs/server.crt"),
                   certfile=None,
                   keyfile=None,
                   tls_version=ssl.PROTOCOL_TLSv1_2)
    client.tls_insecure_set(True)
    doc = search_tinydb_doc(
        path, 'credentials',
        where('broker_id').exists() & where('broker_password').exists())
    client.username_pw_set(f"u:{doc['broker_id']}", doc['broker_password'])
    client.connect(MQTT_BROKER, MQTT_PORT, 30)
    return client
Beispiel #8
0
def send_message(user_id, device_id, data):
    doc = search_tinydb_doc(path, 'device_keys',
                            Query().device_id == device_id)

    if not doc:
        with click.Context(send_key_to_device) as ctx:
            click.echo(
                f"Keys for device {device_id} not present, please use: {ctx.command.name}"
            )
            click.echo(send_key_to_device.get_help(ctx))
            return

    fernet_key = hex_to_fernet(doc["shared_key"])
    token = fernet_key.encrypt(data.encode())

    client = _setup_client(user_id)

    payload = f'"{json.dumps(_create_payload({"ciphertext": token.decode()}, user_id))}"'
    ret = client.publish(f"u:{user_id}/d:{device_id}/", payload)
    click.echo(f"RC and MID = {ret}")
Beispiel #9
0
def set_action(device_id, name, token):
    doc = search_tinydb_doc(path, 'device_keys',
                            Query().device_id == str(device_id))
    if not doc:
        with click.Context(send_column_keys) as ctx:
            click.echo(
                f"Keys for device {device_id} not present, please use: {ctx.command.name}"
            )
            click.echo(send_column_keys.get_help(ctx))
            return

    data = {
        "device_id": device_id,
        "name": encrypt_using_fernet_hex(doc["action:name"], name),
        "correctness_hash": correctness_hash(name),
        "name_bi": blind_index(get_device_bi_key(device_id), name)
    }
    r = requests.post(URL_SET_ACTION,
                      headers={"Authorization": token},
                      data=data,
                      verify=VERIFY_CERTS)
    click.echo(r.content.decode('unicode-escape'))
Beispiel #10
0
def get_aa_public_key():
    doc = search_tinydb_doc(path, 'aa_keys', where('public_key').exists())
    return doc["public_key"]
Beispiel #11
0
def get_device_bi_key(device_id):
    doc = search_tinydb_doc(path, 'device_keys',
                            Query().device_id == str(device_id))
    return hex_to_key(doc["bi_key"])