def __init__(self, server_address, RequestHandlerClass, agent_uuid):
        """Constructor overridden to provide ability to pass configuration arguments to the server"""
        secdir = secure_mount.mount()
        keyname = "%s/%s" % (secdir, config.get('cloud_agent', 'rsa_keyname'))

        # read or generate the key depending on configuration
        if os.path.isfile(keyname):
            # read in private key
            logger.debug("Using existing key in %s" % keyname)
            f = open(keyname, "rb")
            rsa_key = crypto.rsa_import_privkey(f.read())
        else:
            logger.debug("key not found, generating a new one")
            rsa_key = crypto.rsa_generate(2048)
            with open(keyname, "wb") as f:
                f.write(crypto.rsa_export_privkey(rsa_key))

        self.rsaprivatekey = rsa_key
        self.rsapublickey_exportable = crypto.rsa_export_pubkey(
            self.rsaprivatekey)

        #attempt to get a U value from the TPM NVRAM
        nvram_u = tpm.read_key_nvram()
        if nvram_u is not None:
            logger.info("Existing U loaded from TPM NVRAM")
            self.add_U(nvram_u)
        http.server.HTTPServer.__init__(self, server_address,
                                        RequestHandlerClass)
        self.enc_keyname = config.get('cloud_agent', 'enc_keyname')
        self.agent_uuid = agent_uuid
示例#2
0
    def test_rsa_sign(self):
        message = b"a secret message!"
        private = rsa_generate(2048)
        public_key = get_public_key(private)
        signature = rsa_sign(private, message)
        self.assertTrue(rsa_verify(public_key, message, signature))

        message = b"another message!"
        self.assertFalse(rsa_verify(public_key, message, signature))
示例#3
0
 def test_rsa(self):
     message = b"a secret message!"
     private = rsa_generate(2048)
     pubkeypem = rsa_export_pubkey(private)
     pubkey = rsa_import_pubkey(pubkeypem)
     keypem = rsa_export_privkey(private)
     key = rsa_import_privkey(keypem)
     ciphertext = rsa_encrypt(pubkey, message)
     plain = rsa_decrypt(key, ciphertext)
     self.assertEqual(plain, message)
示例#4
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!")
示例#5
0
    def __init__(self, server_address, RequestHandlerClass, agent_uuid):
        """Constructor overridden to provide ability to pass configuration arguments to the server"""
        secdir = secure_mount.mount()
        keyname = os.path.join(secdir, config.get('cloud_agent',
                                                  'rsa_keyname'))
        certname = os.path.join(secdir, config.get('cloud_agent', 'mtls_cert'))
        # read or generate the key depending on configuration
        if os.path.isfile(keyname):
            # read in private key
            logger.debug("Using existing key in %s", keyname)
            f = open(keyname, "rb")
            rsa_key = crypto.rsa_import_privkey(f.read())
        else:
            logger.debug("key not found, generating a new one")
            rsa_key = crypto.rsa_generate(2048)
            with open(keyname, "wb") as f:
                f.write(crypto.rsa_export_privkey(rsa_key))

        self.rsakey_path = keyname
        self.rsaprivatekey = rsa_key
        self.rsapublickey_exportable = crypto.rsa_export_pubkey(
            self.rsaprivatekey)

        if os.path.isfile(certname):
            logger.debug("Using existing mTLS cert in %s", certname)
            with open(certname, "rb") as f:
                mtls_cert = x509.load_pem_x509_certificate(f.read())
        else:
            logger.debug("No mTLS certificate found generating a new one")
            with open(certname, "wb") as f:
                # By default generate a TLS certificate valid for 5 years
                valid_util = datetime.datetime.utcnow() + datetime.timedelta(
                    days=(360 * 5))
                mtls_cert = crypto.generate_selfsigned_cert(
                    agent_uuid, rsa_key, valid_util)
                f.write(mtls_cert.public_bytes(serialization.Encoding.PEM))

        self.mtls_cert_path = certname
        self.mtls_cert = mtls_cert

        # attempt to get a U value from the TPM NVRAM
        nvram_u = tpm_instance.read_key_nvram()
        if nvram_u is not None:
            logger.info("Existing U loaded from TPM NVRAM")
            self.add_U(nvram_u)
        http.server.HTTPServer.__init__(self, server_address,
                                        RequestHandlerClass)
        self.enc_keyname = config.get('cloud_agent', 'enc_keyname')
        self.agent_uuid = agent_uuid
示例#6
0
    def __init__(self, server_address, RequestHandlerClass, agent_uuid,
                 contact_ip, ima_log_file, tpm_log_file_data):
        """Constructor overridden to provide ability to pass configuration arguments to the server"""
        # Find the locations for the U/V transport and mTLS key and certificate.
        # They are either relative to secdir (/var/lib/keylime/secure) or absolute paths.
        secdir = secure_mount.mount()
        keyname = config.get("cloud_agent", "rsa_keyname")
        if not os.path.isabs(keyname):
            keyname = os.path.join(secdir, keyname)

        # read or generate the key depending on configuration
        if os.path.isfile(keyname):
            # read in private key
            logger.info("Using existing key in %s", keyname)
            with open(keyname, "rb") as f:
                rsa_key = crypto.rsa_import_privkey(f.read())
        else:
            logger.info(
                "Key for U/V transport and mTLS certificate not found, generating a new one"
            )
            rsa_key = crypto.rsa_generate(2048)
            with open(keyname, "wb") as f:
                f.write(crypto.rsa_export_privkey(rsa_key))

        self.rsakey_path = keyname
        self.rsaprivatekey = rsa_key
        self.rsapublickey_exportable = crypto.rsa_export_pubkey(
            self.rsaprivatekey)

        self.mtls_cert_enabled = config.getboolean("cloud_agent",
                                                   "mtls_cert_enabled",
                                                   fallback=False)
        if self.mtls_cert_enabled:
            certname = config.get("cloud_agent", "mtls_cert")

            if not os.path.isabs(certname):
                certname = os.path.join(secdir, certname)

            if os.path.isfile(certname):
                logger.info("Using existing mTLS cert in %s", certname)
                with open(certname, "rb") as f:
                    mtls_cert = x509.load_pem_x509_certificate(
                        f.read(), backend=default_backend())
            else:
                logger.info("No mTLS certificate found, generating a new one")
                agent_ips = [server_address[0]]
                if contact_ip is not None:
                    agent_ips.append(contact_ip)
                with open(certname, "wb") as f:
                    # By default generate a TLS certificate valid for 5 years
                    valid_util = datetime.datetime.utcnow(
                    ) + datetime.timedelta(days=(360 * 5))
                    mtls_cert = crypto.generate_selfsigned_cert(
                        agent_uuid, rsa_key, valid_util, agent_ips)
                    f.write(mtls_cert.public_bytes(serialization.Encoding.PEM))

            self.mtls_cert_path = certname
            self.mtls_cert = mtls_cert
        else:
            self.mtls_cert_path = None
            self.mtls_cert = None
            logger.info(
                "WARNING: mTLS disabled, Tenant and Verifier will reach out to agent via HTTP"
            )

        self.revocation_cert_path = config.get("cloud_agent",
                                               "revocation_cert")
        if self.revocation_cert_path == "default":
            self.revocation_cert_path = os.path.join(
                secdir, "unzipped/RevocationNotifier-cert.crt")
        elif self.revocation_cert_path[0] != "/":
            # if it is a relative, convert to absolute in work_dir
            self.revocation_cert_path = os.path.abspath(
                os.path.join(config.WORK_DIR, self.revocation_cert_path))

        # attempt to get a U value from the TPM NVRAM
        nvram_u = tpm_instance.read_key_nvram()
        if nvram_u is not None:
            logger.info("Existing U loaded from TPM NVRAM")
            self.add_U(nvram_u)
        http.server.HTTPServer.__init__(self, server_address,
                                        RequestHandlerClass)
        self.enc_keyname = config.get("cloud_agent", "enc_keyname")
        self.agent_uuid = agent_uuid
        self.ima_log_file = ima_log_file
        self.tpm_log_file_data = tpm_log_file_data