Ejemplo n.º 1
0
def doRegisterAgent(registrar_ip,
                    registrar_port,
                    agent_id,
                    tpm_version,
                    pub_ek,
                    ekcert,
                    pub_aik,
                    pub_ek_tpm=None,
                    aik_name=None):
    data = {
        'ek': pub_ek,
        'ekcert': ekcert,
        'aik': pub_aik,
        'aik_name': aik_name,
        'ek_tpm': pub_ek_tpm,
        'tpm_version': tpm_version,
    }
    response = None
    try:
        client = RequestsClient(f'{registrar_ip}:{registrar_port}',
                                tls_enabled)
        response = client.post(f'/agents/{agent_id}',
                               cert=tls_cert_info,
                               data=json.dumps(data),
                               verify=False)
        response_body = response.json()

        if response.status_code != 200:
            logger.error(
                f"Error: unexpected http response code from Registrar Server: {response.status_code}"
            )
            keylime_logging.log_http_response(logger, logging.ERROR,
                                              response_body)
            return None

        logger.info(f"Agent registration requested for {agent_id}")

        if "results" not in response_body:
            logger.critical(
                f"Error: unexpected http response body from Registrar Server: {response.status_code}"
            )
            return None

        if "blob" not in response_body["results"]:
            logger.critical(
                f"Error: did not receive blob from Registrar Server: {response.status_code}"
            )
            return None

        return response_body["results"]["blob"]
    except Exception as e:
        if response and response.status_code == 503:
            logger.error(
                f"Agent cannot establish connection to registrar at {registrar_ip}:{registrar_port}"
            )
            sys.exit()
        else:
            logger.exception(e)

    return None
Ejemplo n.º 2
0
    def do_cvstop(self):
        """ Stop declared active agent
        """
        params = f'/agents/{self.agent_uuid}/stop'
        do_cvstop = RequestsClient(self.verifier_base_url, self.tls_enabled)
        response = do_cvstop.put(
            params,
            cert=self.cert,
            data=b'',
            verify=False
        )

        if response.status_code == 503:
            logger.error("Cannot connect to Verifier at %s with Port %s. Connection refused.", self.verifier_ip, self.verifier_port)
            sys.exit()
        elif response.status_code == 504:
            logger.error("Verifier at %s with Port %s timed out.", self.verifier_ip, self.verifier_port)
            sys.exit()

        response_body = response.json()
        if response.status_code != 200:
            keylime_logging.log_http_response(
                logger, logging.ERROR, response_body)
        else:
            logger.info("Agent %s stopped", self.agent_uuid)
Ejemplo n.º 3
0
    def do_cvreactivate(self):
        """ Reactive Agent
        """
        do_cvreactivate = RequestsClient(
            self.verifier_base_url, self.tls_enabled)
        response = do_cvreactivate.put(
            (f'/agents/{self.agent_uuid}/reactivate'),
            data=b'',
            cert=self.cert,
            verify=False
        )

        if response.status_code == 503:
            logger.error("Cannot connect to Verifier at %s with Port %s. Connection refused.", self.verifier_ip, self.verifier_port)
            sys.exit()
        elif response.status_code == 504:
            logger.error("Verifier at %s with Port %s timed out.", self.verifier_ip, self.verifier_port)
            sys.exit()

        response_body = response.json()

        if response.status_code != 200:
            keylime_logging.log_http_response(
                logger, logging.ERROR, response_body)
            logger.error("Update command response: %s Unexpected response from Cloud Verifier.", response.status_code)
        else:
            logger.info("Agent %s re-activated", self.agent_uuid)
Ejemplo n.º 4
0
    async def get_agent_state(self, agent_id):
        try:
            get_agent_state = RequestsClient(verifier_base_url, tls_enabled)
            response = get_agent_state.get(
                (f'/agents/{agent_id}'),
                cert=cert,
                verify=False
            )

        except Exception as e:
            logger.error("Status command response: %s:%s Unexpected response from Cloud Verifier.",
                tenant_templ.cloudverifier_ip, tenant_templ.cloudverifier_port)
            logger.exception(e)
            config.echo_json_response(
                self, 500, "Unexpected response from Cloud Verifier", str(e))
            logger.error("Unexpected response from Cloud Verifier: %s", e)
            return

        inst_response_body = response.json()

        if response.status_code != 200 and response.status_code != 404:
            logger.error("Status command response: %d Unexpected response from Cloud Verifier.", response.status_code)
            keylime_logging.log_http_response(
                logger, logging.ERROR, inst_response_body)
            return None

        if "results" not in inst_response_body:
            logger.critical("Error: unexpected http response body from Cloud Verifier: %s", response.status_code)
            return None

        # Agent not added to CV (but still registered)
        if response.status_code == 404:
            return {"operational_state": states.REGISTERED}

        return inst_response_body["results"]
Ejemplo n.º 5
0
    def test_012_reg_agent_vactivate_put(self):
        """Test registrar's PUT /v2/agents/{UUID}/vactivate Interface"""
        global keyblob, aik, ek

        self.assertIsNotNone(keyblob, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(aik, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(ek, "Required value not set.  Previous step may have failed?")

        key = tpm.activate_identity(keyblob)
        deepquote = tpm.create_deep_quote(hashlib.sha1(key).hexdigest(),
                                          tenant_templ.agent_uuid + aik + ek)
        data = {
            'deepquote': deepquote,
        }

        test_012_reg_agent_vactivate_put = RequestsClient(tenant_templ.registrar_base_url, tls_enabled=False)
        response = test_012_reg_agent_vactivate_put.put(
            f'/v{self.api_version}/agents/{tenant_templ.agent_uuid}/vactivate',
            data=json.dumps(data),
            cert="",
            verify=False
        )

        self.assertEqual(response.status_code, 200, "Non-successful Registrar agent vActivate return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 6
0
    def test_024_agent_keys_ukey_post(self):
        """Test agents's POST /v2/keys/ukey Interface"""
        global public_key

        self.assertIsNotNone(public_key, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(self.U, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(self.auth_tag, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(self.payload, "Required value not set.  Previous step may have failed?")

        encrypted_U = crypto.rsa_encrypt(crypto.rsa_import_pubkey(public_key), self.U)
        b64_encrypted_u = base64.b64encode(encrypted_U)
        data = {
            'encrypted_key': b64_encrypted_u,
            'auth_tag': self.auth_tag,
            'payload': self.payload
        }

        test_024_agent_keys_ukey_post = RequestsClient(tenant_templ.agent_base_url, tls_enabled=False)
        response = test_024_agent_keys_ukey_post.post(
            f'/v{self.api_version}/keys/ukey',
            data=json.dumps(data),
            cert="",
            verify=False
        )

        self.assertEqual(response.status_code, 200, "Non-successful Agent ukey post return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 7
0
    def test_034_cv_agent_post_invalid_exclude_list(self):
        """Test CV's POST /v2/agents/{UUID} Interface"""
        self.assertIsNotNone(self.V, "Required value not set.  Previous step may have failed?")

        b64_v = base64.b64encode(self.V)
        # Set unsupported regex in exclude list
        allowlist = {'exclude': ['*']}
        data = {
            'v': b64_v,
            'cloudagent_ip': tenant_templ.cloudagent_ip,
            'cloudagent_port': tenant_templ.cloudagent_port,
            'tpm_policy': json.dumps(self.tpm_policy),
            'vtpm_policy': json.dumps(self.vtpm_policy),
            'allowlist': json.dumps(allowlist),
            'ima_sign_verification_keys': '',
            'metadata': json.dumps(self.metadata),
            'revocation_key': self.revocation_key,
            'accept_tpm_hash_algs': config.get('tenant', 'accept_tpm_hash_algs').split(','),
            'accept_tpm_encryption_algs': config.get('tenant', 'accept_tpm_encryption_algs').split(','),
            'accept_tpm_signing_algs': config.get('tenant', 'accept_tpm_signing_algs').split(','),
        }

        client = RequestsClient(tenant_templ.verifier_base_url, tls_enabled)
        response = client.post(
            f'/v{self.api_version}/agents/{tenant_templ.agent_uuid}',
            cert=tenant_templ.cert,
            data=json.dumps(data),
            verify=False
        )

        self.assertEqual(response.status_code, 400, "Successful CV agent Post return code!")

        # Ensure response is well-formed
        json_response = response.json()
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 8
0
    def test_014_reg_agent_get(self):
        """Test registrar's GET /agents/{UUID} Interface"""
        test_014_reg_agent_get = RequestsClient(
            tenant_templ.registrar_base_tls_url, tls_enabled=True)
        response = test_014_reg_agent_get.get(
            f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}",
            cert=tenant_templ.cert,
            verify=False)

        self.assertEqual(response.status_code, 200,
                         "Non-successful Registrar agent return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("ek_tpm", json_response["results"],
                      "Malformed response body!")
        self.assertIn("aik_tpm", json_response["results"],
                      "Malformed response body!")
        self.assertIn("ekcert", json_response["results"],
                      "Malformed response body!")
        self.assertIn("mtls_cert", json_response["results"],
                      "Malformed response body!")
        self.assertIn("ip", json_response["results"],
                      "Malformed response body!")
        self.assertIn("port", json_response["results"],
                      "Malformed response body!")

        global aik_tpm
        global mtls_cert
        mtls_cert = json_response["results"]["mtls_cert"]
        aik_tpm = json_response["results"]["aik_tpm"]
Ejemplo n.º 9
0
    def test_011_reg_agent_activate_put(self):
        """Test registrar's PUT /agents/{UUID}/activate Interface"""

        self.assertIsNotNone(
            keyblob, "Required value not set.  Previous step may have failed?")

        key = tpm_instance.activate_identity(keyblob)
        data = {
            "auth_tag": crypto.do_hmac(key, tenant_templ.agent_uuid),
        }
        test_011_reg_agent_activate_put = RequestsClient(
            tenant_templ.registrar_base_url, tls_enabled=False)
        response = test_011_reg_agent_activate_put.put(
            f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}/activate",
            data=json.dumps(data),
            cert="",
            verify=False,
        )

        self.assertEqual(
            response.status_code, 200,
            "Non-successful Registrar agent Activate return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 10
0
    def test_020_agent_keys_pubkey_get(self):
        """Test agent's GET /keys/pubkey Interface"""

        # We want a real cloud agent to communicate with!
        launch_cloudagent()
        test_020_agent_keys_pubkey_get = RequestsClient(
            tenant_templ.agent_base_url,
            tls_enabled=True,
            ignore_hostname=True)
        response = test_020_agent_keys_pubkey_get.get(
            f"/v{self.api_version}/keys/pubkey",
            cert=tenant_templ.agent_cert,
            verify=False,  # TODO: use agent certificate
        )

        self.assertEqual(response.status_code, 200,
                         "Non-successful Agent pubkey return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("pubkey", json_response["results"],
                      "Malformed response body!")

        global public_key
        public_key = json_response["results"]["pubkey"]
        self.assertNotEqual(public_key, None, "Malformed response body!")
Ejemplo n.º 11
0
    def test_023_agent_keys_vkey_post(self):
        """Test agent's POST /keys/vkey Interface"""
        # CV should do this (during CV POST/PUT test)
        # Running this test might hide problems with the CV sending the V key

        self.assertIsNotNone(
            self.V, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(
            public_key,
            "Required value not set.  Previous step may have failed?")

        encrypted_V = crypto.rsa_encrypt(crypto.rsa_import_pubkey(public_key),
                                         str(self.V))
        b64_encrypted_V = base64.b64encode(encrypted_V)
        data = {"encrypted_key": b64_encrypted_V}

        test_023_agent_keys_vkey_post = RequestsClient(
            tenant_templ.agent_base_url, tls_enabled=False)
        response = test_023_agent_keys_vkey_post.post(
            f"/v{self.api_version}/keys/vkey",
            data=json.dumps(data),
            cert="",
            verify=False)

        self.assertEqual(response.status_code, 200,
                         "Non-successful Agent vkey post return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 12
0
    def test_027_cv_allowlist_delete(self):
        """Test CV's DELETE /allowlists/{name} Interface"""
        cv_client = RequestsClient(tenant_templ.verifier_base_url, tls_enabled)
        response = cv_client.delete(
            f"/v{self.api_version}/allowlists/test-allowlist", cert=tenant_templ.cert, verify=False
        )

        self.assertEqual(response.status_code, 204, "Non-successful CV allowlist Delete return code!")
Ejemplo n.º 13
0
    def test_010_reg_agent_post(self):
        """Test registrar's POST /v2/agents/{UUID} Interface"""
        global keyblob, aik, vtpm, ek

        # Change CWD for TPM-related operations
        cwd = os.getcwd()
        config.ch_dir(config.WORK_DIR, None)
        _ = secure_mount.mount()

        # Initialize the TPM with AIK
        (ek, ekcert, aik, ek_tpm,
         aik_name) = tpm.tpm_init(self_activate=False,
                                  config_pw=config.get('cloud_agent',
                                                       'tpm_ownerpassword'))
        vtpm = tpm.is_vtpm()

        # Seed RNG (root only)
        if config.REQUIRE_ROOT:
            tpm.init_system_rand()

        # Handle virtualized and emulated TPMs
        if ekcert is None:
            if vtpm:
                ekcert = 'virtual'
            elif tpm.is_emulator():
                ekcert = 'emulator'

        # Get back to our original CWD
        config.ch_dir(cwd, None)

        data = {
            'ek': ek,
            'ekcert': ekcert,
            'aik': aik,
            'aik_name': aik_name,
            'ek_tpm': ek_tpm,
            'tpm_version': tpm.VERSION,
        }

        test_010_reg_agent_post = RequestsClient(
            tenant_templ.registrar_base_url, tls_enabled=False)
        response = test_010_reg_agent_post.post(
            f'/v{self.api_version}/agents/{tenant_templ.agent_uuid}',
            data=json.dumps(data),
            cert="",
            verify=False)

        self.assertEqual(response.status_code, 200,
                         "Non-successful Registrar agent Add return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("blob", json_response["results"],
                      "Malformed response body!")

        keyblob = json_response["results"]["blob"]
        self.assertIsNotNone(keyblob, "Malformed response body!")
Ejemplo n.º 14
0
    def do_verify(self):
        """ Perform verify using a random generated challenge
        """
        challenge = TPM_Utilities.random_password(20)
        numtries = 0
        while True:
            try:
                cloudagent_base_url = (f'{self.agent_ip}:{self.agent_port}')
                do_verify = RequestsClient(cloudagent_base_url,
                                           tls_enabled=False)
                response = do_verify.get(
                    (f'/keys/verify?challenge={challenge}'),
                    cert=self.cert,
                    verify=False)
            except Exception as e:
                if response.status_code in (503, 504):
                    numtries += 1
                    maxr = config.getint('tenant', 'max_retries')
                    if numtries >= maxr:
                        logger.error(
                            f"Cannot establish connection to agent on {self.agent_ip} with port {self.agent_port}"
                        )
                        sys.exit()
                    retry = config.getfloat('tenant', 'retry_interval')
                    logger.info(
                        f"Verifier connection to agent at {self.agent_ip} refused {numtries}/{maxr} times, trying again in {retry} seconds..."
                    )
                    time.sleep(retry)
                    continue

                raise e
            response_body = response.json()
            if response.status_code == 200:
                if "results" not in response_body or 'hmac' not in response_body[
                        'results']:
                    logger.critical(
                        f"Error: unexpected http response body from Cloud Agent: {response.status_code}"
                    )
                    break
                mac = response_body['results']['hmac']

                ex_mac = crypto.do_hmac(self.K, challenge)

                if mac == ex_mac:
                    logger.info("Key derivation successful")
                else:
                    logger.error("Key derivation failed")
            else:
                keylime_logging.log_http_response(logger, logging.ERROR,
                                                  response_body)
                retry = config.getfloat('tenant', 'retry_interval')
                logger.warning(
                    f"Key derivation not yet complete...trying again in {retry} seconds...Ctrl-C to stop"
                )
                time.sleep(retry)
                continue
            break
Ejemplo n.º 15
0
    def test_030_cv_agent_post(self):
        """Test CV's POST /agents/{UUID} Interface"""
        self.assertIsNotNone(
            self.V, "Required value not set.  Previous step may have failed?")

        b64_v = base64.b64encode(self.V)
        data = {
            "v":
            b64_v,
            "cloudagent_ip":
            tenant_templ.cloudagent_ip,
            "cloudagent_port":
            tenant_templ.cloudagent_port,
            "tpm_policy":
            json.dumps(self.tpm_policy),
            "ima_policy_bundle":
            json.dumps(self.ima_policy_bundle),
            "ima_sign_verification_keys":
            "",
            "mb_refstate":
            None,
            "metadata":
            json.dumps(self.metadata),
            "revocation_key":
            self.revocation_key,
            "accept_tpm_hash_algs":
            config.get("tenant", "accept_tpm_hash_algs").split(","),
            "accept_tpm_encryption_algs":
            config.get("tenant", "accept_tpm_encryption_algs").split(","),
            "accept_tpm_signing_algs":
            config.get("tenant", "accept_tpm_signing_algs").split(","),
            "supported_version":
            tenant_templ.supported_version,
            "ak_tpm":
            aik_tpm,
            "mtls_cert":
            mtls_cert,
        }

        test_030_cv_agent_post = RequestsClient(tenant_templ.verifier_base_url,
                                                tls_enabled)
        response = test_030_cv_agent_post.post(
            f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}",
            data=json.dumps(data),
            cert=tenant_templ.cert,
            verify=False,
        )

        self.assertEqual(response.status_code, 200,
                         "Non-successful CV agent Post return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")

        time.sleep(10)
Ejemplo n.º 16
0
    def test_010_reg_agent_post(self):
        """Test registrar's POST /agents/{UUID} Interface"""
        global keyblob, vtpm, tpm_instance, ek_tpm, aik_tpm
        contact_ip = "127.0.0.1"
        contact_port = 9002
        tpm_instance = tpm_main.tpm()

        # Change CWD for TPM-related operations
        cwd = os.getcwd()
        config.ch_dir(config.WORK_DIR, None)
        _ = secure_mount.mount()

        # Initialize the TPM with AIK
        (ekcert, ek_tpm, aik_tpm) = tpm_instance.tpm_init(
            self_activate=False,
            config_pw=config.get('cloud_agent', 'tpm_ownerpassword'))
        vtpm = tpm_instance.is_vtpm()

        # Handle virtualized and emulated TPMs
        if ekcert is None:
            if vtpm:
                ekcert = 'virtual'
            elif tpm_instance.is_emulator():
                ekcert = 'emulator'

        # Get back to our original CWD
        config.ch_dir(cwd, None)

        data = {
            'ekcert': ekcert,
            'aik_tpm': aik_tpm,
            'ip': contact_ip,
            'port': contact_port
        }
        if ekcert is None or ekcert == 'emulator':
            data['ek_tpm'] = ek_tpm

        test_010_reg_agent_post = RequestsClient(
            tenant_templ.registrar_base_url, tls_enabled=False)
        response = test_010_reg_agent_post.post(
            f'/v{self.api_version}/agents/{tenant_templ.agent_uuid}',
            data=json.dumps(data),
            cert="",
            verify=False)

        self.assertEqual(response.status_code, 200,
                         "Non-successful Registrar agent Add return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("blob", json_response["results"],
                      "Malformed response body!")

        keyblob = json_response["results"]["blob"]
        self.assertIsNotNone(keyblob, "Malformed response body!")
Ejemplo n.º 17
0
def doRegistrarDelete(registrar_ip, registrar_port, agent_id):
    client = RequestsClient(f'{registrar_ip}:{registrar_port}', tls_enabled)
    response = client.delete(f'/v{api_version}/agents/{agent_id}', cert=tls_cert_info, verify=False)
    response_body = response.json()

    if response.status_code == 200:
        logger.debug("Registrar deleted.")
    else:
        logger.warning("Status command response: %s Unexpected response from registrar.", response.status_code)
        keylime_logging.log_http_response(logger, logging.WARNING, response_body)
Ejemplo n.º 18
0
def getData(registrar_ip, registrar_port, agent_id):
    # make absolutely sure you don't ask for data that contains AIK keys unauthenticated
    if not tls_enabled:
        raise Exception(
            "It is unsafe to use this interface to query AIKs without server-authenticated TLS.")

    response = None
    try:
        client = RequestsClient(f'{registrar_ip}:{registrar_port}', tls_enabled)
        response = client.get(f'/v{api_version}/agents/{agent_id}', cert=tls_cert_info, verify=False)
        response_body = response.json()

        if response.status_code != 200:
            logger.critical("Error: unexpected http response code from Registrar Server: %s", response.status_code)
            keylime_logging.log_http_response(logger, logging.CRITICAL, response_body)
            return None

        # Check for all values that are consumed by other parts of Keylime
        if "results" not in response_body:
            logger.critical("Error: unexpected http response body from Registrar Server: %s", response.status_code)
            return None

        if "aik_tpm" not in response_body["results"]:
            logger.critical("Error: did not receive AIK from Registrar Server.")
            return None

        if "regcount" not in response_body["results"]:
            logger.critical("Error: did not receive regcount from Registrar Server.")
            return None

        if "ek_tpm" not in response_body["results"]:
            logger.critical("Error: did not receive EK from Registrar Server.")
            return None

        if "ip" not in response_body["results"]:
            logger.critical("Error: did not receive IP from Registrar Server.")
            return None

        if "port" not in response_body["results"]:
            logger.critical("Error: did not receive port from Registrar Server.")
            return None

        return response_body["results"]

    except AttributeError as e:
        if response and response.status_code == 503:
            logger.critical("Error: the registrar is not available at %s:%s", registrar_ip, registrar_port)
        else:
            logger.exception(e)

    except Exception as e:
        logger.exception(e)

    return None
Ejemplo n.º 19
0
def doRegistrarList(registrar_ip, registrar_port):
    client = RequestsClient(f'{registrar_ip}:{registrar_port}', tls_enabled)
    response = client.get(f'/v{api_version}/agents/', cert=tls_cert_info, verify=False)
    response_body = response.json()

    if response.status_code != 200:
        logger.warning("Registrar returned: %s Unexpected response from registrar.", response.status_code)
        keylime_logging.log_http_response(logger, logging.WARNING, response_body)
        return None

    return response_body
Ejemplo n.º 20
0
    def test_031_cv_agent_put(self):
        """Test CV's PUT /agents/{UUID} Interface"""
        # TODO: this should actually test PUT functionality (e.g., make agent fail and then PUT back up)
        test_031_cv_agent_put = RequestsClient(tenant_templ.verifier_base_url, tls_enabled)
        response = test_031_cv_agent_put.put(
            f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}", data=b"", cert=tenant_templ.cert, verify=False
        )
        self.assertEqual(response.status_code, 200, "Non-successful CV agent Post return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 21
0
    def test_040_agent_quotes_integrity_get(self):
        """Test agent's GET /quotes/integrity Interface"""
        global public_key

        self.assertIsNotNone(
            aik_tpm, "Required value not set.  Previous step may have failed?")

        nonce = tpm_abstract.TPM_Utilities.random_password(20)
        mask = self.tpm_policy["mask"]
        partial = "1"
        if public_key is None:
            partial = "0"

        test_040_agent_quotes_integrity_get = RequestsClient(
            tenant_templ.agent_base_url,
            tls_enabled=True,
            ignore_hostname=True)
        response = test_040_agent_quotes_integrity_get.get(
            f"/v{self.api_version}/quotes/integrity?nonce={nonce}&mask={mask}&partial={partial}",
            cert=tenant_templ.agent_cert,
            verify=False,  # TODO: use agent certificate
        )

        self.assertEqual(response.status_code, 200,
                         "Non-successful Agent Integrity Get return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("quote", json_response["results"],
                      "Malformed response body!")
        if public_key is None:
            self.assertIn("pubkey", json_response["results"],
                          "Malformed response body!")
            public_key = json_response["results"]["pubkey"]
        self.assertIn("hash_alg", json_response["results"],
                      "Malformed response body!")

        quote = json_response["results"]["quote"]
        hash_alg = algorithms.Hash(json_response["results"]["hash_alg"])

        agentAttestState = cloud_verifier_common.get_AgentAttestStates(
        ).get_by_agent_id(tenant_templ.agent_uuid)

        failure = tpm_instance.check_quote(agentAttestState,
                                           nonce,
                                           public_key,
                                           quote,
                                           aik_tpm,
                                           self.tpm_policy,
                                           hash_alg=hash_alg)
        self.assertTrue(not failure)
Ejemplo n.º 22
0
    def test_015_reg_agent_delete(self):

        """Test registrar's DELETE /agents/{UUID} Interface"""
        test_015_reg_agent_delete = RequestsClient(tenant_templ.registrar_base_tls_url, tls_enabled=True)
        response = test_015_reg_agent_delete.delete(
            f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}", cert=tenant_templ.cert, verify=False
        )

        self.assertEqual(response.status_code, 200, "Non-successful Registrar Delete return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 23
0
    def test_050_cv_agent_delete(self):
        """Test CV's DELETE /agents/{UUID} Interface"""
        time.sleep(5)
        test_050_cv_agent_delete = RequestsClient(tenant_templ.verifier_base_url, tls_enabled)
        response = test_050_cv_agent_delete.delete(
            f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}", cert=tenant_templ.cert, verify=False
        )

        self.assertEqual(response.status_code, 202, "Non-successful CV agent Delete return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
Ejemplo n.º 24
0
    def test_060_cv_version_get(self):
        """Test CV's GET /version Interface"""
        cv_client = RequestsClient(tenant_templ.verifier_base_url, tls_enabled)
        response = cv_client.get("/version", cert=tenant_templ.cert, verify=False)

        self.assertEqual(response.status_code, 200, "Non-successful CV allowlist Post return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        results = json_response["results"]
        self.assertEqual(results["current_version"], api_version.current_version())
        self.assertEqual(results["supported_versions"], api_version.all_versions())
Ejemplo n.º 25
0
def doRegisterAgent(registrar_ip, registrar_port, agent_id, ek_tpm, ekcert,
                    aik_tpm):
    data = {
        'ekcert': ekcert,
        'aik_tpm': aik_tpm,
    }
    if ekcert is None or ekcert == 'emulator':
        data['ek_tpm'] = ek_tpm
    response = None
    try:
        client = RequestsClient(f'{registrar_ip}:{registrar_port}',
                                tls_enabled)
        response = client.post(f'/agents/{agent_id}',
                               cert=tls_cert_info,
                               data=json.dumps(data),
                               verify=False)
        response_body = response.json()

        if response.status_code != 200:
            logger.error(
                "Error: unexpected http response code from Registrar Server: %s",
                response.status_code)
            keylime_logging.log_http_response(logger, logging.ERROR,
                                              response_body)
            return None

        logger.info("Agent registration requested for %s", agent_id)

        if "results" not in response_body:
            logger.critical(
                "Error: unexpected http response body from Registrar Server: %s",
                response.status_code)
            return None

        if "blob" not in response_body["results"]:
            logger.critical(
                "Error: did not receive blob from Registrar Server: %s",
                response.status_code)
            return None

        return response_body["results"]["blob"]
    except Exception as e:
        if response and response.status_code == 503:
            logger.error(
                "Agent cannot establish connection to registrar at %s:%s",
                registrar_ip, registrar_port)
            sys.exit()
        else:
            logger.exception(e)

    return None
Ejemplo n.º 26
0
    def test_030_cv_agent_post(self):
        """Test CV's POST /v2/agents/{UUID} Interface"""
        self.assertIsNotNone(
            self.V, "Required value not set.  Previous step may have failed?")

        b64_v = base64.b64encode(self.V)
        data = {
            'v':
            b64_v,
            'cloudagent_ip':
            tenant_templ.cloudagent_ip,
            'cloudagent_port':
            tenant_templ.cloudagent_port,
            'tpm_policy':
            json.dumps(self.tpm_policy),
            'vtpm_policy':
            json.dumps(self.vtpm_policy),
            'allowlist':
            json.dumps(self.allowlist),
            'ima_sign_verification_keys':
            '',
            'mb_refstate':
            None,
            'metadata':
            json.dumps(self.metadata),
            'revocation_key':
            self.revocation_key,
            'accept_tpm_hash_algs':
            config.get('tenant', 'accept_tpm_hash_algs').split(','),
            'accept_tpm_encryption_algs':
            config.get('tenant', 'accept_tpm_encryption_algs').split(','),
            'accept_tpm_signing_algs':
            config.get('tenant', 'accept_tpm_signing_algs').split(','),
        }

        test_030_cv_agent_post = RequestsClient(tenant_templ.verifier_base_url,
                                                tls_enabled)
        response = test_030_cv_agent_post.post(
            f'/agents/{tenant_templ.agent_uuid}',
            data=json.dumps(data),
            cert=tenant_templ.cert,
            verify=False)

        self.assertEqual(response.status_code, 200,
                         "Non-successful CV agent Post return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")

        time.sleep(10)
Ejemplo n.º 27
0
    def test_010_reg_agent_post(self):
        """Test registrar's POST /agents/{UUID} Interface"""
        global keyblob, tpm_instance, ek_tpm, aik_tpm
        contact_ip = "127.0.0.1"
        contact_port = 9002
        tpm_instance = tpm_main.tpm()

        # Change CWD for TPM-related operations
        cwd = os.getcwd()
        fs_util.ch_dir(config.WORK_DIR)
        _ = secure_mount.mount()

        # Create a mTLS cert for testing
        global mtls_cert
        rsa_key = crypto.rsa_generate(2048)
        valid_util = datetime.datetime.utcnow() + datetime.timedelta(days=(360 * 5))
        mtls_cert = crypto.generate_selfsigned_cert("TEST_CERT", rsa_key, valid_util).public_bytes(
            serialization.Encoding.PEM
        )

        # Initialize the TPM with AIK
        (ekcert, ek_tpm, aik_tpm) = tpm_instance.tpm_init(
            self_activate=False, config_pw=config.get("cloud_agent", "tpm_ownerpassword")
        )

        # Handle emulated TPMs
        if ekcert is None:
            if tpm_instance.is_emulator():
                ekcert = "emulator"

        # Get back to our original CWD
        fs_util.ch_dir(cwd)

        data = {"ekcert": ekcert, "aik_tpm": aik_tpm, "ip": contact_ip, "port": contact_port, "mtls_cert": mtls_cert}
        if ekcert is None or ekcert == "emulator":
            data["ek_tpm"] = ek_tpm

        test_010_reg_agent_post = RequestsClient(tenant_templ.registrar_base_url, tls_enabled=False)
        response = test_010_reg_agent_post.post(
            f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}", data=json.dumps(data), cert="", verify=False
        )

        self.assertEqual(response.status_code, 200, "Non-successful Registrar agent Add return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("blob", json_response["results"], "Malformed response body!")

        keyblob = json_response["results"]["blob"]
        self.assertIsNotNone(keyblob, "Malformed response body!")
Ejemplo n.º 28
0
def getKeys(registrar_ip, registrar_port, agent_id):

    # make absolutely sure you don't ask for AIKs unauthenticated
    if not tls_enabled:
        raise Exception(
            "It is unsafe to use this interface to query AIKs without server-authenticated TLS."
        )

    response = None
    try:
        client = RequestsClient(f'{registrar_ip}:{registrar_port}',
                                tls_enabled)
        response = client.get(f'/agents/{agent_id}',
                              cert=tls_cert_info,
                              verify=False)
        response_body = response.json()

        if response.status_code != 200:
            logger.critical(
                "Error: unexpected http response code from Registrar Server: %s"
                % str(response.status_code))
            keylime_logging.log_http_response(logger, logging.CRITICAL,
                                              response_body)
            return None

        if "results" not in response_body:
            logger.critical(
                "Error: unexpected http response body from Registrar Server: %s"
                % str(response.status_code))
            return None

        if "aik" not in response_body["results"]:
            logger.critical(
                "Error: did not receive AIK from Registrar Server: %s" %
                str(response.status_code))
            return None

        return response_body["results"]

    except AttributeError as e:
        if response and response.status_code == 503:
            logger.critical("Error: the registrar is not available at %s:%s" %
                            (registrar_ip, registrar_port))
        else:
            logger.exception(e)

    except Exception as e:
        logger.exception(e)

    return None
Ejemplo n.º 29
0
    def test_013_reg_agents_get(self):
        """Test registrar's GET /agents Interface"""
        test_013_reg_agents_get = RequestsClient(tenant_templ.registrar_base_tls_url, tls_enabled=True)
        response = test_013_reg_agents_get.get(f"/v{self.api_version}/agents/", cert=tenant_templ.cert, verify=False)

        self.assertEqual(response.status_code, 200, "Non-successful Registrar agent List return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("uuids", json_response["results"], "Malformed response body!")

        # We registered exactly one agent so far
        self.assertEqual(1, len(json_response["results"]["uuids"]), "Incorrect system state!")
Ejemplo n.º 30
0
    def test_032_cv_agents_get(self):
        """Test CV's GET /agents Interface"""
        test_032_cv_agents_get = RequestsClient(tenant_templ.verifier_base_url, tls_enabled)
        response = test_032_cv_agents_get.get(f"/v{self.api_version}/agents/", cert=tenant_templ.cert, verify=False)

        self.assertEqual(response.status_code, 200, "Non-successful CV agent List return code!")
        json_response = response.json()

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("uuids", json_response["results"], "Malformed response body!")

        # Be sure our agent is registered
        self.assertEqual(1, len(json_response["results"]["uuids"]))