Пример #1
0
def p11(request):
    token_path = tempfile.mkdtemp(prefix='pytest_', suffix='_pkcs11')
    os.chdir(token_path)
    os.mkdir('tokens')

    with open('softhsm2.conf', 'w') as cfg:
        cfg.write(CONFIG_DATA % token_path)
    os.environ['SOFTHSM2_CONF'] = os.path.join(token_path, 'softhsm2.conf')
    subprocess.check_call([
        SOFTHSM2_UTIL, '--init-token', '--slot', '0', '--label', 'test',
        '--pin', '1234', '--so-pin', '1234'
    ])

    try:
        p11 = _ipap11helper.P11_Helper(0, "1234", LIBSOFTHSM)
    except _ipap11helper.Error:
        pytest.fail('Failed to initialize the helper object.', pytrace=False)

    def fin():
        try:
            p11.finalize()
        except _ipap11helper.Error:
            pytest.fail('Failed to finalize the helper object.', pytrace=False)
        finally:
            del os.environ['SOFTHSM2_CONF']

    request.addfinalizer(fin)

    return p11
Пример #2
0
    def __generate_master_key(self):

        with open(paths.DNSSEC_SOFTHSM_PIN, "r") as f:
            pin = f.read()

        os.environ["SOFTHSM2_CONF"] = paths.DNSSEC_SOFTHSM2_CONF
        p11 = p11helper.P11_Helper(softhsm_slot, pin, paths.LIBSOFTHSM2_SO)
        try:
            # generate master key
            root_logger.debug("Creating master key")
            p11helper.generate_master_key(p11)

            # change tokens mod/owner
            root_logger.debug("Changing ownership of token files")
            for (root, dirs, files) in os.walk(paths.DNSSEC_TOKENS_DIR):
                for directory in dirs:
                    dir_path = os.path.join(root, directory)
                    os.chmod(dir_path, 0o770 | stat.S_ISGID)
                    os.chown(dir_path, self.ods_uid, self.named_gid)  # chown to ods:named
                for filename in files:
                    file_path = os.path.join(root, filename)
                    os.chmod(file_path, 0o770 | stat.S_ISGID)
                    os.chown(file_path, self.ods_uid, self.named_gid)  # chown to ods:named

        finally:
            p11.finalize()
Пример #3
0
    def __setup_replica_keys(self):
        keylabel = replica_keylabel_template % DNSName(self.fqdn).\
            make_absolute().canonicalize().ToASCII()

        ldap = self.admin_conn
        dn_base = DN(('cn', 'keys'), ('cn', 'sec'), ('cn', 'dns'),
                     api.env.basedn)

        with open(paths.DNSSEC_SOFTHSM_PIN, "r") as f:
            pin = f.read()

        os.environ["SOFTHSM2_CONF"] = paths.DNSSEC_SOFTHSM2_CONF
        p11 = _ipap11helper.P11_Helper(softhsm_slot, pin, paths.LIBSOFTHSM2_SO)

        try:
            # generate replica keypair
            self.logger.debug("Creating replica's key pair")
            key_id = None
            while True:
                # check if key with this ID exist in softHSM
                # id is 16 Bytes long
                key_id = "".join(
                    chr(random.randint(0, 255)) for _ in range(0, 16))
                replica_pubkey_dn = DN(('ipk11UniqueId', 'autogenerate'),
                                       dn_base)

                pub_keys = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY,
                                         label=keylabel,
                                         id=key_id)
                if pub_keys:
                    # key with id exists
                    continue

                priv_keys = p11.find_keys(_ipap11helper.KEY_CLASS_PRIVATE_KEY,
                                          label=keylabel,
                                          id=key_id)
                if not priv_keys:
                    break  # we found unique id

            public_key_handle, _privkey_handle = p11.generate_replica_key_pair(
                keylabel,
                key_id,
                pub_cka_verify=False,
                pub_cka_verify_recover=False,
                pub_cka_wrap=True,
                priv_cka_unwrap=True,
                priv_cka_sensitive=True,
                priv_cka_extractable=False)

            # export public key
            public_key_blob = p11.export_public_key(public_key_handle)

            # save key to LDAP
            replica_pubkey_objectclass = [
                'ipk11Object', 'ipk11PublicKey', 'ipaPublicKeyObject', 'top'
            ]
            kw = {
                'objectclass': replica_pubkey_objectclass,
                'ipk11UniqueId': [u'autogenerate'],
                'ipk11Label': [keylabel],
                'ipaPublicKey': [public_key_blob],
                'ipk11Id': [key_id],
                'ipk11Wrap': [True],
                'ipk11Verify': [False],
                'ipk11VerifyRecover': [False],
            }

            self.logger.debug("Storing replica public key to LDAP, %s",
                              replica_pubkey_dn)

            entry = ldap.make_entry(replica_pubkey_dn, **kw)
            ldap.add_entry(entry)
            self.logger.debug("Replica public key stored")

            self.logger.debug("Setting CKA_WRAP=False for old replica keys")
            # first create new keys, we don't want disable keys before, we
            # have new keys in softhsm and LDAP

            # get replica pub keys with CKA_WRAP=True
            replica_pub_keys = p11.find_keys(
                _ipap11helper.KEY_CLASS_PUBLIC_KEY,
                label=keylabel,
                cka_wrap=True)
            # old keys in softHSM
            for handle in replica_pub_keys:
                # don't disable wrapping for new key
                # compare IDs not handle
                if key_id != p11.get_attribute(handle, _ipap11helper.CKA_ID):
                    p11.set_attribute(handle, _ipap11helper.CKA_WRAP, False)

            # get old keys from LDAP
            search_kw = {
                'objectclass': u"ipaPublicKeyObject",
                'ipk11Label': keylabel,
                'ipk11Wrap': True,
            }
            filter = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
            entries, _truncated = ldap.find_entries(filter=filter,
                                                    base_dn=dn_base)
            for entry in entries:
                # don't disable wrapping for new key
                if entry.single_value['ipk11Id'] != key_id:
                    entry['ipk11Wrap'] = [False]
                    ldap.update_entry(entry)

        finally:
            p11.finalize()

        # change tokens mod/owner
        self.logger.debug("Changing ownership of token files")
        for (root, dirs, files) in os.walk(paths.DNSSEC_TOKENS_DIR):
            for directory in dirs:
                dir_path = os.path.join(root, directory)
                os.chmod(dir_path, 0o770 | stat.S_ISGID)
                # chown to ods:named
                os.chown(dir_path, self.ods_uid, self.named_gid)
            for filename in files:
                file_path = os.path.join(root, filename)
                os.chmod(file_path, 0o770 | stat.S_ISGID)
                # chown to ods:named
                os.chown(file_path, self.ods_uid, self.named_gid)
Пример #4
0
 def __init__(self, library, slot, pin):
     self.cache_replica_pubkeys = None
     self.p11 = _ipap11helper.P11_Helper(slot, pin, library)
     self.log = logging.getLogger()