def write_error(self, status_code, **kwargs): if self.settings.get("serve_traceback") and "exc_info" in kwargs: # in debug mode, try to send a traceback lines = [] for line in traceback.format_exception(*kwargs["exc_info"]): lines.append(line) web_util.echo_json_response(self, status_code, self._reason, lines) else: web_util.echo_json_response(self, status_code, self._reason)
def put(self): """This method handles the PUT requests to add agents to the Cloud Verifier. Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's will return errors. """ rest_params = web_util.get_restful_params(self.request.uri) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if "agents" not in rest_params: web_util.echo_json_response(self, 400, "uri not supported") logger.warning('PUT returning 400 response. uri not supported: %s', self.request.path) return agent_id = rest_params["agents"] # If the agent ID is not valid (wrong set of characters), just # do nothing. if not validators.valid_agent_id(agent_id): web_util.echo_json_response(self, 400, "agent_id not not valid") logger.error("PUT received an invalid agent ID: %s", agent_id) return # let Tenant do dirty work of reactivating agent mytenant = tenant.Tenant() mytenant.agent_uuid = agent_id mytenant.do_cvreactivate() web_util.echo_json_response(self, 200, "Success")
async def get_agent_state(self, agent_id): try: get_agent_state = RequestsClient(verifier_base_url, tls_enabled) response = get_agent_state.get( (f'/v{api_version}/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) web_util.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 not in [200, 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"]
def test_json_response_tornado(self): """Tests JSON response output for Tornado""" mock_handler = MagicMock(spec=tornado.web.RequestHandler) test_data = {"key_1": "value", "key_2": 2} expected_output = json.dumps({ "code": 200, "status": "Success", "results": test_data, }).encode("utf-8") res = web_util.echo_json_response(mock_handler, 200, "Success", test_data) self.assertTrue(res) mock_handler.set_status.assert_called_once_with(200) mock_handler.set_header.assert_called_once_with('Content-Type', 'application/json') mock_handler.write.assert_called_once_with(expected_output) mock_handler.finish.assert_called_once()
def test_json_response_http_server(self): """Tests JSON response output for Tornado""" mock_handler = MagicMock(spec=http.server.BaseHTTPRequestHandler) mock_handler.wfile = MagicMock() test_data = {"key_1": "value", "key_2": 2} expected_output = json.dumps({ "code": 200, "status": "Success", "results": test_data, }).encode("utf-8") res = web_util.echo_json_response(mock_handler, 200, "Success", test_data) self.assertTrue(res) mock_handler.send_response.assert_called_once_with(200) mock_handler.send_header.assert_called_once_with( "Content-Type", "application/json") mock_handler.end_headers.assert_called_once() mock_handler.wfile.write.assert_called_once_with(expected_output)
def do_GET(self): """This method handles the GET requests to the unprotected side of the Registrar Server Currently the only supported path is /versions which shows the supported API versions """ rest_params = web_util.get_restful_params(self.path) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /version/ interface") return if "version" not in rest_params: web_util.echo_json_response(self, 400, "URI not supported") logger.warning( 'GET agent returning 400 response. URI not supported: %s', self.path) return version_info = { "current_version": keylime_api_version.current_version(), "supported_versions": keylime_api_version.all_versions(), } web_util.echo_json_response(self, 200, "Success", version_info)
def post(self): """This method handles the POST requests to add agents to the Cloud Verifier. Currently, only agents resources are available for POSTing, i.e. /agents. All other POST uri's will return errors. agents requests require a yaml block sent in the body """ rest_params = web_util.get_restful_params(self.request.uri) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if "agents" not in rest_params: web_util.echo_json_response(self, 400, "uri not supported") logger.warning( 'POST returning 400 response. uri not supported: %s', self.request.path) return agent_id = rest_params["agents"] # If the agent ID is not valid (wrong set of characters), just # do nothing. if not validators.valid_agent_id(agent_id): web_util.echo_json_response(self, 400, "agent_id not not valid") logger.error("POST received an invalid agent ID: %s", agent_id) return # Parse payload files (base64 data-uri) if self.get_argument("ptype", Agent_Init_Types.FILE, True) == Agent_Init_Types.FILE: keyfile = None payload = None data = { 'data': parse_data_uri(self.get_argument("file_data", None, True)) } ca_dir = None incl_dir = None ca_dir_pw = None elif self.get_argument("ptype", Agent_Init_Types.FILE, True) == Agent_Init_Types.KEYFILE: keyfile = { 'data': parse_data_uri(self.get_argument("keyfile_data", None, True)), } payload = { 'data': parse_data_uri(self.get_argument("file_data", None, True)) } data = None ca_dir = None incl_dir = None ca_dir_pw = None elif self.get_argument("ptype", Agent_Init_Types.FILE, True) == Agent_Init_Types.CA_DIR: keyfile = None payload = None data = None incl_dir = { 'data': parse_data_uri( self.get_argument("include_dir_data", None, True)), 'name': self.get_argument("include_dir_name", "", True).splitlines() } ca_dir = self.get_argument("ca_dir", 'default', True) if ca_dir == "": ca_dir = 'default' ca_dir_pw = self.get_argument("ca_dir_pw", 'default', True) if ca_dir_pw == "": ca_dir_pw = 'default' else: web_util.echo_json_response(self, 400, "invalid payload type chosen") logger.warning('POST returning 400 response. malformed query') return # Pull in user-defined v/TPM policies tpm_policy = self.get_argument("tpm_policy", "", True) if tpm_policy == "": tpm_policy = None vtpm_policy = self.get_argument("vtpm_policy", "", True) if vtpm_policy == "": vtpm_policy = None # Pull in allowlist allowlist = None a_list_data = self.get_argument("a_list_data", None, True) if a_list_data != "": allowlist_str = parse_data_uri(a_list_data) if allowlist_str is not None: allowlist = allowlist_str[0].splitlines() # Pull in IMA exclude list ima_exclude = None e_list_data = self.get_argument("e_list_data", None, True) if e_list_data != "": ima_exclude_str = parse_data_uri(e_list_data) if ima_exclude_str is not None: ima_exclude = ima_exclude_str[0].splitlines() # Build args to give to Tenant's init_add method args = { 'agent_ip': self.get_argument("agent_ip", None, True), 'file': data, 'keyfile': keyfile, 'payload': payload, 'ca_dir': ca_dir, 'incl_dir': incl_dir, 'ca_dir_pw': ca_dir_pw, 'tpm_policy': tpm_policy, 'vtpm_policy': vtpm_policy, 'allowlist': allowlist, 'ima_exclude': ima_exclude, } # let Tenant do dirty work of adding agent try: mytenant = tenant.Tenant() mytenant.agent_uuid = agent_id mytenant.init_add(args) mytenant.preloop() mytenant.do_cv() mytenant.do_quote() except Exception as e: logger.exception(e) logger.warning('POST returning 500 response. Tenant error: %s', e) web_util.echo_json_response(self, 500, "Request failure", str(e)) return web_util.echo_json_response(self, 200, "Success")
async def get(self): """This method handles the GET requests to retrieve status on agents from the WebApp. Currently, only the web app is available for GETing, i.e. /agents. All other GET uri's will return errors. """ rest_params = web_util.get_restful_params(self.request.uri) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /agents/ or /logs/ interface") return if "logs" in rest_params and rest_params["logs"] == "tenant": offset = 0 if "pos" in rest_params and rest_params[ "pos"] is not None and rest_params["pos"].isdigit(): offset = int(rest_params["pos"]) # intercept requests for logs with open(keylime_logging.LOGSTREAM, encoding="utf-8") as f: logValue = f.readlines() web_util.echo_json_response(self, 200, "Success", {'log': logValue[offset:]}) return if "agents" not in rest_params: # otherwise they must be looking for agent info web_util.echo_json_response(self, 400, "uri not supported") logger.warning('GET returning 400 response. uri not supported: %s', self.request.path) return agent_id = rest_params["agents"] if agent_id is not None: # If the agent ID is not valid (wrong set of characters), # just do nothing. if not validators.valid_agent_id(agent_id): web_util.echo_json_response(self, 400, "agent_id not not valid") logger.error("GET received an invalid agent ID: %s", agent_id) return # Handle request for specific agent data separately agents = await self.get_agent_state(agent_id) agents["id"] = agent_id web_util.echo_json_response(self, 200, "Success", agents) return # If no agent ID, get list of all agents from Registrar try: get_agents = RequestsClient(registrar_base_tls_url, tls_enabled) response = get_agents.get((f'/v{api_version}/agents/'), cert=cert, verify=False) except Exception as e: logger.error( "Status command response: %s:%s Unexpected response from Registrar.", tenant_templ.registrar_ip, tenant_templ.registrar_port) logger.exception(e) web_util.echo_json_response(self, 500, "Unexpected response from Registrar", str(e)) return response_body = response.json() if response.status_code != 200: logger.error( "Status command response: %d Unexpected response from Registrar.", response.status_code) keylime_logging.log_http_response(logger, logging.ERROR, response_body) return None if ("results" not in response_body) or ("uuids" not in response_body["results"]): logger.critical( "Error: unexpected http response body from Registrar: %s", response.status_code) return None agent_list = response_body["results"]["uuids"] web_util.echo_json_response(self, 200, "Success", {'uuids': agent_list})
def do_HEAD(self): """Not supported""" web_util.echo_json_response(self, 405, "HEAD not supported")
def do_GET(self): """This method handles the GET requests to retrieve status on agents from the Registrar Server. Currently, only agents resources are available for GETing, i.e. /agents. All other GET uri's will return errors. agents requests require a single agent_id parameter which identifies the agent to be returned. If the agent_id is not found, a 404 response is returned. """ session = SessionManager().make_session(engine) rest_params = web_util.get_restful_params(self.path) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: web_util.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: web_util.echo_json_response(self, 400, "uri not supported") logger.warning('GET returning 400 response. uri not supported: %s', self.path) return agent_id = rest_params["agents"] if agent_id is not None: # If the agent ID is not valid (wrong set of characters), # just do nothing. if not validators.valid_agent_id(agent_id): web_util.echo_json_response(self, 400, "agent_id not not valid") logger.error("GET received an invalid agent ID: %s", agent_id) return try: agent = session.query(RegistrarMain).filter_by( agent_id=agent_id).first() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) if agent is None: web_util.echo_json_response(self, 404, "agent_id not found") logger.warning( 'GET returning 404 response. agent_id %s not found.', agent_id) return if not bool(agent.active): web_util.echo_json_response(self, 404, "agent_id not yet active") logger.warning( 'GET returning 404 response. agent_id %s not yet active.', agent_id) return response = { 'aik_tpm': agent.aik_tpm, 'ek_tpm': agent.ek_tpm, 'ekcert': agent.ekcert, 'mtls_cert': agent.mtls_cert, 'ip': agent.ip, 'port': agent.port, 'regcount': agent.regcount, } if agent.virtual: response['provider_keys'] = agent.provider_keys web_util.echo_json_response(self, 200, "Success", response) logger.info('GET returning 200 response for agent_id: %s', agent_id) else: # return the available registered uuids from the DB json_response = session.query(RegistrarMain.agent_id).all() return_response = [item[0] for item in json_response] web_util.echo_json_response(self, 200, "Success", {'uuids': return_response}) logger.info('GET returning 200 response for agent_id list') return
def do_PATCH(self): """PATCH not supported""" web_util.echo_json_response(self, 405, "PATCH not supported")
def do_PUT(self): """This method handles the PUT requests to add agents to the Registrar Server. Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's will return errors. """ session = SessionManager().make_session(engine) rest_params = web_util.get_restful_params(self.path) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: web_util.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: web_util.echo_json_response(self, 400, "uri not supported") logger.warning( 'PUT agent returning 400 response. uri not supported: %s', self.path) return agent_id = rest_params["agents"] if agent_id is None: web_util.echo_json_response(self, 400, "agent id not found in uri") logger.warning( 'PUT agent returning 400 response. agent id not found in uri %s', self.path) return # If the agent ID is not valid (wrong set of characters), just # do nothing. if not validators.valid_agent_id(agent_id): web_util.echo_json_response(self, 400, "agent_id not not valid") logger.error("PUT received an invalid agent ID: %s", agent_id) return try: content_length = int(self.headers.get('Content-Length', 0)) if content_length == 0: web_util.echo_json_response( self, 400, "Expected non zero content length") logger.warning( 'PUT for %s returning 400 response. Expected non zero content length.', agent_id) return post_body = self.rfile.read(content_length) json_body = json.loads(post_body) auth_tag = json_body['auth_tag'] try: agent = session.query(RegistrarMain).filter_by( agent_id=agent_id).first() except NoResultFound as e: raise Exception( "attempting to activate agent before requesting " "registrar for %s" % agent_id) from e except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) raise if config.STUB_TPM: try: session.query(RegistrarMain).filter( RegistrarMain.agent_id == agent_id).update( {'active': int(True)}) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) raise else: ex_mac = crypto.do_hmac(agent.key.encode(), agent_id) if ex_mac == auth_tag: try: session.query(RegistrarMain).filter( RegistrarMain.agent_id == agent_id).update( {'active': int(True)}) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) raise else: raise Exception( f"Auth tag {auth_tag} does not match expected value {ex_mac}" ) web_util.echo_json_response(self, 200, "Success") logger.info('PUT activated: %s', agent_id) except Exception as e: web_util.echo_json_response(self, 400, "Error: %s" % e) logger.warning("PUT for %s returning 400 response. Error: %s", agent_id, e) logger.exception(e) return
def do_POST(self): """This method handles the POST requests to add agents to the Registrar Server. Currently, only agents resources are available for POSTing, i.e. /agents. All other POST uri's will return errors. POST requests require an an agent_id identifying the agent to add, and json block sent in the body with 2 entries: ek and aik. """ session = SessionManager().make_session(engine) rest_params = web_util.get_restful_params(self.path) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: web_util.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: web_util.echo_json_response(self, 400, "uri not supported") logger.warning( 'POST agent returning 400 response. uri not supported: %s', self.path) return agent_id = rest_params["agents"] if agent_id is None: web_util.echo_json_response(self, 400, "agent id not found in uri") logger.warning( 'POST agent returning 400 response. agent id not found in uri %s', self.path) return # If the agent ID is not valid (wrong set of characters), just # do nothing. if not validators.valid_agent_id(agent_id): web_util.echo_json_response(self, 400, "agent id not valid") logger.error("POST received an invalid agent ID: %s", agent_id) return try: content_length = int(self.headers.get('Content-Length', 0)) if content_length == 0: web_util.echo_json_response( self, 400, "Expected non zero content length") logger.warning( 'POST for %s returning 400 response. Expected non zero content length.', agent_id) return post_body = self.rfile.read(content_length) json_body = json.loads(post_body) ekcert = json_body['ekcert'] aik_tpm = json_body['aik_tpm'] initialize_tpm = tpm() if ekcert is None or ekcert == 'emulator': logger.warning('Agent %s did not submit an ekcert', agent_id) ek_tpm = json_body['ek_tpm'] else: if 'ek_tpm' in json_body: # This would mean the agent submitted both a non-None ekcert, *and* # an ek_tpm... We can deal with it by just ignoring the ek_tpm they sent logger.warning( 'Overriding ek_tpm for agent %s from ekcert', agent_id) # If there's an EKCert, we just overwrite their ek_tpm # Note, we don't validate the EKCert here, other than the implicit # "is it a valid x509 cert" check. So it's still untrusted. # This will be validated by the tenant. ek509 = load_der_x509_certificate( base64.b64decode(ekcert), backend=default_backend(), ) ek_tpm = base64.b64encode( tpm2_objects.ek_low_tpm2b_public_from_pubkey( ek509.public_key(), )).decode() aik_attrs = tpm2_objects.get_tpm2b_public_object_attributes( base64.b64decode(aik_tpm), ) if aik_attrs != tpm2_objects.AK_EXPECTED_ATTRS: web_util.echo_json_response(self, 400, "Invalid AK attributes") logger.warning( "Agent %s submitted AIK with invalid attributes! %s (provided) != %s (expected)", agent_id, tpm2_objects.object_attributes_description(aik_attrs), tpm2_objects.object_attributes_description( tpm2_objects.AK_EXPECTED_ATTRS), ) return # try to encrypt the AIK (blob, key) = initialize_tpm.encryptAIK( agent_id, base64.b64decode(ek_tpm), base64.b64decode(aik_tpm), ) # special behavior if we've registered this uuid before regcount = 1 try: agent = session.query(RegistrarMain).filter_by( agent_id=agent_id).first() except NoResultFound: agent = None except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) raise if agent is not None: # keep track of how many ek-ekcerts have registered on this uuid regcount = agent.regcount if agent.ek_tpm != ek_tpm or agent.ekcert != ekcert: logger.warning( 'WARNING: Overwriting previous registration for this UUID with new ek-ekcert pair!' ) regcount += 1 # force overwrite logger.info('Overwriting previous registration for this UUID.') try: session.query(RegistrarMain).filter_by( agent_id=agent_id).delete() session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) raise # Check for ip and port contact_ip = json_body.get('ip', None) contact_port = json_body.get('port', None) # Validate ip and port if contact_ip is not None: try: # Use parser from the standard library instead of implementing our own ipaddress.ip_address(contact_ip) except ValueError: logger.warning( "Contact ip for agent %s is not a valid ip got: %s.", agent_id, contact_ip) contact_ip = None if contact_port is not None: try: contact_port = int(contact_port) if contact_port < 1 or contact_port > 65535: logger.warning( "Contact port for agent %s is not a number between 1 and got: %s.", agent_id, contact_port) contact_port = None except ValueError: logger.warning( "Contact port for agent %s is not a valid number got: %s.", agent_id, contact_port) contact_port = None # Check for mTLS cert mtls_cert = json_body.get('mtls_cert', None) if mtls_cert is None: logger.warning( "Agent %s did not send a mTLS certificate. Most operations will not work!", agent_id) # Add values to database d = {} d['agent_id'] = agent_id d['ek_tpm'] = ek_tpm d['aik_tpm'] = aik_tpm d['ekcert'] = ekcert d['ip'] = contact_ip d['mtls_cert'] = mtls_cert d['port'] = contact_port d['virtual'] = int(ekcert == 'virtual') d['active'] = int(False) d['key'] = key d['provider_keys'] = {} d['regcount'] = regcount try: session.add(RegistrarMain(**d)) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) raise response = { 'blob': blob, } web_util.echo_json_response(self, 200, "Success", response) logger.info('POST returning key blob for agent_id: %s', agent_id) except Exception as e: web_util.echo_json_response(self, 400, "Error: %s" % e) logger.warning("POST for %s returning 400 response. Error: %s", agent_id, e) logger.exception(e)
def do_DELETE(self): """This method handles the DELETE requests to remove agents from the Registrar Server. Currently, only agents resources are available for DELETEing, i.e. /agents. All other DELETE uri's will return errors. agents requests require a single agent_id parameter which identifies the agent to be deleted. """ session = SessionManager().make_session(engine) rest_params = web_util.get_restful_params(self.path) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: web_util.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: web_util.echo_json_response(self, 400, "URI not supported") logger.warning( 'DELETE agent returning 400 response. uri not supported: %s', self.path) return agent_id = rest_params["agents"] if agent_id is not None: # If the agent ID is not valid (wrong set of characters), # just do nothing. if not validators.valid_agent_id(agent_id): web_util.echo_json_response(self, 400, "agent_id not not valid") logger.error("DELETE received an invalid agent ID: %s", agent_id) return if session.query(RegistrarMain).filter_by( agent_id=agent_id).delete(): # send response try: session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) web_util.echo_json_response(self, 200, "Success") return # send response web_util.echo_json_response(self, 404) return web_util.echo_json_response(self, 404)
def do_PUT(self): """PUT not supported""" web_util.echo_json_response(self, 405, "PUT not supported via TLS interface")
def delete(self): web_util.echo_json_response( self, 405, "Not Implemented: Use /webapp/, /agents/ or /logs/ interface instead" )
def do_POST(self): """This method services the POST request typically from either the Tenant or the Cloud Verifier. Only tenant and cloudverifier uri's are supported. Both requests require a nonce parameter. The Cloud verifier requires an additional mask parameter. If the uri or parameters are incorrect, a 400 response is returned. """ rest_params = web_util.get_restful_params(self.path) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /keys/ or /notifications/ interface") return if not rest_params["api_version"]: web_util.echo_json_response(self, 400, "API Version not supported") return content_length = int(self.headers.get("Content-Length", 0)) if content_length <= 0: logger.warning( "POST returning 400 response, expected content in message. url: %s", self.path) web_util.echo_json_response(self, 400, "expected content in message") return post_body = self.rfile.read(content_length) try: json_body = json.loads(post_body) except Exception as e: logger.warning( "POST returning 400 response, could not parse body data: %s", e) web_util.echo_json_response(self, 400, "content is invalid") return if "notifications" in rest_params: if rest_params["notifications"] == "revocation": revocation_notifier.process_revocation( json_body, perform_actions, cert_path=self.server.revocation_cert_path) web_util.echo_json_response(self, 200, "Success") else: web_util.echo_json_response( self, 400, "Only /notifications/revocation is supported") return if rest_params.get("keys", None) not in ["ukey", "vkey"]: web_util.echo_json_response( self, 400, "Only /keys/ukey or /keys/vkey are supported") return try: b64_encrypted_key = json_body["encrypted_key"] decrypted_key = crypto.rsa_decrypt( self.server.rsaprivatekey, base64.b64decode(b64_encrypted_key)) except (ValueError, KeyError, TypeError) as e: logger.warning( "POST returning 400 response, could not parse body data: %s", e) web_util.echo_json_response(self, 400, "content is invalid") return have_derived_key = False if rest_params["keys"] == "ukey": if "auth_tag" not in json_body: logger.warning( "POST returning 400 response, U key provided without an auth_tag" ) web_util.echo_json_response(self, 400, "auth_tag is missing") return self.server.add_U(decrypted_key) self.server.auth_tag = json_body["auth_tag"] self.server.payload = json_body.get("payload", None) have_derived_key = self.server.attempt_decryption() elif rest_params["keys"] == "vkey": self.server.add_V(decrypted_key) have_derived_key = self.server.attempt_decryption() else: logger.warning("POST returning response. uri not supported: %s", self.path) web_util.echo_json_response(self, 400, "uri not supported") return logger.info("POST of %s key returning 200", ("V", "U")[rest_params["keys"] == "ukey"]) web_util.echo_json_response(self, 200, "Success") # no key yet, then we're done if not have_derived_key: return # woo hoo we have a key # ok lets write out the key now secdir = secure_mount.mount( ) # confirm that storage is still securely mounted # clean out the secure dir of any previous info before we extract files if os.path.isdir(os.path.join(secdir, "unzipped")): shutil.rmtree(os.path.join(secdir, "unzipped")) # write out key file with open(os.path.join(secdir, self.server.enc_keyname), "w", encoding="utf-8") as f: f.write(base64.b64encode(self.server.K).decode()) # stow the U value for later tpm_instance.write_key_nvram(self.server.final_U) # optionally extend a hash of they key and payload into specified PCR tomeasure = self.server.K # if we have a good key, now attempt to write out the encrypted payload dec_path = os.path.join(secdir, config.get("cloud_agent", "dec_payload_file")) enc_path = os.path.join(config.WORK_DIR, "encrypted_payload") dec_payload = None enc_payload = None if self.server.payload is not None: if not self.server.mtls_cert_enabled and not config.getboolean( "cloud_agent", "enable_insecure_payload", fallback=False): logger.warning( 'agent mTLS is disabled, and unless "enable_insecure_payload" is set to "True", payloads cannot be deployed' ) enc_payload = None else: dec_payload = crypto.decrypt(self.server.payload, bytes(self.server.K)) enc_payload = self.server.payload elif os.path.exists(enc_path): # if no payload provided, try to decrypt one from a previous run stored in encrypted_payload with open(enc_path, "rb") as f: enc_payload = f.read() try: dec_payload = crypto.decrypt(enc_payload, self.server.K) logger.info("Decrypted previous payload in %s to %s", enc_path, dec_path) except Exception as e: logger.warning( "Unable to decrypt previous payload %s with derived key: %s", enc_path, e) os.remove(enc_path) enc_payload = None # also write out encrypted payload to be decrytped next time if enc_payload is not None: with open(enc_path, "wb") as f: f.write(self.server.payload.encode("utf-8")) # deal with payload payload_thread = None if dec_payload is not None: tomeasure = tomeasure + dec_payload # see if payload is a zip zfio = io.BytesIO(dec_payload) if config.getboolean( "cloud_agent", "extract_payload_zip") and zipfile.is_zipfile(zfio): logger.info("Decrypting and unzipping payload to %s/unzipped", secdir) with zipfile.ZipFile(zfio, "r") as f: f.extractall(os.path.join(secdir, "unzipped")) # run an included script if one has been provided initscript = config.get("cloud_agent", "payload_script") if initscript != "": def initthread(): env = os.environ.copy() env["AGENT_UUID"] = self.server.agent_uuid with subprocess.Popen( ["/bin/bash", initscript], env=env, shell=False, cwd=os.path.join(secdir, "unzipped"), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) as proc: for line in iter(proc.stdout.readline, b""): logger.debug("init-output: %s", line.strip()) # should be a no-op as poll already told us it's done proc.wait() if not os.path.exists( os.path.join(secdir, "unzipped", initscript)): logger.info( "No payload script %s found in %s/unzipped", initscript, secdir) else: logger.info("Executing payload script: %s/unzipped/%s", secdir, initscript) payload_thread = threading.Thread(target=initthread, daemon=True) else: logger.info("Decrypting payload to %s", dec_path) with open(dec_path, "wb") as f: f.write(dec_payload) zfio.close() # now extend a measurement of the payload and key if there was one pcr = config.getint("cloud_agent", "measure_payload_pcr") if 0 < pcr < 24: logger.info("extending measurement of payload into PCR %s", pcr) measured = tpm_instance.hashdigest(tomeasure) tpm_instance.extendPCR(pcr, measured) if payload_thread is not None: payload_thread.start() return
def do_DELETE(self): """DELETE not supported""" web_util.echo_json_response(self, 405, "DELETE not supported")
def do_GET(self): """This method services the GET request typically from either the Tenant or the Cloud Verifier. Only tenant and cloudverifier uri's are supported. Both requests require a nonce parameter. The Cloud verifier requires an additional mask paramter. If the uri or parameters are incorrect, a 400 response is returned. """ logger.info("GET invoked from %s with uri: %s", self.client_address, self.path) rest_params = web_util.get_restful_params(self.path) if rest_params is None: web_util.echo_json_response( self, 405, "Not Implemented: Use /version, /keys/ or /quotes/ interfaces") return if "version" in rest_params: version_info = { "supported_version": keylime_api_version.current_version() } web_util.echo_json_response(self, 200, "Success", version_info) return if not rest_params["api_version"]: web_util.echo_json_response(self, 400, "API Version not supported") return if "keys" in rest_params and rest_params["keys"] == "verify": if self.server.K is None: logger.info( "GET key challenge returning 400 response. bootstrap key not available" ) web_util.echo_json_response( self, 400, "Bootstrap key not yet available.") return if "challenge" not in rest_params: logger.info( "GET key challenge returning 400 response. No challenge provided" ) web_util.echo_json_response(self, 400, "No challenge provided.") return challenge = rest_params["challenge"] response = {} response["hmac"] = crypto.do_hmac(self.server.K, challenge) web_util.echo_json_response(self, 200, "Success", response) logger.info("GET key challenge returning 200 response.") # If agent pubkey requested elif "keys" in rest_params and rest_params["keys"] == "pubkey": response = {} response["pubkey"] = self.server.rsapublickey_exportable web_util.echo_json_response(self, 200, "Success", response) logger.info("GET pubkey returning 200 response.") return elif "quotes" in rest_params: nonce = rest_params.get("nonce", None) pcrmask = rest_params.get("mask", None) ima_ml_entry = rest_params.get("ima_ml_entry", "0") # if the query is not messed up if nonce is None: logger.warning( "GET quote returning 400 response. nonce not provided as an HTTP parameter in request" ) web_util.echo_json_response( self, 400, "nonce not provided as an HTTP parameter in request") return # Sanitization assurance (for tpm.run() tasks below) if not (nonce.isalnum() and (pcrmask is None or validators.valid_hex(pcrmask)) and ima_ml_entry.isalnum()): logger.warning( "GET quote returning 400 response. parameters should be strictly alphanumeric" ) web_util.echo_json_response( self, 400, "parameters should be strictly alphanumeric") return if len(nonce) > tpm_instance.MAX_NONCE_SIZE: logger.warning( "GET quote returning 400 response. Nonce is too long (max size %i): %i", tpm_instance.MAX_NONCE_SIZE, len(nonce), ) web_util.echo_json_response( self, 400, f"Nonce is too long (max size {tpm_instance.MAX_NONCE_SIZE}): {len(nonce)}" ) return hash_alg = tpm_instance.defaults["hash"] quote = tpm_instance.create_quote( nonce, self.server.rsapublickey_exportable, pcrmask, hash_alg) imaMask = pcrmask # Allow for a partial quote response (without pubkey) enc_alg = tpm_instance.defaults["encrypt"] sign_alg = tpm_instance.defaults["sign"] if "partial" in rest_params and (rest_params["partial"] is None or rest_params["partial"] == "1"): response = { "quote": quote, "hash_alg": hash_alg, "enc_alg": enc_alg, "sign_alg": sign_alg, } else: response = { "quote": quote, "hash_alg": hash_alg, "enc_alg": enc_alg, "sign_alg": sign_alg, "pubkey": self.server.rsapublickey_exportable, } response["boottime"] = self.server.boottime # return a measurement list if available if TPM_Utilities.check_mask(imaMask, config.IMA_PCR): ima_ml_entry = int(ima_ml_entry) if ima_ml_entry > self.server.next_ima_ml_entry: ima_ml_entry = 0 ml, nth_entry, num_entries = ima.read_measurement_list( self.server.ima_log_file, ima_ml_entry) if num_entries > 0: response["ima_measurement_list"] = ml response["ima_measurement_list_entry"] = nth_entry self.server.next_ima_ml_entry = num_entries # similar to how IMA log retrievals are triggered by IMA_PCR, we trigger boot logs with MEASUREDBOOT_PCRs # other possibilities would include adding additional data to rest_params to trigger boot log retrievals # generally speaking, retrieving the 15Kbytes of a boot log does not seem significant compared to the # potential Mbytes of an IMA measurement list. if TPM_Utilities.check_mask(imaMask, config.MEASUREDBOOT_PCRS[0]): if not self.server.tpm_log_file_data: logger.warning("TPM2 event log not available: %s", config.MEASUREDBOOT_ML) else: response[ "mb_measurement_list"] = self.server.tpm_log_file_data web_util.echo_json_response(self, 200, "Success", response) logger.info("GET %s quote returning 200 response.", rest_params["quotes"]) return else: logger.warning("GET returning 400 response. uri not supported: %s", self.path) web_util.echo_json_response(self, 400, "uri not supported") return
def head(self): """HEAD not supported""" web_util.echo_json_response(self, 405, "HEAD not supported")