Beispiel #1
0
def Main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    conffiles = ['work_order_tests.toml']
    confpaths = [".", TCFHOME + "/" + "config", "../../etc"]

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument('--config-dir', help='configuration folder', nargs='+')
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        config_json_str = json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    ParseCommandLine(config, remainder)
    LocalMain(config)
Beispiel #2
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    conf_file = ['listener_config.toml']
    conf_path = [get_config_dir('listener/')]

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument('--config-dir', help='configuration folder', nargs='+')
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_file = options.config

    if options.config_dir:
        conf_path = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_file, conf_path)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    host_name, port = parse_command_line(config, remainder)
    start_listener(host_name, port, TCSListener(config))
Beispiel #3
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # Parse out the configuration file first
    conffiles = ['tcs_config.toml']
    confpaths = [".", TCFHOME + "/config"]

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument('--config-dir', help='configuration folder', nargs='+')
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    parse_command_line(config, remainder)
    local_main(config)
Beispiel #4
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    conffiles = ["tcs_config.toml"]
    confpaths = [".", TCFHOME + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    parse_command_line(config, remainder)
    logger.info("Starting Enclave manager")
    start_enclave_manager(config)
Beispiel #5
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["kme_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--bind",
                        help="KME listener url for requests to KME",
                        type=str)
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)
    parser.add_argument(
        "--wpe-mrenclave",
        help="MRENCLAVE of WPE that can register with this KME",
        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.bind:
        config["KMEListener"]["bind"] = options.bind
    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id
    if options.wpe_mrenclave:
        config["EnclaveModule"]["wpe_mrenclave"] = options.wpe_mrenclave

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    logger.info("Initialize KeyManagement enclave_manager")
    enclave_manager = KeyManagementEnclaveManager(config)
    enclave_manager.init_kv_delegates()
    enclave_manager.setup_enclave()
    logger.info("About to start KeyManagement Enclave manager")
    enclave_manager.start_enclave_manager()
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["wpe_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--kme_listener_url",
                        help="KME listener url for requests to KME",
                        type=str)
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.kme_listener_url:
        config["KMEListener"]["kme_listener_url"] = options.kme_listener_url
    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    try:
        EnclaveManager.parse_command_line(config, remainder)
        logger.info("Initialize WorkOrderProcessor enclave_manager")
        enclave_manager = WorkOrderProcessorEnclaveManager(config)
        logger.info("About to start WorkOrderProcessor Enclave manager")
        enclave_manager.start_enclave_manager()
    except Exception as e:
        logger.error("Exception occurred while running WPE, " +
                     "exiting WPE enclave manager")
        exit(1)
Beispiel #7
0
def Main(args=None):
    ParseCommandLine(args)

    if verbose:
        config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}
    else:
        config["Logging"] = {"LogFile": "__screen__", "LogLevel": "WARN"}
    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    logger.info("***************** TRUSTED COMPUTE FRAMEWORK (TCF)" + \
     " *****************")

    # Retrieve Worker Registry
    if not off_chain:
        direct_wrapper.init_worker_registry_list(config)
        registry_lookup_result = direct_wrapper.registry_lookup()
        if (registry_lookup_result[0] == 0):
            logger.warn("No registries found")
            sys.exit(1)
        registry_retrieve_result = direct_wrapper.registry_retrieve(
            registry_lookup_result[2][0])
        config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

    # Prepare worker
    direct_wrapper.init_worker_registry(config)

    global worker_id
    if not worker_id:
        worker_lookup_json = jrpc_request.WorkerLookupJson(1, worker_type=1)
        worker_lookup_result = direct_wrapper.worker_lookup(worker_lookup_json)
        if "result" in worker_lookup_result and \
         "ids" in worker_lookup_result["result"].keys():
            if worker_lookup_result["result"]["totalCount"] != 0:
                worker_id = worker_lookup_result["result"]["ids"][0]
            else:
                logger.error("ERROR: No workers found")
                sys.exit(1)
        else:
            logger.error("ERROR: Failed to lookup worker")
            sys.exit(1)

    worker_retrieve_json = jrpc_request.WorkerRetrieveJson(2, worker_id)
    worker_obj.load_worker(
        direct_wrapper.worker_retrieve(worker_retrieve_json))
    logger.info("**********Worker details Updated with Worker ID" + \
     "*********\n%s\n", worker_id)

    # Open GUI
    GuiMain()
Beispiel #8
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../")

    conf_files = ["graphene_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    try:
        enclave_manager = GrapheneEnclaveManager(config)
        enclave_manager.init_kv_delegates()
        enclave_manager.setup_enclave()
        logger.info("About to start Graphene Enclave manager")
        enclave_manager.start_enclave_manager()
    except Exception as ex:
        logger.error("Error starting Graphene Enclave Manager: " + str(e))
    # Disconnect ZMQ socket.
    if self.zmq_socket:
        self.zmq_socket.disconnect()
Beispiel #9
0
def initialize_logging(config):
    """Initialize logging."""

    if verbose:
        config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}
    else:
        config["Logging"] = {"LogFile": "__screen__", "LogLevel": "WARN"}
    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)
def setup_config(args=None):
    """ Fixture to setup initial config for pytest session. """

    # parse out the configuration file first
    conffiles = ["tcs_config.toml"]
    confpaths = [".", TCFHOME + "/config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--connect_uri", action="store",
                        default="http://localhost:1947",
                        help="server uri")
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    if options.connect_uri:
        server_uri = options.connect_uri

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        config_json_str = json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger((logging.getLogger("STDOUT"),
                                           logging.DEBUG))
    sys.stderr = plogger.stream_to_logger((logging.getLogger("STDERR"),
                                           logging.WARN))

    logger.info("configuration for the session: %s", config)
    uri_client = HttpJrpcClient(server_uri)

    # private_key of client
    private_key = enclave_helper.generate_signing_keys()

    # Initializing worker object to pass client default worker
    # data to testcases
    worker_obj = worker.SGXWorkerDetails()

    worker_obj, err_cd = worker_lookup_retrieve(config, worker_obj, uri_client)

    # return worker_obj, sig_obj, uri_client, private_key, err_cd
    return worker_obj, uri_client, private_key, err_cd
Beispiel #11
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["singleton_enclave_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)
    parser.add_argument("--workloads",
                        help="Comma-separated list of workloads supported",
                        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.workloads:
        config["WorkerConfig"]["workloads"] = options.workloads
    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    logger.info("Initialize singleton enclave_manager")
    enclave_manager = SingletonEnclaveManager(config)
    logger.info("About to start Singleton Enclave manager")
    enclave_manager.start_enclave_manager()
Beispiel #12
0
def setup_config(args=None):
    """ Fixture to setup initial config for pytest session. """

    # parse out the configuration file first
    conffiles = ["tcs_config.toml"]
    confpaths = [".", TCFHOME + "/config"]

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        config_json_str = json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(
        (logging.getLogger("STDOUT"), logging.DEBUG))
    sys.stderr = plogger.stream_to_logger(
        (logging.getLogger("STDERR"), logging.WARN))

    logger.info("configuration for the session: %s", config)
Beispiel #13
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["kme_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    logger.info("Initialize KeyManagement enclave_manager")
    enclave_manager = KeyManagementEnclaveManager(config)
    logger.info("About to start KeyManagement Enclave manager")
    enclave_manager.start_enclave_manager()
Beispiel #14
0
def Main(args=None):
    ParseCommandLine(args)

    config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    logger.info("***************** TRUSTED COMPUTE FRAMEWORK (TCF)" +
                " *****************")

    global direct_jrpc
    direct_jrpc = DirectJsonRpcApiConnector(config_file=None, config=config)

    global address
    if mode == "registry" and address:
        logger.error("\n Worker registry contract address is unsupported \n")
        sys.exit(-1)

    # Connect to registry list and retrieve registry
    global uri
    if not uri and mode == "listing":
        registry_list_instance = direct_jrpc.create_worker_registry_list(
            config)
        # Lookup returns tuple, first element is number of registries and
        # second is element is lookup tag and
        # third is list of organization ids.
        registry_count, lookup_tag, registry_list = \
            registry_list_instance.registry_lookup()
        logger.info("\n Registry lookup response: registry count: {} " +
                    "lookup tag: {} registry list: {}\n".format(
                        registry_count, lookup_tag, registry_list))
        if (registry_count == 0):
            logger.error("No registries found")
            sys.exit(1)
        # Retrieve the fist registry details.
        registry_retrieve_result = registry_list_instance.registry_retrieve(
            registry_list[0])
        logger.info("\n Registry retrieve response: {}\n".format(
            registry_retrieve_result))
        config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

    # Prepare worker
    req_id = 31
    global worker_id
    if not worker_id:
        worker_registry_instance = direct_jrpc.create_worker_registry(config)
        worker_lookup_result = worker_registry_instance.worker_lookup(
            worker_type=WorkerType.TEE_SGX, id=req_id)
        logger.info("\n Worker lookup response: {}\n".format(
            json.dumps(worker_lookup_result, indent=4)))
        if "result" in worker_lookup_result and \
                "ids" in worker_lookup_result["result"].keys():
            if worker_lookup_result["result"]["totalCount"] != 0:
                worker_id = worker_lookup_result["result"]["ids"][0]
            else:
                logger.error("ERROR: No workers found")
                sys.exit(1)
        else:
            logger.error("ERROR: Failed to lookup worker")
            sys.exit(1)

    req_id += 1
    worker_retrieve_result = worker_registry_instance.worker_retrieve(
        worker_id, req_id)
    logger.info("\n Worker retrieve response: {}\n".format(
        json.dumps(worker_retrieve_result, indent=4)))

    if "error" in worker_retrieve_result:
        logger.error("Unable to retrieve worker details\n")
        sys.exit(1)

    # Initializing Worker Object
    worker_obj = worker_details.SGXWorkerDetails()
    worker_obj.load_worker(worker_retrieve_result)

    logger.info(
        "**********Worker details Updated with Worker ID" + "*********\n%s\n",
        worker_id)

    # Convert workloadId to hex
    global workload_id
    workload_id = workload_id.encode("UTF-8").hex()
    work_order_id = secrets.token_hex(32)
    requester_id = secrets.token_hex(32)
    session_iv = utility.generate_iv()
    session_key = utility.generate_key()
    requester_nonce = secrets.token_hex(16)
    # Create work order
    wo_params = WorkOrderParams(
        work_order_id,
        worker_id,
        workload_id,
        requester_id,
        session_key,
        session_iv,
        requester_nonce,
        result_uri=" ",
        notify_uri=" ",
        worker_encryption_key=worker_obj.encryption_key,
        data_encryption_algorithm="AES-GCM-256")
    # Add worker input data
    global in_data

    for value in in_data:
        wo_params.add_in_data(value)

    # Encrypt work order request hash
    wo_params.add_encrypted_request_hash()

    private_key = utility.generate_signing_keys()
    if requester_signature:
        # Add requester signature and requester verifying_key
        if wo_params.add_requester_signature(private_key) is False:
            logger.info("Work order request signing failed")
            exit(1)
    # Submit work order
    logger.info("Work order submit request : %s, \n \n ",
                wo_params.to_string(req_id))
    work_order_instance = direct_jrpc.create_work_order(config)
    req_id += 1
    response = work_order_instance.work_order_submit(wo_params.get_params(),
                                                     wo_params.get_in_data(),
                                                     wo_params.get_out_data(),
                                                     id=req_id)
    logger.info("Work order submit response : {}\n ".format(
        json.dumps(response, indent=4)))

    if "error" in response and response["error"]["code"] != \
            WorkOrderStatus.PENDING:
        sys.exit(1)

    wo_receipt_instance = direct_jrpc.create_work_order_receipt(config)
    # Create receipt
    if show_receipt:
        req_id += 1
        # Create work order receipt object using WorkOrderReceiptRequest class
        wo_request = json.loads(wo_params.to_string(req_id))
        wo_receipt_obj = WorkOrderReceiptRequest()
        wo_create_receipt = wo_receipt_obj.create_receipt(
            wo_request, ReceiptCreateStatus.PENDING.value, private_key)
        logger.info("Work order create receipt request : {} \n \n ".format(
            json.dumps(wo_create_receipt, indent=4)))
        # Submit work order create receipt jrpc request
        wo_receipt_resp = wo_receipt_instance.work_order_receipt_create(
            wo_create_receipt["workOrderId"],
            wo_create_receipt["workerServiceId"],
            wo_create_receipt["workerId"], wo_create_receipt["requesterId"],
            wo_create_receipt["receiptCreateStatus"],
            wo_create_receipt["workOrderRequestHash"],
            wo_create_receipt["requesterGeneratedNonce"],
            wo_create_receipt["requesterSignature"],
            wo_create_receipt["signatureRules"],
            wo_create_receipt["receiptVerificationKey"], req_id)
        logger.info("Work order create receipt response : {} \n \n ".format(
            wo_receipt_resp))

    # Retrieve result
    req_id += 1
    res = work_order_instance.work_order_get_result(work_order_id, req_id)

    logger.info("Work order get result : {}\n ".format(
        json.dumps(res, indent=4)))
    sig_obj = signature.ClientSignature()
    if "result" in res:
        status = sig_obj.verify_signature(res, worker_obj.verification_key)
        try:
            if status == SignatureStatus.PASSED:
                logger.info("Signature verification Successful")
                decrypted_res = utility.decrypted_response(
                    res, session_key, session_iv)
                if show_decrypted_output:
                    logger.info(
                        "\nDecrypted response:\n {}".format(decrypted_res))
            else:
                logger.error("Signature verification Failed")
                sys.exit(1)
        except Exception as err:
            logger.error("ERROR: Failed to decrypt response: %s", str(err))
            sys.exit(1)
    else:
        logger.error("\n Work order get result failed {}\n".format(res))
        sys.exit(1)

    if show_receipt:
        # Retrieve receipt
        req_id += 1
        receipt_res = wo_receipt_instance.work_order_receipt_retrieve(
            work_order_id, id=req_id)
        logger.info("\n Retrieve receipt response:\n {}".format(
            json.dumps(receipt_res, indent=4)))
        # Retrieve last update to receipt by passing 0xFFFFFFFF
        req_id += 1
        receipt_update_retrieve = \
            wo_receipt_instance.work_order_receipt_update_retrieve(
                work_order_id,
                None,
                1 << 32,
                id=req_id)
        logger.info("\n Last update to receipt receipt is:\n {}".format(
            json.dumps(receipt_update_retrieve, indent=4)))
        status = sig_obj.verify_update_receipt_signature(
            receipt_update_retrieve)
        if status == SignatureStatus.PASSED:
            logger.info("Work order receipt retrieve signature verification " +
                        "successful")
        else:
            logger.info(
                "Work order receipt retrieve signature verification failed!!")
            sys.exit(1)
def Main(args=None):
    options = _parse_command_line(args)

    config = _parse_config_file(options.config)
    if config is None:
        logger.error("\n Error in parsing config file: {}\n".format(
            options.config))
        sys.exit(-1)

    # mode should be one of listing or registry (default)
    mode = options.mode

    # Http JSON RPC listener uri
    uri = options.uri
    if uri:
        config["tcf"]["json_rpc_uri"] = uri
    # Setting blockchain type
    # if blockchain parameter is not passed, set to None
    # and None implies direct mode.
    blockchain = options.blockchain
    if blockchain:
        config['blockchain']['type'] = blockchain

    # Address of smart contract
    address = options.address
    if address:
        if mode == "listing":
            config["ethereum"]["direct_registry_contract_address"] = \
                address
        elif mode == "registry":
            logger.error(
                "\n Only Worker registry listing address is supported." +
                "Worker registry address is unsupported \n")
            sys.exit(-1)

    # worker id
    worker_id = options.worker_id
    worker_id_hex = options.worker_id_hex

    worker_id = worker_id_hex if not worker_id \
        else hex_utils.get_worker_id_from_name(worker_id)

    # work load id of worker
    workload_id = options.workload_id
    if not workload_id:
        logger.error("\nWorkload id is mandatory\n")
        sys.exit(-1)

    # work order input data
    in_data = options.in_data

    # show receipt in output
    show_receipt = options.receipt

    # show decrypted result in output
    show_decrypted_output = options.decrypted_output

    # requester signature for work order requests
    requester_signature = options.requester_signature

    # setup logging
    config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    logger.info("******* Hyperledger Avalon Generic client *******")

    if mode == "registry" and address:
        logger.error("\n Worker registry contract address is unsupported \n")
        sys.exit(-1)

    # Retrieve JSON RPC uri from registry list for direct mode.
    if not uri and mode == "listing":
        if not blockchain:
            uri = _retrieve_uri_from_registry_list(config)
            if uri is None:
                logger.error("\n Unable to get http JSON RPC uri \n")
                sys.exit(-1)

    # Prepare worker
    worker_registry = _create_worker_registry_instance(blockchain, config)
    worker_obj, worker_id = _get_first_active_worker(worker_registry,
                                                     worker_id, config)
    if worker_obj is None:
        logger.error("Cannot proceed without a valid worker")
        sys.exit(-1)
    # Create session key and iv to sign work order request
    session_key = crypto_utility.generate_key()
    session_iv = crypto_utility.generate_iv()

    s_key = session_key
    s_iv = session_iv
    logger.info(
        "**********Worker details Updated with Worker ID" + "*********\n%s\n",
        worker_id)

    # Create work order
    verification_key = worker_obj.verification_key
    code, wo_params = _create_work_order_params(worker_id, workload_id,
                                                in_data,
                                                worker_obj.encryption_key,
                                                session_key, session_iv)
    if not code:
        logger.error("Work order submission failed")
        exit(1)

    client_private_key = crypto_utility.generate_signing_keys()
    if requester_signature:
        # Add requester signature and requester verifying_key
        if wo_params.add_requester_signature(client_private_key) is False:
            logger.info("Work order request signing failed")
            exit(1)

    # Submit work order
    jrpc_req_id = random.randint(0, 100000)
    logger.info("Work order submit request : %s, \n \n ",
                wo_params.to_jrpc_string(jrpc_req_id))
    work_order = _create_work_order_instance(blockchain, config)
    jrpc_req_id += 1
    wo_id = wo_params.get_worker_id()
    response = work_order.work_order_submit(wo_params.get_work_order_id(),
                                            wo_params.get_worker_id(),
                                            wo_params.get_requester_id(),
                                            wo_params.to_string(),
                                            id=jrpc_req_id)
    logger.info("Work order submit response : {}\n ".format(response))

    if blockchain is None:
        if "error" in response and response["error"]["code"] != \
                WorkOrderStatus.PENDING:
            sys.exit(1)
    else:
        if response != ContractResponse.SUCCESS:
            sys.exit(1)

    # Create receipt
    wo_receipt = _create_work_order_receipt_instance(blockchain, config)
    if show_receipt and wo_receipt:
        jrpc_req_id += 1
        _create_work_order_receipt(wo_receipt, wo_params, client_private_key,
                                   jrpc_req_id)

    # Retrieve work order result
    res = _get_work_order_result(work_order, wo_params.get_work_order_id(),
                                 jrpc_req_id + 1)
    if res:
        logger.info("Work order get result : {}\n ".format(
            json.dumps(res, indent=4)))

        # Check if result field is present in work order response
        if "result" in res:
            # Verify work order response signature
            if _verify_wo_res_signature(res['result'],
                                        worker_obj.verification_key,
                                        wo_params.get_requester_nonce()) \
                    is False:
                logger.error(
                    "Work order response signature verification Failed")
                sys.exit(1)
            # Decrypt work order response
            if show_decrypted_output:
                decrypted_res = crypto_utility.decrypted_response(
                    res['result'], session_key, session_iv)
                logger.info("\nDecrypted response:\n {}".format(decrypted_res))
        else:
            logger.error("\n Work order get result failed {}\n".format(res))
            sys.exit(1)
    else:
        logger.error("\n Work order get result failed {}\n".format(res))
        sys.exit(1)

    if show_receipt and wo_receipt:
        # Retrieve receipt
        jrpc_req_id += 1
        retrieve_wo_receipt \
            = _retrieve_work_order_receipt(wo_receipt,
                                           wo_params, jrpc_req_id)
        # Verify receipt signature
        if _verify_receipt_signature(retrieve_wo_receipt) is False:
            logger.error("Receipt signature verification Failed")
            sys.exit(1)
Beispiel #16
0
def Main(args=None):
    options = _parse_command_line(args)

    config = _parse_config_file(options.config)
    if config is None:
        logger.error("\n Error in parsing config file: {}\n".format(
            options.config))
        sys.exit(-1)

    # mode should be one of listing or registry (default)
    mode = options.mode

    # Http JSON RPC listener uri
    uri = options.uri
    if uri:
        config["tcf"]["json_rpc_uri"] = uri

    # Address of smart contract
    address = options.address
    if address:
        if mode == "listing":
            config["ethereum"]["direct_registry_contract_address"] = \
                address
        elif mode == "registry":
            logger.error(
                "\n Only Worker registry listing address is supported." +
                "Worker registry address is unsupported \n")
            sys.exit(-1)

    # worker id
    worker_id = options.worker_id
    worker_id_hex = options.worker_id_hex

    worker_id = worker_id_hex if not worker_id \
        else hex_utils.get_worker_id_from_name(worker_id)

    # work load id of worker
    workload_id = options.workload_id
    if not workload_id:
        logger.error("\nWorkload id is mandatory\n")
        sys.exit(-1)

    # work order input data
    in_data = options.in_data

    # Option to send input data in plain text
    in_data_plain_text = options.in_data_plain

    # show receipt in output
    show_receipt = options.receipt

    # show decrypted result in output
    show_decrypted_output = options.decrypted_output

    # requester signature for work order requests
    requester_signature = options.requester_signature

    # setup logging
    config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    logger.info("******* Hyperledger Avalon Generic client *******")

    if mode == "registry" and address:
        logger.error("\n Worker registry contract address is unsupported \n")
        sys.exit(-1)

    # Retrieve JSON RPC uri from registry list
    if not uri and mode == "listing":
        uri = _retrieve_uri_from_registry_list(config)
        if uri is None:
            logger.error("\n Unable to get http JSON RPC uri \n")
            sys.exit(-1)

    # Prepare worker
    # JRPC request id. Choose any integer value
    jrpc_req_id = 31
    worker_registry = JRPCWorkerRegistryImpl(config)
    if not worker_id:
        # Get first worker from worker registry
        worker_id = _lookup_first_worker(worker_registry, jrpc_req_id)
        if worker_id is None:
            logger.error("\n Unable to get worker \n")
            sys.exit(-1)

    # Retrieve worker details
    jrpc_req_id += 1
    worker_retrieve_result = worker_registry.worker_retrieve(
        worker_id, jrpc_req_id)
    logger.info("\n Worker retrieve response: {}\n".format(
        json.dumps(worker_retrieve_result, indent=4)))

    if "error" in worker_retrieve_result:
        logger.error("Unable to retrieve worker details\n")
        sys.exit(1)

    # Create session key and iv to sign work order request
    session_key = crypto_utility.generate_key()
    session_iv = crypto_utility.generate_iv()

    # Initializing Worker Object
    worker_obj = worker_details.SGXWorkerDetails()
    worker_obj.load_worker(worker_retrieve_result['result']['details'])

    # Do worker verification
    _do_worker_verification(worker_obj)

    logger.info(
        "**********Worker details Updated with Worker ID" + "*********\n%s\n",
        worker_id)

    # Create work order
    if in_data_plain_text:
        # As per TC spec, if encryptedDataEncryptionKey is "-" then
        # input data is not encrypted
        encrypted_data_encryption_key = "-"
    else:
        # As per TC spec, if encryptedDataEncryptionKey is not
        # provided then set it to None which means
        # use default session key to encrypt input data
        encrypted_data_encryption_key = None

    wo_params = _create_work_order_params(worker_id, workload_id, in_data,
                                          worker_obj.encryption_key,
                                          session_key, session_iv,
                                          encrypted_data_encryption_key)

    client_private_key = crypto_utility.generate_signing_keys()
    if requester_signature:
        # Add requester signature and requester verifying_key
        if wo_params.add_requester_signature(client_private_key) is False:
            logger.info("Work order request signing failed")
            exit(1)

    # Submit work order
    logger.info("Work order submit request : %s, \n \n ",
                wo_params.to_jrpc_string(jrpc_req_id))
    work_order = JRPCWorkOrderImpl(config)
    jrpc_req_id += 1
    response = work_order.work_order_submit(wo_params.get_work_order_id(),
                                            wo_params.get_worker_id(),
                                            wo_params.get_requester_id(),
                                            wo_params.to_string(),
                                            id=jrpc_req_id)
    logger.info("Work order submit response : {}\n ".format(
        json.dumps(response, indent=4)))

    if "error" in response and response["error"]["code"] != \
            WorkOrderStatus.PENDING:
        sys.exit(1)

    # Create receipt
    wo_receipt = JRPCWorkOrderReceiptImpl(config)
    if show_receipt:
        jrpc_req_id += 1
        _create_work_order_receipt(wo_receipt, wo_params, client_private_key,
                                   jrpc_req_id)

    # Retrieve work order result
    jrpc_req_id += 1
    res = work_order.work_order_get_result(wo_params.get_work_order_id(),
                                           jrpc_req_id)

    logger.info("Work order get result : {}\n ".format(
        json.dumps(res, indent=4)))

    # Check if result field is present in work order response
    if "result" in res:
        # Verify work order response signature
        if _verify_wo_res_signature(res['result'], worker_obj.verification_key,
                                    wo_params.get_requester_nonce()) is False:
            logger.error("Work order response signature verification Failed")
            sys.exit(1)
        # Decrypt work order response
        if show_decrypted_output:
            decrypted_res = crypto_utility.decrypted_response(
                res['result'], session_key, session_iv)
            logger.info("\nDecrypted response:\n {}".format(decrypted_res))
    else:
        logger.error("\n Work order get result failed {}\n".format(res))
        sys.exit(1)

    if show_receipt:
        # Retrieve receipt
        jrpc_req_id += 1
        retrieve_wo_receipt \
            = _retrieve_work_order_receipt(wo_receipt,
                                           wo_params, jrpc_req_id)
        # Verify receipt signature
        if "result" in retrieve_wo_receipt:
            if _verify_receipt_signature(retrieve_wo_receipt) is False:
                logger.error("Receipt signature verification Failed")
                sys.exit(1)
        else:
            logger.info("Work Order receipt retrieve failed")
            sys.exit(1)
Beispiel #17
0
def Main(args=None):
    ParseCommandLine(args)

    config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    logger.info("***************** AVALON *****************")

    # Connect to registry list and retrieve registry
    if not off_chain:
        registry_list_instance = direct_jrpc.get_worker_registry_list_instance(
        )

        # Lookup returns tuple, first element is number of registries and
        # second is element is lookup tag and
        # third is list of organization ids.
        registry_count, lookup_tag, registry_list = \
            registry_list_instance.registry_lookup()
        logger.info("\n Registry lookup response: registry count: {} " +
                    "lookup tag: {} registry list: {}\n".format(
                        registry_count, lookup_tag, registry_list))
        if (registry_count == 0):
            logger.warn("No registries found")
            sys.exit(1)

        # Retrieve the first registry details.
        registry_retrieve_result = registry_list_instance.registry_retrieve(
            registry_list[0])
        logger.info("\n Registry retrieve response: {}\n".format(
            registry_retrieve_result))
        config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

    # Prepare worker
    req_id = 31
    global worker_id
    worker_registry_instance = direct_jrpc.get_worker_registry_instance()
    if not worker_id:
        worker_lookup_result = worker_registry_instance.worker_lookup(
            worker_type=WorkerType.TEE_SGX, id=req_id)
        logger.info("\n Worker lookup response: {}\n".format(
            json.dumps(worker_lookup_result, indent=4)))
        if "result" in worker_lookup_result and \
                "ids" in worker_lookup_result["result"].keys():
            if worker_lookup_result["result"]["totalCount"] != 0:
                worker_id = worker_lookup_result["result"]["ids"][0]
            else:
                logger.error("ERROR: No workers found")
                sys.exit(1)
        else:
            logger.error("ERROR: Failed to lookup worker")
            sys.exit(1)
    req_id += 1
    worker_retrieve_result = worker_registry_instance.worker_retrieve(
        worker_id, req_id)
    logger.info("\n Worker retrieve response: {}\n".format(
        json.dumps(worker_retrieve_result, indent=4)))
    worker_obj.load_worker(worker_retrieve_result)

    logger.info(
        "**********Worker details Updated with Worker ID" + "*********\n%s\n",
        worker_id)

    # Convert workloadId to hex
    workload_id = "echo-result".encode("UTF-8").hex()
    work_order_id = secrets.token_hex(32)
    requester_id = secrets.token_hex(32)
    session_iv = utility.generate_iv()
    session_key = utility.generate_key()
    requester_nonce = secrets.token_hex(16)

    # Create work order
    wo_params = WorkOrderParams(
        work_order_id,
        worker_id,
        workload_id,
        requester_id,
        session_key,
        session_iv,
        requester_nonce,
        result_uri=" ",
        notify_uri=" ",
        worker_encryption_key=worker_obj.encryption_key,
        data_encryption_algorithm="AES-GCM-256")
    # Add worker input data
    if input_data_hash:
        # Compute data hash for data params inData
        data_hash = utility.compute_data_hash(message)
        # Convert data_hash to hex
        data_hash = hex_utils.byte_array_to_hex_str(data_hash)
        wo_params.add_in_data(message, data_hash)
    else:
        wo_params.add_in_data(message)

    # Encrypt work order request hash
    wo_params.add_encrypted_request_hash()

    private_key = utility.generate_signing_keys()
    if requester_signature:
        # Add requester signature and requester verifying_key
        if wo_params.add_requester_signature(private_key) is False:
            logger.info("Work order request signing failed")
            exit(1)

    # Submit work order
    logger.info("Work order submit request : %s, \n \n ",
                wo_params.to_jrpc_string(req_id))
    work_order_instance = direct_jrpc.get_work_order_instance()
    req_id += 1
    response = work_order_instance.work_order_submit(
        wo_params.get_work_order_id(),
        wo_params.get_worker_id(),
        wo_params.get_requester_id(),
        wo_params.to_string(),
        id=req_id)
    logger.info("Work order submit response : {}\n ".format(
        json.dumps(response, indent=4)))

    if "error" in response and response["error"]["code"] != \
            WorkOrderStatus.PENDING:
        sys.exit(1)

    # Create receipt
    wo_receipt_instance = direct_jrpc.get_work_order_receipt_instance()
    req_id += 1
    # Create work order receipt object using WorkOrderReceiptRequest class
    wo_request = json.loads(wo_params.to_jrpc_string(req_id))
    wo_receipt_obj = WorkOrderReceiptRequest()
    wo_create_receipt = wo_receipt_obj.create_receipt(
        wo_request, ReceiptCreateStatus.PENDING.value, private_key)
    logger.info("Work order create receipt request : {} \n \n ".format(
        json.dumps(wo_create_receipt, indent=4)))
    # Submit work order create receipt jrpc request
    wo_receipt_resp = wo_receipt_instance.work_order_receipt_create(
        wo_create_receipt["workOrderId"], wo_create_receipt["workerServiceId"],
        wo_create_receipt["workerId"], wo_create_receipt["requesterId"],
        wo_create_receipt["receiptCreateStatus"],
        wo_create_receipt["workOrderRequestHash"],
        wo_create_receipt["requesterGeneratedNonce"],
        wo_create_receipt["requesterSignature"],
        wo_create_receipt["signatureRules"],
        wo_create_receipt["receiptVerificationKey"], req_id)
    logger.info("Work order create receipt response : {} \n \n ".format(
        wo_receipt_resp))
    # Retrieve result
    req_id += 1
    res = work_order_instance.work_order_get_result(work_order_id, req_id)

    logger.info("Work order get result : {}\n ".format(
        json.dumps(res, indent=4)))
    sig_obj = signature.ClientSignature()
    if "result" in res:
        status = sig_obj.verify_signature(res, worker_obj.verification_key)
        try:
            if status == SignatureStatus.PASSED:
                logger.info(
                    "Work order response signature verification Successful")
                decrypted_res = utility.decrypted_response(
                    res, session_key, session_iv)
                logger.info("\nDecrypted response:\n {}".format(decrypted_res))
                if input_data_hash:
                    decrypted_data = decrypted_res[0]["data"]
                    data_hash_in_resp = (decrypted_res[0]["dataHash"]).upper()
                    # Verify data hash in response
                    if utility.verify_data_hash(decrypted_data,
                                                data_hash_in_resp) is False:
                        sys.exit(1)
            else:
                logger.info("Signature verification Failed")
                sys.exit(1)
        except Exception as err:
            logger.error("ERROR: Failed to decrypt response: %s", str(err))
            sys.exit(1)
    else:
        logger.info("\n Work order get result failed {}\n".format(res))
        sys.exit(1)

    # Retrieve receipt
    receipt_res = wo_receipt_instance.work_order_receipt_retrieve(
        work_order_id, id=req_id)

    logger.info("\n Retrieve receipt response:\n {}".format(
        json.dumps(receipt_res, indent=4)))

    # Retrieve last update to receipt by passing 0xFFFFFFFF
    req_id += 1
    receipt_update_retrieve = \
        wo_receipt_instance.work_order_receipt_update_retrieve(
            work_order_id,
            None,
            1 << 32,
            id=req_id)
    logger.info("\n Last update to receipt receipt is:\n {}".format(
        json.dumps(receipt_update_retrieve, indent=4)))
    status = sig_obj.verify_update_receipt_signature(receipt_update_retrieve)
    if status == SignatureStatus.PASSED:
        logger.info(
            "Work order receipt retrieve signature verification Successful")
    else:
        logger.info(
            "Work order receipt retrieve signature verification failed!!")
        sys.exit(1)
    # Receipt lookup based on requesterId
    req_id += 1
    receipt_lookup_res = wo_receipt_instance.work_order_receipt_lookup(
        requester_id=requester_id, id=req_id)
    logger.info("\n Work order receipt lookup response :\n {}".format(
        json.dumps(receipt_lookup_res, indent=4)))
def Main(args=None):
	ParseCommandLine(args)

	if verbose:
		config["Logging"] = {
			"LogFile" : "__screen__",
			"LogLevel" : "INFO"
		}
	else:
		config["Logging"] = {
			"LogFile" : "__screen__",
			"LogLevel" : "WARN"
		}
	plogger.setup_loggers(config.get("Logging", {}))
	sys.stdout = plogger.stream_to_logger(
		logging.getLogger("STDOUT"), logging.DEBUG)
	sys.stderr = plogger.stream_to_logger(
		logging.getLogger("STDERR"), logging.WARN)

	logger.info("***************** TRUSTED COMPUTE FRAMEWORK (TCF)" + \
		" *****************") 

	# Retrieve Worker Registry
	if not off_chain:
		registry_list_instance = direct_jrpc.create_worker_registry_list(
			config
		)
		registry_count, lookup_tag, registry_list = registry_list_instance.registry_lookup()
		logger.info("\n Registry lookup response : registry count {}\
			lookup tag {} registry list {}\n".format(
			registry_count, lookup_tag, registry_list
		))
		if (registry_count == 0):
			logger.warn("No registries found")
			sys.exit(1)
		registry_retrieve_result = registry_list_instance.registry_retrieve(
			registry_list[0]
		)
		logger.info("\n Registry retrieve response : {}\n".format(
			registry_retrieve_result
		))
		config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

	# Prepare worker

	global worker_id
	if not worker_id:
		worker_registry_instance = direct_jrpc.create_worker_registry(
			config
		)
		req_id = 31
		worker_lookup_result = worker_registry_instance.worker_lookup(
			worker_type=WorkerType.TEE_SGX,
			id=req_id
		)
		logger.info("\n Worker lookup response : {} \n",
			json.dumps(worker_lookup_result, indent=4)
		)
		if "result" in worker_lookup_result and \
			"ids" in worker_lookup_result["result"].keys():
			if worker_lookup_result["result"]["totalCount"] != 0:
				worker_id = worker_lookup_result["result"]["ids"][0]
			else:
				logger.error("ERROR: No workers found")
				sys.exit(1)
		else:
			logger.error("ERROR: Failed to lookup worker")
			sys.exit(1)
	req_id += 1
	worker = worker_registry_instance.worker_retrieve(
		worker_id,
		req_id
	)
	logger.info("\n Worker retrieve response : {}\n".format(
		json.dumps(worker, indent=4)
	))
	worker_obj.load_worker(
		worker
	)
	logger.info("**********Worker details Updated with Worker ID" + \
		"*********\n%s\n", worker_id)

	# Open GUI
	GuiMain()
def Main(args=None):
        ParseCommandLine(args)

        config["Logging"] = {
            "LogFile": "__screen__",
            "LogLevel": "INFO"
        }

        plogger.setup_loggers(config.get("Logging", {}))
        sys.stdout = plogger.stream_to_logger(
            logging.getLogger("STDOUT"), logging.DEBUG)
        sys.stderr = plogger.stream_to_logger(
            logging.getLogger("STDERR"), logging.WARN)

        logger.info("***************** AVALON *****************")

        # Connect to registry list and retrieve registry
        if not off_chain:
                direct_wrapper.init_worker_registry_list(config)
                registry_lookup_result = direct_wrapper.registry_lookup()
                if (registry_lookup_result[0] == 0):
                    logger.warn("No registries found")
                    sys.exit(1)
                registry_retrieve_result = direct_wrapper.registry_retrieve(
                    registry_lookup_result[2][0])
                config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

        # Prepare worker
        direct_wrapper.init_worker_registry(config)

        global worker_id
        if not worker_id:
                worker_lookup_json = jrpc_request.WorkerLookupJson(
                    1, worker_type=1)
                worker_lookup_result = direct_wrapper.worker_lookup(
                    worker_lookup_json)
                if "result" in worker_lookup_result and \
                        "ids" in worker_lookup_result["result"].keys():
                        if worker_lookup_result["result"]["totalCount"] != 0:
                            worker_id = \
                                worker_lookup_result["result"]["ids"][0]
                        else:
                            logger.error("ERROR: No workers found")
                            sys.exit(1)
                else:
                        logger.error("ERROR: Failed to lookup worker")
                        sys.exit(1)

        worker_retrieve_json = jrpc_request.WorkerRetrieveJson(2, worker_id)
        worker_obj.load_worker(
            direct_wrapper.worker_retrieve(worker_retrieve_json))

        logger.info("********** Worker details Updated with Worker ID" +
                    "*********\n%s\n", worker_id)

        # Convert workloadId to hex
        workload_id = "echo-result"
        workload_id = workload_id.encode("UTF-8").hex()
        # Create work order
        wo_submit_json = jrpc_request.WorkOrderSubmitJson(
            3, 6000, "pformat",
            worker_id, workload_id, "0x2345",
            worker_encryption_key=base64.b64decode(
                worker_obj.worker_encryption_key).hex(),
            data_encryption_algorithm="AES-GCM-256")
        wo_id = wo_submit_json.get_work_order_id()

        # Sign work order
        private_key = utility.generate_signing_keys()
        session_key = utility.generate_key()
        session_iv = utility.generate_iv()
        encrypted_session_key = utility.generate_encrypted_key(
            session_key, worker_obj.worker_encryption_key)
        # Generate one time key used for encrypting inData
        data_key = utility.generate_key()
        # Initialation vector of size 12 bytes with all zeros.
        data_iv = bytearray(12)

        encrypted_key = utility.generate_encrypted_key(
            data_key, worker_obj.worker_encryption_key)
        encrypted_data_encryption_key = utility.encrypt_data(
            encrypted_key, session_key)
        encrypted_data_encryption_key_str = ''.join(
            format(i, '02x') for i in encrypted_data_encryption_key)
        data_iv_str = ''.join(format(i, '02x') for i in data_iv)
        wo_submit_json.add_in_data(
            message, None, encrypted_data_encryption_key_str, data_iv_str)
        # Submit work order
        direct_wrapper.init_work_order(config)
        direct_wrapper.work_order_submit(
            wo_submit_json, encrypted_session_key, worker_obj, private_key,
            session_key, session_iv, data_key, data_iv)

        # Retrieve result
        wo_get_result_json = jrpc_request.WorkOrderGetResultJson(4, wo_id)
        direct_wrapper.work_order_get_result(
            wo_get_result_json, session_key, session_iv, data_key, data_iv)
Beispiel #20
0
def Main(args=None):
        ParseCommandLine(args)

        config["Logging"] = {
                "LogFile" : "__screen__",
                "LogLevel" : "INFO"
        }
 
        plogger.setup_loggers(config.get("Logging", {}))
        sys.stdout = plogger.stream_to_logger(
                logging.getLogger("STDOUT"), logging.DEBUG)
        sys.stderr = plogger.stream_to_logger(
                logging.getLogger("STDERR"), logging.WARN)

        logger.info("***************** TRUSTED COMPUTE FRAMEWORK (TCF)" +
                " *****************")

        # Connect to registry list and retrieve registry
        if not off_chain:
                registry_list_instance = direct_jrpc.create_worker_registry_list(
                        config
                )
                # Lookup returns tuple, first element is number of registries and
                # second is element is lookup tag and third is list of organization ids.
                registry_count, lookup_tag, registry_list = registry_list_instance.registry_lookup()
                logger.info("\n Registry lookup response: registry count: {} lookup tag: {} registry list: {}\n".format(
                        registry_count, lookup_tag, registry_list
                ))
                if (registry_count == 0):
                        logger.warn("No registries found")
                        sys.exit(1)
                # Retrieve the fist registry details.
                registry_retrieve_result = registry_list_instance.registry_retrieve(registry_list[0])
                logger.info("\n Registry retrieve response: {}\n".format(
                        registry_retrieve_result
                ))
                config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

        # Prepare worker
        req_id = 31
        global worker_id
        worker_registry_instance = direct_jrpc.create_worker_registry(
                config
        )
        if not worker_id:
                worker_lookup_result = worker_registry_instance.worker_lookup(
                        worker_type=WorkerType.TEE_SGX, id=req_id
                )
                logger.info("\n Worker lookup response: {}\n".format(
                        json.dumps(worker_lookup_result, indent=4)
                ))
                if "result" in worker_lookup_result and \
                        "ids" in worker_lookup_result["result"].keys():
                        if worker_lookup_result["result"]["totalCount"] != 0:
                                worker_id = worker_lookup_result["result"]["ids"][0]
                        else:
                                logger.error("ERROR: No workers found")
                                sys.exit(1)
                else:
                        logger.error("ERROR: Failed to lookup worker")
                        sys.exit(1)
        req_id += 1
        worker_retrieve_result = worker_registry_instance.worker_retrieve(
                worker_id,req_id
        )
        logger.info("\n Worker retrieve response: {}\n".format(
                json.dumps(worker_retrieve_result, indent=4)
        ))
        worker_obj.load_worker(worker_retrieve_result)

        logger.info("**********Worker details Updated with Worker ID" + \
                "*********\n%s\n", worker_id)

        if not worker_obj.proof_data:
            logger.info("Proof data is empty, skipping verification of attestation report")
            exit(0)

        # Construct enclave signup info json
        enclave_info = {
            'verifying_key': worker_obj.verification_key,
            'encryption_key': worker_obj.encryption_key,
            'proof_data': worker_obj.proof_data,
            'enclave_persistent_id': ''
        }

        logger.info("Perform verification of attestation report")
        verify_report_status = attestation_util.verify_attestation_report(enclave_info)
        if verify_report_status == False:
            logger.error("Verification of enclave signup info failed")
        else:
            logger.info("Verification of enclave signup info passed")
Beispiel #21
0
def Main(args=None):
    ParseCommandLine(args)

    config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    logger.info("***************** TRUSTED COMPUTE FRAMEWORK (TCF)" + \
     " *****************")

    # Connect to registry list and retrieve registry
    if not off_chain:
        direct_wrapper.init_worker_registry_list(config)
        registry_lookup_result = direct_wrapper.registry_lookup()
        if (registry_lookup_result[0] == 0):
            logger.warn("No registries found")
            sys.exit(1)
        registry_retrieve_result = direct_wrapper.registry_retrieve(
            registry_lookup_result[2][0])
        config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

    # Prepare worker
    direct_wrapper.init_worker_registry(config)

    global worker_id
    if not worker_id:
        worker_lookup_json = jrpc_request.WorkerLookupJson(1, worker_type=1)
        worker_lookup_result = direct_wrapper.worker_lookup(worker_lookup_json)
        if "result" in worker_lookup_result and \
         "ids" in worker_lookup_result["result"].keys():
            if worker_lookup_result["result"]["totalCount"] != 0:
                worker_id = worker_lookup_result["result"]["ids"][0]
            else:
                logger.error("ERROR: No workers found")
                sys.exit(1)
        else:
            logger.error("ERROR: Failed to lookup worker")
            sys.exit(1)

    worker_retrieve_json = jrpc_request.WorkerRetrieveJson(2, worker_id)
    worker_obj.load_worker(
        direct_wrapper.worker_retrieve(worker_retrieve_json))

    logger.info("**********Worker details Updated with Worker ID" + \
     "*********\n%s\n", worker_id)

    # Convert workloadId to hex
    workload_id = "echo-result".encode("UTF-8").hex()
    work_order_id = secrets.token_hex(32)
    requester_id = secrets.token_hex(32)
    session_iv = utility.generate_iv()
    session_key = utility.generate_key()
    encrypted_session_key = utility.generate_encrypted_key(
        session_key, worker_obj.encryption_key)
    requester_nonce = secrets.token_hex(32)
    # Create work order
    wo_submit_json = jrpc_request.WorkOrderSubmitJson(
        3,
        6000,
        "JSON-RPC",
        work_order_id,
        worker_id,
        workload_id,
        requester_id,
        encrypted_session_key,
        session_iv,
        requester_nonce,
        worker_encryption_key=base64.b64decode(
            worker_obj.encryption_key).hex(),
        data_encryption_algorithm="AES-GCM-256")
    wo_submit_json.add_in_data(message)

    # Sign work order
    private_key = utility.generate_signing_keys()

    # Submit work order
    direct_wrapper.init_work_order(config)
    direct_wrapper.work_order_submit(wo_submit_json, encrypted_session_key,
                                     worker_obj, private_key, session_key,
                                     session_iv)

    # Retrieve result
    wo_get_result_json = jrpc_request.WorkOrderGetResultJson(4, work_order_id)
    direct_wrapper.work_order_get_result(wo_get_result_json, session_key,
                                         session_iv)

    # Retrieve receipt
    wo_receipt_retrieve_json = \
     jrpc_request.WorkOrderReceiptRetrieveJson(5, work_order_id)
    direct_wrapper.init_work_order_receipt(config)
    direct_wrapper.work_order_receipt_retrieve(wo_receipt_retrieve_json)
Beispiel #22
0
def Main(args=None):
    ParseCommandLine(args)

    config["Logging"] = {"LogFile": "__screen__", "LogLevel": "INFO"}

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    logger.info("***************** TRUSTED COMPUTE FRAMEWORK (TCF)" +
                " *****************")

    global direct_jrpc
    direct_jrpc = DirectJsonRpcApiAdaptorFactory(config_file=None,
                                                 config=config)

    global address
    if mode == "registry" and address:
        logger.info("\n Worker registry contract address is unsupported \n")
        sys.exit(-1)

    # Connect to registry list and retrieve registry
    global uri
    if not uri and mode == "listing":
        registry_list_instance = direct_jrpc.create_worker_registry_list_adaptor(
            config)
        # Lookup returns tuple, first element is number of registries and
        # second is element is lookup tag and third is list of organization ids.
        registry_count, lookup_tag, registry_list = registry_list_instance.registry_lookup(
        )
        logger.info(
            "\n Registry lookup response: registry count: {} lookup tag: {} registry list: {}\n"
            .format(registry_count, lookup_tag, registry_list))
        if (registry_count == 0):
            logger.warn("No registries found")
            sys.exit(1)
        # Retrieve the fist registry details.
        registry_retrieve_result = registry_list_instance.registry_retrieve(
            registry_list[0])
        logger.info("\n Registry retrieve response: {}\n".format(
            registry_retrieve_result))
        config["tcf"]["json_rpc_uri"] = registry_retrieve_result[0]

    # Prepare worker
    req_id = 31
    global worker_id
    if not worker_id:
        worker_registry_instance = direct_jrpc.create_worker_registry_adaptor(
            config)
        worker_lookup_result = worker_registry_instance.worker_lookup(
            worker_type=WorkerType.TEE_SGX, id=req_id)
        logger.info("\n Worker lookup response: {}\n".format(
            json.dumps(worker_lookup_result, indent=4)))
        if "result" in worker_lookup_result and \
         "ids" in worker_lookup_result["result"].keys():
            if worker_lookup_result["result"]["totalCount"] != 0:
                worker_id = worker_lookup_result["result"]["ids"][0]
            else:
                logger.error("ERROR: No workers found")
                sys.exit(1)
        else:
            logger.error("ERROR: Failed to lookup worker")
            sys.exit(1)

    req_id += 1
    worker_retrieve_result = worker_registry_instance.worker_retrieve(
        worker_id, req_id)
    logger.info("\n Worker retrieve response: {}\n".format(
        json.dumps(worker_retrieve_result, indent=4)))

    if "error" in worker_retrieve_result:
        logger.error("Unable to retrieve worker details\n")
        sys.exit(1)

# Initializing Worker Object
    worker_obj = worker_details.SGXWorkerDetails()
    worker_obj.load_worker(worker_retrieve_result)

    logger.info("**********Worker details Updated with Worker ID" + \
     "*********\n%s\n", worker_id)

    # Convert workloadId to hex
    global workload_id
    workload_id = workload_id.encode("UTF-8").hex()
    work_order_id = secrets.token_hex(32)
    requester_id = secrets.token_hex(32)
    session_iv = utility.generate_iv()
    session_key = utility.generate_key()
    requester_nonce = secrets.token_hex(16)
    # Create work order
    wo_params = WorkOrderParams(
        work_order_id,
        worker_id,
        workload_id,
        requester_id,
        session_key,
        session_iv,
        requester_nonce,
        result_uri=" ",
        notify_uri=" ",
        worker_encryption_key=worker_obj.encryption_key,
        data_encryption_algorithm="AES-GCM-256")
    # Add worker input data
    global in_data
    wo_params.add_in_data(in_data)

    # Sign work order
    private_key = utility.generate_signing_keys()
    wo_params.add_encrypted_request_hash()
    wo_params.add_requester_signature(private_key)
    # Submit work order
    logger.info("Work order submit request : %s, \n \n ",
                wo_params.to_string())
    work_order_instance = direct_jrpc.create_work_order_adaptor(config)
    req_id += 1
    response = work_order_instance.work_order_submit(wo_params.get_params(),
                                                     wo_params.get_in_data(),
                                                     wo_params.get_out_data(),
                                                     id=req_id)
    logger.info("Work order submit response : {}\n ".format(
        json.dumps(response, indent=4)))

    if "error" in response and response["error"][
            "code"] != WorkOrderStatus.PENDING:
        sys.exit(1)
    # Retrieve result
    req_id += 1
    res = work_order_instance.work_order_get_result(work_order_id, req_id)

    logger.info("Work order get result : {}\n ".format(
        json.dumps(res, indent=4)))
    if "result" in res:
        decrypted_res = utility.decrypted_response(json.dumps(res),
                                                   session_key, session_iv)
        logger.info("\nDecrypted response:\n {}".format(decrypted_res))
    else:
        sys.exit(1)

    # Retrieve receipt
    wo_receipt_instance = direct_jrpc.create_work_order_receipt_adaptor(config)
    req_id += 1
    receipt_res = wo_receipt_instance.work_order_receipt_retrieve(
        work_order_id, id=req_id)
    logger.info("\Retrieve receipt response:\n {}".format(
        json.dumps(receipt_res, indent=4)))