Exemplo n.º 1
0
    def execute(self, *keys, **options):
        # the server must be the local host
        if keys[-2] != api.env.host:
            raise errors.ValidationError(name='cn',
                                         error=_("must be \"%s\"") %
                                         api.env.host)

        # the server entry must exist
        try:
            self.obj.get_dn_if_exists(*keys[:-1])
        except errors.NotFound:
            raise self.obj.handle_not_found(keys[-2])

        # the user must have the Replication Administrators privilege
        privilege = u'Replication Administrators'
        privilege_dn = self.api.Object.privilege.get_dn(privilege)
        ldap = self.obj.backend
        filter = ldap.make_filter(
            {
                'krbprincipalname': context.principal,  # pylint: disable=no-member
                'memberof': privilege_dn
            },
            rules=ldap.MATCH_ALL)
        try:
            ldap.find_entries(base_dn=self.api.env.basedn, filter=filter)
        except errors.NotFound:
            raise errors.ACIError(
                info=_("not allowed to perform server connection check"))

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        bus = dbus.SystemBus()
        obj = bus.get_object('org.freeipa.server',
                             '/',
                             follow_name_owner_changes=True)
        server = dbus.Interface(obj, 'org.freeipa.server')

        ret, stdout, _stderr = server.conncheck(keys[-1])

        result = dict(
            result=(ret == 0),
            value=keys[-2],
        )

        for line in stdout.splitlines():
            messages.add_message(options['version'], result,
                                 messages.ExternalCommandOutput(line=line))

        return result
Exemplo n.º 2
0
    def remove_server_ns_records(self, fqdn):
        """
        Remove all NS records pointing to this server
        """
        ldap = api.Backend.ldap2
        ns_rdata = normalize_zone(fqdn)

        # find all NS records pointing to this server
        search_kw = {}
        search_kw['nsrecord'] = ns_rdata
        attr_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
        attributes = ['idnsname', 'objectclass']
        dn = DN(api.env.container_dns, api.env.basedn)

        entries, truncated = ldap.find_entries(attr_filter, attributes, base_dn=dn)

        # remove records
        if entries:
            root_logger.debug("Removing all NS records pointing to %s:", ns_rdata)

        for entry in entries:
            if 'idnszone' in entry['objectclass']:
                # zone record
                zone = entry.single_value['idnsname']
                root_logger.debug("zone record %s", zone)
                del_ns_rr(zone, u'@', ns_rdata)
            else:
                zone = entry.dn[1].value  # get zone from DN
                record = entry.single_value['idnsname']
                root_logger.debug("record %s in zone %s", record, zone)
                del_ns_rr(zone, record, ns_rdata)
Exemplo n.º 3
0
    def remove_server_ns_records(self, fqdn):
        """
        Remove all NS records pointing to this server
        """
        ldap = self.api.Backend.ldap2
        ns_rdata = normalize_zone(fqdn)

        # find all NS records pointing to this server
        search_kw = {}
        search_kw['nsrecord'] = ns_rdata
        attr_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
        attributes = ['idnsname', 'objectclass']
        dn = DN(self.api.env.container_dns, self.api.env.basedn)

        entries, _truncated = ldap.find_entries(attr_filter,
                                                attributes,
                                                base_dn=dn)

        # remove records
        if entries:
            root_logger.debug("Removing all NS records pointing to %s:",
                              ns_rdata)

        for entry in entries:
            if 'idnszone' in entry['objectclass']:
                # zone record
                zone = entry.single_value['idnsname']
                root_logger.debug("zone record %s", zone)
                del_ns_rr(zone, u'@', ns_rdata, api=self.api)
            else:
                zone = entry.dn[1].value  # get zone from DN
                record = entry.single_value['idnsname']
                root_logger.debug("record %s in zone %s", record, zone)
                del_ns_rr(zone, record, ns_rdata, api=self.api)
Exemplo n.º 4
0
    def execute(self, *keys, **options):
        # the server must be the local host
        if keys[-2] != api.env.host:
            raise errors.ValidationError(
                name='cn', error=_("must be \"%s\"") % api.env.host)

        # the server entry must exist
        try:
            self.obj.get_dn_if_exists(*keys[:-1])
        except errors.NotFound:
            self.obj.handle_not_found(keys[-2])

        # the user must have the Replication Administrators privilege
        privilege = u'Replication Administrators'
        privilege_dn = self.api.Object.privilege.get_dn(privilege)
        ldap = self.obj.backend
        filter = ldap.make_filter({
            'krbprincipalname': context.principal,  # pylint: disable=no-member
            'memberof': privilege_dn},
            rules=ldap.MATCH_ALL)
        try:
            ldap.find_entries(base_dn=self.api.env.basedn, filter=filter)
        except errors.NotFound:
            raise errors.ACIError(
                info=_("not allowed to perform server connection check"))

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        bus = dbus.SystemBus()
        obj = bus.get_object('org.freeipa.server', '/',
                             follow_name_owner_changes=True)
        server = dbus.Interface(obj, 'org.freeipa.server')

        ret, stdout, _stderr = server.conncheck(keys[-1])

        result = dict(
            result=(ret == 0),
            value=keys[-2],
        )

        for line in stdout.splitlines():
            messages.add_message(options['version'],
                                 result,
                                 messages.ExternalCommandOutput(line=line))

        return result
Exemplo n.º 5
0
 def remove_replica_public_keys(self, replica_fqdn):
     ldap = api.Backend.ldap2
     dn_base = DN(("cn", "keys"), ("cn", "sec"), ("cn", "dns"), api.env.basedn)
     keylabel = replica_keylabel_template % DNSName(replica_fqdn).make_absolute().canonicalize().ToASCII()
     # 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:
         ldap.delete_entry(entry)
Exemplo n.º 6
0
 def remove_replica_public_keys(self, replica_fqdn):
     ldap = api.Backend.ldap2
     dn_base = DN(('cn', 'keys'), ('cn', 'sec'), ('cn', 'dns'), api.env.basedn)
     keylabel = replica_keylabel_template % DNSName(replica_fqdn).\
         make_absolute().canonicalize().ToASCII()
     # 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:
         ldap.delete_entry(entry)
Exemplo n.º 7
0
 def remove_replica_public_keys(self, replica_fqdn):
     ldap = api.Backend.ldap2
     dn_base = DN(('cn', 'keys'), ('cn', 'sec'), ('cn', 'dns'), api.env.basedn)
     keylabel = replica_keylabel_template % DNSName(replica_fqdn).\
         make_absolute().canonicalize().ToASCII()
     # 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:
         ldap.delete_entry(entry)
Exemplo n.º 8
0
    def __setup_replica_keys(self):
        keylabel = replica_keylabel_template % DNSName(self.fqdn).\
            make_absolute().canonicalize().ToASCII()

        ldap = api.Backend.ldap2
        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_DNSSEC_TOKEN_LABEL, pin,
                                       paths.LIBSOFTHSM2_SO)

        try:
            # generate replica keypair
            logger.debug("Creating replica's key pair")
            key_id = None
            while True:
                # check if key with this ID exist in softHSM
                key_id = _ipap11helper.gen_key_id()
                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],
            }

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

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

            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
        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)
Exemplo n.º 9
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, private_key_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)