Example #1
0
def process_quote_response(agent, json_response):
    """Validates the response from the Cloud agent.
    
    This method invokes an Registrar Server call to register, and then check the quote. 
    """
    received_public_key = None
    quote = None
    
    # in case of failure in response content do not continue
    try:
        received_public_key = json_response.get("pubkey",None)
        quote = json_response["quote"]
        
        ima_measurement_list = json_response.get("ima_measurement_list",None)
        
        logger.debug("received quote:      %s"%quote)
        logger.debug("for nonce:           %s"%agent['nonce'])
        logger.debug("received public key: %s"%received_public_key)
        logger.debug("received ima_measurement_list    %s"%(ima_measurement_list!=None))
    except Exception:
        return None
    
    # if no public key provided, then ensure we have cached it
    if received_public_key is None:
        if agent.get('public_key',"") == "" or agent.get('b64_encrypted_V',"")=="":
            logger.error("agent did not provide public key and no key or encrypted_v was cached at CV")
            return False
        agent['provide_V'] = False
        received_public_key = agent['public_key']
    
    if agent.get('registrar_keys',"") is "":
        registrar_client.init_client_tls(config,'cloud_verifier')
        registrar_keys = registrar_client.getKeys(config.get("general","registrar_ip"),config.get("general","registrar_tls_port"),agent['agent_id'])
        if registrar_keys is None:
            logger.warning("AIK not found in registrar, quote not validated")
            return False
        agent['registrar_keys']  = registrar_keys
        
    tpm_version = json_response.get('tpm_version')
    tpm = tpm_obj.getTPM(need_hw_tpm=False,tpm_version=tpm_version)
    hash_alg = json_response.get('hash_alg')
    enc_alg = json_response.get('enc_alg')
    sign_alg = json_response.get('sign_alg')
    
    # Update chosen tpm and algorithms
    agent['tpm_version'] = tpm_version
    agent['hash_alg'] = hash_alg
    agent['enc_alg'] = enc_alg
    agent['sign_alg'] = sign_alg
    
    # Ensure hash_alg is in accept_tpm_hash_alg list
    if not Hash_Algorithms.is_accepted(hash_alg, agent['accept_tpm_hash_algs']):
        raise Exception("TPM Quote is using an unaccepted hash algorithm: %s"%hash_alg)
    
    # Ensure enc_alg is in accept_tpm_encryption_algs list
    if not Encrypt_Algorithms.is_accepted(enc_alg, agent['accept_tpm_encryption_algs']):
        raise Exception("TPM Quote is using an unaccepted encryption algorithm: %s"%enc_alg)
    
    # Ensure sign_alg is in accept_tpm_encryption_algs list
    if not Sign_Algorithms.is_accepted(sign_alg, agent['accept_tpm_signing_algs']):
        raise Exception("TPM Quote is using an unaccepted signing algorithm: %s"%sign_alg)
    
    if tpm.is_deep_quote(quote):
        validQuote = tpm.check_deep_quote(agent['nonce'],
                                                received_public_key,
                                                quote,
                                                agent['registrar_keys']['aik'],
                                                agent['registrar_keys']['provider_keys']['aik'],
                                                agent['vtpm_policy'],
                                                agent['tpm_policy'],
                                                ima_measurement_list,
                                                agent['ima_whitelist'])
    else:
        validQuote = tpm.check_quote(agent['nonce'],
                                           received_public_key,
                                           quote,
                                           agent['registrar_keys']['aik'],
                                           agent['tpm_policy'],
                                           ima_measurement_list,
                                           agent['ima_whitelist'],
                                           hash_alg)
    if not validQuote:
        return False
    
    # set a flag so that we know that the agent was verified once.
    # we only issue notifications for agents that were at some point good
    agent['first_verified']=True
    
    # has public key changed? if so, clear out b64_encrypted_V, it is no longer valid
    if received_public_key != agent.get('public_key',""):
        agent['public_key'] = received_public_key
        agent['b64_encrypted_V'] = ""
        agent['provide_V'] = True
    
    # ok we're done
    return validQuote
Example #2
0
def process_quote_response(instance, json_response):
    """Validates the response from the Cloud node.
    
    This method invokes an Registrar Server call to register, and then check the quote. 
    """
    received_public_key = None
    quote = None

    # in case of failure in response content do not continue
    try:
        received_public_key = json_response.get("pubkey", None)
        quote = json_response["quote"]

        ima_measurement_list = json_response.get("ima_measurement_list", None)

        logger.debug("received quote:      %s" % quote)
        logger.debug("for nonce:           %s" % instance['nonce'])
        logger.debug("received public key: %s" % received_public_key)
        logger.debug("received ima_measurement_list    %s" %
                     (ima_measurement_list != None))
    except Exception:
        return None

    # if no public key provided, then ensure we have cached it
    if received_public_key is None:
        if instance.get('public_key', "") == "" or instance.get(
                'b64_encrypted_V', "") == "":
            logger.error(
                "node did not provide public key and no key or encrypted_v was cached at CV"
            )
            return False
        instance['provide_V'] = False
        received_public_key = instance['public_key']

    if instance.get('registrar_keys', "") is "":
        registrar_client.init_client_tls(config, 'cloud_verifier')
        registrar_keys = registrar_client.getKeys(
            config.get("general", "registrar_ip"),
            config.get("general", "registrar_tls_port"),
            instance['instance_id'])
        if registrar_keys is None:
            logger.warning("AIK not found in registrar, quote not validated")
            return False
        instance['registrar_keys'] = registrar_keys

    if tpm_quote.is_deep_quote(quote):
        validQuote = tpm_quote.check_deep_quote(
            instance['nonce'], received_public_key, quote,
            instance['registrar_keys']['aik'],
            instance['registrar_keys']['provider_keys']['aik'],
            instance['vtpm_policy'], instance['tpm_policy'],
            ima_measurement_list, instance['ima_whitelist'])
    else:
        validQuote = tpm_quote.check_quote(instance['nonce'],
                                           received_public_key, quote,
                                           instance['registrar_keys']['aik'],
                                           instance['tpm_policy'],
                                           ima_measurement_list,
                                           instance['ima_whitelist'])
    if not validQuote:
        return False

    # set a flag so that we know that the node was verified once.
    # we only issue notifications for nodes that were at some point good
    instance['first_verified'] = True

    # has public key changed? if so, clear out b64_encrypted_V, it is no longer valid
    if received_public_key != instance.get('public_key', ""):
        instance['public_key'] = received_public_key
        instance['b64_encrypted_V'] = ""
        instance['provide_V'] = True

    # ok we're done
    return validQuote
Example #3
0
    def validate_tpm_quote(self, public_key, quote, tpm_version, hash_alg):
        registrar_client.init_client_tls(config, 'tenant')
        reg_keys = registrar_client.getKeys(self.cloudverifier_ip,
                                            self.registrar_port,
                                            self.agent_uuid)
        if reg_keys is None:
            logger.warning("AIK not found in registrar, quote not validated")
            return False

        tpm = tpm_obj.getTPM(need_hw_tpm=False, tpm_version=tpm_version)
        if not tpm.check_quote(
                self.nonce, public_key, quote, reg_keys['aik'],
                hash_alg=hash_alg):
            if reg_keys['regcount'] > 1:
                raise UserError(
                    "WARNING: This UUID had more than one ek-ekcert registered to it!  This might indicate that your system is misconfigured or a malicious host is present.  Run 'regdelete' for this agent and restart it to make this message go away!"
                )
            return False

        if reg_keys['regcount'] > 1:
            logger.warn(
                "WARNING: This UUID had more than one ek-ekcert registered to it!  This might indicate that your system is misconfigured.  Run 'regdelete' for this agent and restart it to make this message go away!"
            )

        if not common.STUB_TPM and (
                not config.getboolean('tenant', 'require_ek_cert')
                and config.get('tenant', 'ek_check_script') == ""):
            logger.warn(
                "DANGER: EK cert checking is disabled and no additional checks on EKs have been specified with ek_check_script option. Keylime is not secure!!"
            )

        # check EK cert and make sure it matches EK
        if not self.check_ek(reg_keys['ek'], reg_keys['ekcert'], tpm):
            return False
        # if agent is virtual, check phyisical EK cert and make sure it matches phyiscal EK
        if 'provider_keys' in reg_keys:
            if not self.check_ek(reg_keys['provider_keys']['ek'],
                                 reg_keys['provider_keys']['ekcert'], tpm):
                return False

        # check all EKs with optional script:
        script = config.get('tenant', 'ek_check_script')
        if script is not "":
            if script[0] != '/':
                script = "%s/%s" % (common.WORK_DIR, script)

            logger.info("Checking EK with script %s" % script)
            #now we need to exec the script with the ek and ek cert in vars
            env = os.environ.copy()
            env['AGENT_UUID'] = self.agent_uuid
            env['EK'] = reg_keys['ek']
            if reg_keys['ekcert'] is not None:
                env['EK_CERT'] = reg_keys['ekcert']
            else:
                env['EK_CERT'] = ""

            env['PROVKEYS'] = json.dumps(reg_keys.get('provider_keys', {}))
            proc = subprocess.Popen(script,
                                    env=env,
                                    shell=True,
                                    cwd=common.WORK_DIR,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            retval = proc.wait()

            if retval != 0:
                raise UserError("External check script failed to validate EK")
                while True:
                    line = proc.stdout.readline()
                    if line == "":
                        break
                    logger.debug("ek_check output: %s" % line.strip())
                return False
            else:
                logger.debug(
                    "External check script successfully to validated EK")
                while True:
                    line = proc.stdout.readline()
                    if line == "":
                        break
                    logger.debug("ek_check output: %s" % line.strip())
        return True
Example #4
0
    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.
        """
        rest_params = common.get_restful_params(self.path)
        if rest_params is None:
            common.echo_json_response(
                self, 405, "Not Implemented: Use /agents/ interface")
            return

        if "agents" not in rest_params:
            common.echo_json_response(self, 400, "uri not supported")
            logger.warning(
                'PUT agent returning 400 response. uri not supported: ' +
                self.path)
            return

        agent_id = rest_params["agents"]

        if agent_id is None:
            common.echo_json_response(self, 400, "agent id not found in uri")
            logger.warning(
                'PUT agent returning 400 response. agent id not found in uri '
                + self.path)
            return

        try:
            content_length = int(self.headers.get('Content-Length', 0))
            if content_length == 0:
                common.echo_json_response(self, 400,
                                          "Expected non zero content length")
                logger.warning(
                    'PUT for ' + agent_id +
                    ' returning 400 response. Expected non zero content length.'
                )
                return

            post_body = self.rfile.read(content_length)
            json_body = json.loads(post_body)

            if "activate" in rest_params:
                auth_tag = json_body['auth_tag']

                agent = self.server.db.get_agent(agent_id)
                if agent is None:
                    raise Exception(
                        "attempting to activate agent before requesting registrar for %s"
                        % agent_id)

                if agent['virtual']:
                    raise Exception(
                        "attempting to activate virtual AIK using physical interface for %s"
                        % agent_id)

                if common.STUB_TPM:
                    self.server.db.update_agent(agent_id, 'active', True)
                else:
                    ex_mac = crypto.do_hmac(base64.b64decode(agent['key']),
                                            agent_id)
                    if ex_mac == auth_tag:
                        self.server.db.update_agent(agent_id, 'active', True)
                    else:
                        raise Exception(
                            "Auth tag %s does not match expected value %s" %
                            (auth_tag, ex_mac))

                common.echo_json_response(self, 200, "Success")
                logger.info('PUT activated: ' + agent_id)
            elif "vactivate" in rest_params:
                deepquote = json_body.get('deepquote', None)

                agent = self.server.db.get_agent(agent_id)
                if agent is None:
                    raise Exception(
                        "attempting to activate agent before requesting registrar for %s"
                        % agent_id)

                if not agent['virtual']:
                    raise Exception(
                        "attempting to activate physical AIK using virtual interface for %s"
                        % agent_id)

                # get an physical AIK for this host
                registrar_client.init_client_tls(config, 'registrar')
                provider_keys = registrar_client.getKeys(
                    config.get('general', 'provider_registrar_ip'),
                    config.get('general', 'provider_registrar_tls_port'),
                    agent_id)
                # we already have the vaik
                tpm = tpm_obj.getTPM(need_hw_tpm=False,
                                     tpm_version=agent['tpm_version'])
                if not tpm.check_deep_quote(
                        hashlib.sha1(agent['key']).hexdigest(),
                        agent_id + agent['aik'] + agent['ek'], deepquote,
                        agent['aik'], provider_keys['aik']):
                    raise Exception("Deep quote invalid")

                self.server.db.update_agent(agent_id, 'active', True)
                self.server.db.update_agent(agent_id, 'provider_keys',
                                            provider_keys)

                common.echo_json_response(self, 200, "Success")
                logger.info('PUT activated: ' + agent_id)
            else:
                pass
        except Exception as e:
            common.echo_json_response(self, 400, "Error: %s" % e)
            logger.warning("PUT for " + agent_id +
                           " returning 400 response. Error: %s" % e)
            logger.exception(e)
            return
Example #5
0
    def validate_tpm_quote(self, public_key, quote):
        registrar_client.init_client_tls(config, 'tenant')
        reg_keys = registrar_client.getKeys(self.cloudverifier_ip,
                                            self.registrar_port,
                                            self.node_uuid)
        if reg_keys is None:
            logger.warning("AIK not found in registrar, quote not validated")
            return False

        if not tpm_quote.check_quote(self.nonce, public_key, quote,
                                     reg_keys['aik']):
            return False

        if not common.STUB_TPM and (
                not config.getboolean('tenant', 'require_ek_cert')
                and config.get('tenant', 'ek_check_script') == ""):
            logger.warn(
                "DANGER: EK cert checking is disabled and no additional checks on EKs have been specified with ek_check_script option. Keylime is not secure!!"
            )

        # check EK cert and make sure it matches EK
        if not self.check_ek(reg_keys['ek'], reg_keys['ekcert']):
            return False
        # if node is virtual, check phyisical EK cert and make sure it matches phyiscal EK
        if 'provider_keys' in reg_keys:
            if not self.check_ek(reg_keys['provider_keys']['ek'],
                                 reg_keys['provider_keys']['ekcert']):
                return False

        # check all EKs with optional script:
        script = config.get('tenant', 'ek_check_script')
        if script is not "":
            logger.info("Checking EK with script %s" % script)
            #now we need to exec the script with the ek and ek cert in vars
            env = os.environ.copy()
            env['NODE_UUID'] = self.node_uuid
            env['EK'] = reg_keys['ek']
            if reg_keys['ekcert'] is not None:
                env['EK_CERT'] = reg_keys['ekcert']
            else:
                env['EK_CERT'] = ""

            env['PROVKEYS'] = json.dumps(reg_keys.get('provider_keys', {}))
            proc = subprocess.Popen(script,
                                    env=env,
                                    shell=True,
                                    cwd=common.WORK_DIR,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            retval = proc.wait()

            if retval != 0:
                logger.error("External check script failed to validate EK")
                while True:
                    line = proc.stdout.readline()
                    if line == "":
                        break
                    logger.debug("ek_check output: %s" % line.strip())
                return False

        return True