Пример #1
0
    def test_mixed_verfication(self):
        """ Test verification using allowlist and keys """

        lists_map = ima.process_allowlists(ALLOWLIST.splitlines(), '')

        # every entry is covered by the allowlist and there's no keyring -> this should pass
        self.assertTrue(
            ima.process_measurement_list(COMBINED.splitlines(), str(lists_map))
            is not None)

        curdir = os.path.dirname(os.path.abspath(__file__))
        keydir = os.path.join(curdir, "data", "ima_keys")
        keyring = ima_file_signatures.ImaKeyring()

        rsakeyfile = os.path.join(keydir, "rsa2048pub.pem")
        pubkey = ima_file_signatures.get_pubkey_from_file(rsakeyfile)
        keyring.add_pubkey(pubkey)

        eckeyfile = os.path.join(keydir, "secp256k1.pem")
        pubkey = ima_file_signatures.get_pubkey_from_file(eckeyfile)
        keyring.add_pubkey(pubkey)

        # entries are not covered by a exclude list -> this should fail
        self.assertTrue(
            ima.process_measurement_list(COMBINED.splitlines(),
                                         ima_keyring=keyring) is None)

        # all entries are either covered by exclude list or by signature verification -> this should pass
        self.assertTrue(
            ima.process_measurement_list(COMBINED.splitlines(),
                                         str(lists_map),
                                         ima_keyring=keyring) is not None)
Пример #2
0
    def test_signature_verification(self):
        """ Test the signature verification """
        curdir = os.path.dirname(os.path.abspath(__file__))
        keydir = os.path.join(curdir, "data", "ima_keys")

        lines = SIGNATURES.split('\n')

        # empty keyring
        keyring = ima_file_signatures.ImaKeyring()
        self.assertTrue(
            ima.process_measurement_list(lines, ima_keyring=keyring) is None)

        # add key for 1st entry; 1st entry must be verifiable
        rsakeyfile = os.path.join(keydir, "rsa2048pub.pem")
        pubkey = ima_file_signatures.get_pubkey_from_file(rsakeyfile)
        keyring.add_pubkey(pubkey)
        self.assertTrue(
            ima.process_measurement_list(lines[0:1], ima_keyring=keyring)
            is not None)
        self.assertTrue(
            ima.process_measurement_list(lines[1:2], ima_keyring=keyring) is
            None)

        # add key for 2nd entry; 1st & 2nd entries must be verifiable
        eckeyfile = os.path.join(keydir, "secp256k1.pem")
        pubkey = ima_file_signatures.get_pubkey_from_file(eckeyfile)
        keyring.add_pubkey(pubkey)
        self.assertTrue(
            ima.process_measurement_list(lines[0:2], ima_keyring=keyring)
            is not None)
Пример #3
0
    def test_signature_verification(self):
        """ Test the signature verification """
        curdir = os.path.dirname(os.path.abspath(__file__))
        keydir = os.path.join(curdir, "data", "ima_keys")

        lines = SIGNATURES.split('\n')

        # empty keyring
        keyrings = ima_file_signatures.ImaKeyrings()
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  lines,
                                                  ima_keyrings=keyrings)
        self.assertTrue(failure)

        tenant_keyring = ima_file_signatures.ImaKeyring()
        keyrings.set_tenant_keyring(tenant_keyring)

        # add key for 1st entry; 1st entry must be verifiable
        rsakeyfile = os.path.join(keydir, "rsa2048pub.pem")
        pubkey, keyidv2 = ima_file_signatures.get_pubkey_from_file(rsakeyfile)
        tenant_keyring.add_pubkey(pubkey, keyidv2)
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  lines[0:1],
                                                  ima_keyrings=keyrings)
        self.assertTrue(not failure)
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  lines[1:2],
                                                  ima_keyrings=keyrings)
        self.assertTrue(failure)

        # add key for 2nd entry; 1st & 2nd entries must be verifiable
        eckeyfile = os.path.join(keydir, "secp256k1.pem")
        pubkey, keyidv2 = ima_file_signatures.get_pubkey_from_file(eckeyfile)
        tenant_keyring.add_pubkey(pubkey, keyidv2)
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  lines[0:2],
                                                  ima_keyrings=keyrings)
        self.assertTrue(not failure)
Пример #4
0
    def process_allowlist(self, args):
        # Set up PCR values
        tpm_policy = config.get('tenant', 'tpm_policy')
        if "tpm_policy" in args and args["tpm_policy"] is not None:
            tpm_policy = args["tpm_policy"]
        self.tpm_policy = TPM_Utilities.readPolicy(tpm_policy)
        logger.info("TPM PCR Mask from policy is %s", self.tpm_policy['mask'])

        vtpm_policy = config.get('tenant', 'vtpm_policy')
        if "vtpm_policy" in args and args["vtpm_policy"] is not None:
            vtpm_policy = args["vtpm_policy"]
        self.vtpm_policy = TPM_Utilities.readPolicy(vtpm_policy)
        logger.info("TPM PCR Mask from policy is %s", self.vtpm_policy['mask'])

        if args.get("ima_sign_verification_keys") is not None:
            # Auto-enable IMA (or-bit mask)
            self.tpm_policy['mask'] = "0x%X" % (
                    int(self.tpm_policy['mask'], 0) | (1 << config.IMA_PCR))

            # Add all IMA file signing verification keys to a keyring
            ima_keyring = ima_file_signatures.ImaKeyring()
            for filename in args["ima_sign_verification_keys"]:
                pubkey = ima_file_signatures.get_pubkey_from_file(filename)
                if not pubkey:
                    raise UserError(
                        "File '%s' is not a file with a key" % filename)
                ima_keyring.add_pubkey(pubkey)
            self.ima_sign_verification_keys = ima_keyring.to_string()

        # Read command-line path string allowlist
        al_data = None

        if "allowlist" in args and args["allowlist"] is not None:

            self.enforce_pcrs(list(self.tpm_policy.keys()), [ config.IMA_PCR ], "IMA")

            # Auto-enable IMA (or-bit mask)
            self.tpm_policy['mask'] = "0x%X" % (
                    int(self.tpm_policy['mask'], 0) | (1 << config.IMA_PCR))

            if isinstance(args["allowlist"], str):
                if args["allowlist"] == "default":
                    args["allowlist"] = config.get('tenant', 'allowlist')
                al_data = ima.read_allowlist(args["allowlist"], args["allowlist_checksum"], args["allowlist_sig"], args["allowlist_sig_key"])
            elif isinstance(args["allowlist"], list):
                al_data = args["allowlist"]
            else:
                raise UserError("Invalid allowlist provided")

        # Read command-line path string IMA exclude list
        excl_data = None
        if "ima_exclude" in args and args["ima_exclude"] is not None:
            if isinstance(args["ima_exclude"], str):
                if args["ima_exclude"] == "default":
                    args["ima_exclude"] = config.get(
                        'tenant', 'ima_excludelist')
                excl_data = ima.read_excllist(args["ima_exclude"])
            elif isinstance(args["ima_exclude"], list):
                excl_data = args["ima_exclude"]
            else:
                raise UserError("Invalid exclude list provided")

        # Set up IMA
        if TPM_Utilities.check_mask(self.tpm_policy['mask'], config.IMA_PCR) or \
                TPM_Utilities.check_mask(self.vtpm_policy['mask'],
                                         config.IMA_PCR):
            # Process allowlists
            self.allowlist = ima.process_allowlists(al_data, excl_data)

        # Read command-line path string TPM event log (measured boot) reference state
        mb_refstate_data = None
        if "mb_refstate" in args and args["mb_refstate"] is not None:

            self.enforce_pcrs(list(self.tpm_policy.keys()), config.MEASUREDBOOT_PCRS, "measured boot")

            # Auto-enable TPM event log mesured boot (or-bit mask)
            for _pcr in config.MEASUREDBOOT_PCRS :
                self.tpm_policy['mask'] = "0x%X" % (
                    int(self.tpm_policy['mask'], 0) | (1 << _pcr))

            logger.info("TPM PCR Mask automatically modified is %s to include IMA/Event log PCRs", self.tpm_policy['mask'])

            if isinstance(args["mb_refstate"], str):
                if args["mb_refstate"] == "default":
                    args["mb_refstate"] = config.get('tenant', 'mb_refstate')
                mb_refstate_data = measured_boot.read_mb_refstate(args["mb_refstate"])
            else:
                raise UserError("Invalid measured boot reference state (intended state) provided")

        # Set up measured boot (TPM event log) reference state
        if TPM_Utilities.check_mask(self.tpm_policy['mask'], config.MEASUREDBOOT_PCRS[2]) :

            # Process measured boot reference state
            self.mb_refstate = measured_boot.process_refstate(mb_refstate_data)
Пример #5
0
    def test_mixed_verfication(self):
        """ Test verification using allowlist and keys """

        lists_map = ima.process_allowlists(ALLOWLIST, '')
        lists_map_wrong = ima.process_allowlists(ALLOWLIST_WRONG, '')
        lists_map_empty = ima.process_allowlists(ALLOWLIST_EMPTY, '')
        lists_map_exclude = ima.process_allowlists(ALLOWLIST, EXCLUDELIST)
        lists_map_exclude_wrong = ima.process_allowlists(
            ALLOWLIST_WRONG, EXCLUDELIST)

        ima_keyrings = ima_file_signatures.ImaKeyrings()
        empty_keyring = ima_file_signatures.ImaKeyring()

        # every entry is covered by the allowlist and there's no keyring -> this should pass
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  COMBINED.splitlines(),
                                                  json.dumps(lists_map))
        self.assertTrue(not failure)

        curdir = os.path.dirname(os.path.abspath(__file__))
        keydir = os.path.join(curdir, "data", "ima_keys")
        tenant_keyring = ima_file_signatures.ImaKeyring()

        rsakeyfile = os.path.join(keydir, "rsa2048pub.pem")
        pubkey, keyidv2 = ima_file_signatures.get_pubkey_from_file(rsakeyfile)
        tenant_keyring.add_pubkey(pubkey, keyidv2)

        eckeyfile = os.path.join(keydir, "secp256k1.pem")
        pubkey, keyidv2 = ima_file_signatures.get_pubkey_from_file(eckeyfile)
        tenant_keyring.add_pubkey(pubkey, keyidv2)

        ima_keyrings.set_tenant_keyring(tenant_keyring)

        # entries are not covered by a exclude list -> this should fail
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  COMBINED.splitlines(),
                                                  ima_keyrings=ima_keyrings)
        self.assertTrue(failure)

        # all entries are either covered by allow list or by signature verification -> this should pass
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  COMBINED.splitlines(),
                                                  json.dumps(lists_map),
                                                  ima_keyrings=ima_keyrings)
        self.assertTrue(not failure)

        # the signature is valid but the hash in the allowlist is wrong -> this should fail
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  SIGNATURES.splitlines(),
                                                  json.dumps(lists_map_wrong),
                                                  ima_keyrings=ima_keyrings)
        self.assertTrue(failure)

        # the signature is valid and the file is not in the allowlist -> this should pass
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  SIGNATURES.splitlines(),
                                                  json.dumps(lists_map_empty),
                                                  ima_keyrings=ima_keyrings)
        self.assertTrue(not failure)

        # the signature is invalid but the correct hash is in the allowlist -> this should fail
        ima_keyrings.set_tenant_keyring(empty_keyring)
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  SIGNATURES.splitlines(),
                                                  json.dumps(lists_map),
                                                  ima_keyrings=ima_keyrings)
        self.assertTrue(failure)

        # the file has no signature but the hash is correct -> this should pass
        _, failure = ima.process_measurement_list(AgentAttestState('1'),
                                                  MEASUREMENTS.splitlines(),
                                                  json.dumps(lists_map))
        self.assertTrue(not failure)

        # All files are in the exclude list but hashes are invalid -> this should pass
        _, failure = ima.process_measurement_list(
            AgentAttestState('1'), MEASUREMENTS.splitlines(),
            json.dumps(lists_map_exclude_wrong))
        self.assertTrue(not failure)

        # All files are in the exclude list and their signatures are invalid -> this should pass
        ima_keyrings.set_tenant_keyring(tenant_keyring)
        _, failure = ima.process_measurement_list(
            AgentAttestState('1'),
            SIGNATURES.splitlines(),
            json.dumps(lists_map_exclude),
            ima_keyrings=ima_keyrings)
        self.assertTrue(not failure)

        # All files are in the exclude list but hashes or signatures are invalid -> this should pass
        _, failure = ima.process_measurement_list(
            AgentAttestState('1'),
            MEASUREMENTS.splitlines(),
            json.dumps(lists_map_exclude_wrong),
            ima_keyrings=ima_keyrings)
        self.assertTrue(not failure)
Пример #6
0
    def init_add(self, args):
        """ Set up required values. Command line options can overwrite these config values

        Arguments:
            args {[string]} -- agent_ip|agent_port|cv_agent_ip
        """
        if "agent_ip" in args:
            self.agent_ip = args["agent_ip"]

        if 'agent_port' in args and args['agent_port'] is not None:
            self.agent_port = args['agent_port']

        if 'cv_agent_ip' in args and args['cv_agent_ip'] is not None:
            self.cv_cloudagent_ip = args['cv_agent_ip']
        else:
            self.cv_cloudagent_ip = self.agent_ip

        # Make sure all keys exist in dictionary
        if "file" not in args:
            args["file"] = None
        if "keyfile" not in args:
            args["keyfile"] = None
        if "payload" not in args:
            args["payload"] = None
        if "ca_dir" not in args:
            args["ca_dir"] = None
        if "incl_dir" not in args:
            args["incl_dir"] = None
        if "ca_dir_pw" not in args:
            args["ca_dir_pw"] = None

        # Set up accepted algorithms
        self.accept_tpm_hash_algs = config.get(
            'tenant', 'accept_tpm_hash_algs').split(',')
        self.accept_tpm_encryption_algs = config.get(
            'tenant', 'accept_tpm_encryption_algs').split(',')
        self.accept_tpm_signing_algs = config.get(
            'tenant', 'accept_tpm_signing_algs').split(',')

        # Set up PCR values
        tpm_policy = config.get('tenant', 'tpm_policy')
        if "tpm_policy" in args and args["tpm_policy"] is not None:
            tpm_policy = args["tpm_policy"]
        self.tpm_policy = TPM_Utilities.readPolicy(tpm_policy)
        logger.info(f"TPM PCR Mask from policy is {self.tpm_policy['mask']}")

        vtpm_policy = config.get('tenant', 'vtpm_policy')
        if "vtpm_policy" in args and args["vtpm_policy"] is not None:
            vtpm_policy = args["vtpm_policy"]
        self.vtpm_policy = TPM_Utilities.readPolicy(vtpm_policy)
        logger.info(f"TPM PCR Mask from policy is {self.vtpm_policy['mask']}")

        if args.get("ima_sign_verification_keys") is not None:
            # Auto-enable IMA (or-bit mask)
            self.tpm_policy['mask'] = "0x%X" % (int(self.tpm_policy['mask'], 0)
                                                | (1 << config.IMA_PCR))

            # Add all IMA file signing verification keys to a keyring
            ima_keyring = ima_file_signatures.ImaKeyring()
            for filename in args["ima_sign_verification_keys"]:
                pubkey = ima_file_signatures.get_pubkey_from_file(filename)
                if not pubkey:
                    raise UserError("File '%s' is not a file with a key" %
                                    filename)
                ima_keyring.add_pubkey(pubkey)
            self.ima_sign_verification_keys = ima_keyring.to_string()

        # Read command-line path string allowlist
        al_data = None

        if "allowlist" in args and args["allowlist"] is not None:

            self.enforce_pcrs(list(self.tpm_policy.keys()), [config.IMA_PCR],
                              "IMA")

            # Auto-enable IMA (or-bit mask)
            self.tpm_policy['mask'] = "0x%X" % (int(self.tpm_policy['mask'], 0)
                                                | (1 << config.IMA_PCR))

            if isinstance(args["allowlist"], str):
                if args["allowlist"] == "default":
                    args["allowlist"] = config.get('tenant', 'allowlist')
                al_data = ima.read_allowlist(args["allowlist"])
            elif isinstance(args["allowlist"], list):
                al_data = args["allowlist"]
            else:
                raise UserError("Invalid allowlist provided")

        # Read command-line path string IMA exclude list
        excl_data = None
        if "ima_exclude" in args and args["ima_exclude"] is not None:
            if isinstance(args["ima_exclude"], str):
                if args["ima_exclude"] == "default":
                    args["ima_exclude"] = config.get('tenant',
                                                     'ima_excludelist')
                excl_data = ima.read_excllist(args["ima_exclude"])
            elif isinstance(args["ima_exclude"], list):
                excl_data = args["ima_exclude"]
            else:
                raise UserError("Invalid exclude list provided")

        # Set up IMA
        if TPM_Utilities.check_mask(self.tpm_policy['mask'], config.IMA_PCR) or \
                TPM_Utilities.check_mask(self.vtpm_policy['mask'], config.IMA_PCR):

            # Process allowlists
            self.allowlist = ima.process_allowlists(al_data, excl_data)

        # Read command-line path string TPM2 event log template
        if "mb_refstate" in args and args["mb_refstate"] is not None:

            self.enforce_pcrs(list(self.tpm_policy.keys()),
                              config.MEASUREDBOOT_PCRS, "measured boot")

            # Auto-enable TPM2 event log (or-bit mask)
            for _pcr in config.MEASUREDBOOT_PCRS:
                self.tpm_policy['mask'] = "0x%X" % (int(
                    self.tpm_policy['mask'], 0) | (1 << _pcr))

            logger.info(
                f"TPM PCR Mask automatically modified is {self.tpm_policy['mask']} to include IMA/Event log PCRs"
            )

            if isinstance(args["mb_refstate"], str):
                if args["mb_refstate"] == "default":
                    args["mb_refstate"] = config.get('tenant', 'mb_refstate')
                al_data = 'test'
            elif isinstance(args["mb_refstate"], list):
                al_data = args["mb_refstate"]
            else:
                raise UserError(
                    "Invalid measured boot reference state (intended state) provided"
                )

        # if none
        if (args["file"] is None and args["keyfile"] is None
                and args["ca_dir"] is None):
            raise UserError(
                "You must specify one of -k, -f, or --cert to specify the key/contents to be securely delivered to the agent"
            )

        if args["keyfile"] is not None:
            if args["file"] is not None or args["ca_dir"] is not None:
                raise UserError(
                    "You must specify one of -k, -f, or --cert to specify the key/contents to be securely delivered to the agent"
                )

            # read the keys in
            if isinstance(args["keyfile"], dict) and "data" in args["keyfile"]:
                if isinstance(args["keyfile"]["data"], list) and len(
                        args["keyfile"]["data"]) == 1:
                    keyfile = args["keyfile"]["data"][0]
                    if keyfile is None:
                        raise UserError("Invalid key file contents")
                    f = io.StringIO(keyfile)
                else:
                    raise UserError("Invalid key file provided")
            else:
                f = open(args["keyfile"], 'r')
            self.K = base64.b64decode(f.readline())
            self.U = base64.b64decode(f.readline())
            self.V = base64.b64decode(f.readline())
            f.close()

            # read the payload in (opt.)
            if isinstance(args["payload"], dict) and "data" in args["payload"]:
                if isinstance(args["payload"]["data"],
                              list) and len(args["payload"]["data"]) > 0:
                    self.payload = args["payload"]["data"][0]
            else:
                if args["payload"] is not None:
                    f = open(args["payload"], 'r')
                    self.payload = f.read()
                    f.close()

        if args["file"] is not None:
            if args["keyfile"] is not None or args["ca_dir"] is not None:
                raise UserError(
                    "You must specify one of -k, -f, or --cert to specify the key/contents to be securely delivered to the agent"
                )

            if isinstance(args["file"], dict) and "data" in args["file"]:
                if isinstance(args["file"]["data"],
                              list) and len(args["file"]["data"]) > 0:
                    contents = args["file"]["data"][0]
                    if contents is None:
                        raise UserError("Invalid file payload contents")
                else:
                    raise UserError("Invalid file payload provided")
            else:
                with open(args["file"], 'r') as f:
                    contents = f.read()
            ret = user_data_encrypt.encrypt(contents)
            self.K = ret['k']
            self.U = ret['u']
            self.V = ret['v']
            self.payload = ret['ciphertext']

        if args["ca_dir"] is None and args["incl_dir"] is not None:
            raise UserError(
                "--include option is only valid when used with --cert")
        if args["ca_dir"] is not None:
            if args["file"] is not None or args["keyfile"] is not None:
                raise UserError(
                    "You must specify one of -k, -f, or --cert to specify the key/contents to be securely delivered to the agent"
                )
            if args["ca_dir"] == 'default':
                args["ca_dir"] = config.CA_WORK_DIR

            if "ca_dir_pw" in args and args["ca_dir_pw"] is not None:
                ca_util.setpassword(args["ca_dir_pw"])

            if not os.path.exists(args["ca_dir"]) or not os.path.exists(
                    "%s/cacert.crt" % args["ca_dir"]):
                logger.warning(" CA directory does not exist.  Creating...")
                ca_util.cmd_init(args["ca_dir"])
            if not os.path.exists("%s/%s-private.pem" %
                                  (args["ca_dir"], self.agent_uuid)):
                ca_util.cmd_mkcert(args["ca_dir"], self.agent_uuid)

            cert_pkg, serial, subject = ca_util.cmd_certpkg(
                args["ca_dir"], self.agent_uuid)

            # support revocation
            if not os.path.exists(
                    "%s/RevocationNotifier-private.pem" % args["ca_dir"]):
                ca_util.cmd_mkcert(args["ca_dir"], "RevocationNotifier")
            rev_package, _, _ = ca_util.cmd_certpkg(args["ca_dir"],
                                                    "RevocationNotifier")

            # extract public and private keys from package
            sf = io.BytesIO(rev_package)
            with zipfile.ZipFile(sf) as zf:
                privkey = zf.read("RevocationNotifier-private.pem")
                cert = zf.read("RevocationNotifier-cert.crt")

            # put the cert of the revoker into the cert package
            sf = io.BytesIO(cert_pkg)
            with zipfile.ZipFile(sf, 'a',
                                 compression=zipfile.ZIP_STORED) as zf:
                zf.writestr('RevocationNotifier-cert.crt', cert)

                # add additional files to zip
                if args["incl_dir"] is not None:
                    if isinstance(args["incl_dir"], dict) and "data" in args[
                            "incl_dir"] and "name" in args["incl_dir"]:
                        if isinstance(args["incl_dir"]["data"],
                                      list) and isinstance(
                                          args["incl_dir"]["name"], list):
                            if len(args["incl_dir"]["data"]) != len(
                                    args["incl_dir"]["name"]):
                                raise UserError("Invalid incl_dir provided")
                            for i in range(len(args["incl_dir"]["data"])):
                                zf.writestr(
                                    os.path.basename(
                                        args["incl_dir"]["name"][i]),
                                    args["incl_dir"]["data"][i])
                    else:
                        if os.path.exists(args["incl_dir"]):
                            files = next(os.walk(args["incl_dir"]))[2]
                            for filename in files:
                                with open(
                                        "%s/%s" % (args["incl_dir"], filename),
                                        'rb') as f:
                                    zf.writestr(os.path.basename(f.name),
                                                f.read())
                        else:
                            logger.warning(
                                f'Specified include directory {args["incl_dir"]} does not exist.  Skipping...'
                            )

            cert_pkg = sf.getvalue()

            # put the private key into the data to be send to the CV
            self.revocation_key = privkey

            # encrypt up the cert package
            ret = user_data_encrypt.encrypt(cert_pkg)
            self.K = ret['k']
            self.U = ret['u']
            self.V = ret['v']
            self.metadata = {'cert_serial': serial, 'subject': subject}
            self.payload = ret['ciphertext']

        if self.payload is not None and len(self.payload) > config.getint(
                'tenant', 'max_payload_size'):
            raise UserError("Payload size %s exceeds max size %d" % (len(
                self.payload), config.getint('tenant', 'max_payload_size')))