Exemple #1
0
    def test_ipahealthcheck_hidden_replica(self):
        """Ensure that ipa-healthcheck runs successfully on all members
        of an IPA cluster that includes a hidden replica.
        """
        os_version = (tasks.get_platform(self.master),
                      tasks.get_platform_version(self.master))
        pki_version = tasks.get_pki_version(self.master)

        # verify state
        self._check_config([self.master], [self.replicas[0]])
        # A DNA range is needed on the replica for ipa-healthcheck to work.
        # Create a user so that the replica gets a range.
        tasks.user_add(self.replicas[0], 'testuser')
        tasks.user_del(self.replicas[0], 'testuser')
        for srv in (self.master, self.replicas[0]):
            returncode, _unused = run_healthcheck(srv, failures_only=True)
            pki_too_old = \
                (os_version[0] == 'fedora'
                    and pki_version < tasks.parse_version('11.1.0'))\
                or (os_version[0] == 'rhel'
                    and os_version[1][0] == 8
                    and pki_version < tasks.parse_version('10.12.0'))\
                or (os_version[0] == 'rhel'
                    and os_version[1][0] == 9
                    and pki_version < tasks.parse_version('11.0.4'))
            with xfail_context(pki_too_old,
                               'https://pagure.io/freeipa/issue/8582'):
                assert returncode == 0
Exemple #2
0
 def test_auth_keycloak_idp(self):
     """
     Test case to check that OAuth 2.0 Device
     Authorization Grant is working as
     expected for user configured with external idp.
     """
     create_quarkus.setup_keycloakserver(self.client)
     time.sleep(60)
     create_quarkus.setup_keycloak_client(self.client)
     tasks.kinit_admin(self.master)
     cmd = ["ipa", "idp-add", "keycloakidp", "--provider=keycloak",
            "--client-id=ipa_oidc_client", "--org=master",
            "--base-url={0}:8443/auth".format(self.client.hostname)]
     self.master.run_command(cmd, stdin_text="{0}\n{0}".format(
         self.client.config.admin_password))
     tasks.user_add(self.master, 'keycloakuser',
                    extra_args=["--user-auth-type=idp",
                                "[email protected]",
                                "--idp=keycloakidp"]
                    )
     list_user = self.master.run_command(
         ["ipa", "user-find", "[email protected]"]
     )
     assert "keycloakuser" in list_user.stdout_text
     list_by_idp = self.master.run_command(["ipa", "user-find",
                                            "--idp=keycloakidp"]
                                           )
     assert "keycloakuser" in list_by_idp.stdout_text
     list_by_user = self.master.run_command(
         ["ipa", "user-find", "[email protected]", "--all"]
     )
     assert "keycloakidp" in list_by_user.stdout_text
     tasks.clear_sssd_cache(self.master)
     kinit_idp(self.master, 'keycloakuser', keycloak_server=self.client)
Exemple #3
0
 def test_EPN_smoketest_2(self, cleanupusers):
     """Add a user without password.
        Add a user whose password expires within the default time range.
        Check --dry-run output.
     """
     tasks.user_add(self.master, "testuser0")
     tasks.user_add(
         self.master,
         "testuser1",
         password="******",
         extra_args=[
             "--password-expiration",
             datetime_to_generalized_time(
                 datetime.datetime.utcnow() + datetime.timedelta(days=7)
             ),
         ],
     )
     (stdout_text_client, unused, _unused) = self._check_epn_output(
         self.clients[0], dry_run=True
     )
     (stdout_text_master, unused, _unused) = self._check_epn_output(
         self.master, dry_run=True
     )
     assert stdout_text_master == stdout_text_client
     assert "testuser0" not in stdout_text_client
     assert "testuser1" in stdout_text_client
Exemple #4
0
    def test_multiple_user_certificates(self):
        """Test that a user may be issued multiple certificates"""
        ldap = self.master.ldap_connect()

        user = '******'

        tasks.kinit_admin(self.master)
        tasks.user_add(self.master, user)

        for id in (0, 1):
            csr_file = f'{id}.csr'
            key_file = f'{id}.key'
            cert_file = f'{id}.crt'
            openssl_cmd = [
                'openssl', 'req', '-newkey', 'rsa:2048', '-keyout', key_file,
                '-nodes', '-out', csr_file, '-subj', '/CN=' + user]
            self.master.run_command(openssl_cmd)

            cmd_args = ['ipa', 'cert-request', '--principal', user,
                        '--certificate-out', cert_file, csr_file]
            self.master.run_command(cmd_args)

        # easier to count by pulling the LDAP entry
        entry = ldap.get_entry(DN(('uid', user), ('cn', 'users'),
                               ('cn', 'accounts'), self.master.domain.basedn))

        assert len(entry.get('usercertificate')) == 2
Exemple #5
0
    def test_subid_useradmin(self):
        tasks.kinit_admin(self.master)

        uid_useradmin = "testuser_usermgr_mgr1"
        role = "User Administrator"
        uid = "testuser_usermgr_user1"
        password = "******"

        # create user administrator
        tasks.create_active_user(self.master, uid_useradmin, password=password)
        # add user to user admin group
        tasks.kinit_admin(self.master)
        self.master.run_command(
            ["ipa", "role-add-member", role, f"--users={uid_useradmin}"], )
        # kinit as user admin
        tasks.kinit_user(self.master, uid_useradmin, password)

        # create new user as user admin
        tasks.user_add(self.master, uid)
        # assign new subid to user (with useradmin credentials)
        self.subid_generate(uid)

        # test that user admin can preserve and delete users with subids
        self.master.run_command(["ipa", "user-del", "--preserve", uid])
        # XXX does not work, see subordinate-ids.md
        # subid should still exist
        # self.assert_subid(uid, match=True)
        # final delete should remove the user and subid
        self.master.run_command(["ipa", "user-del", uid])
        self.assert_subid(uid, match=False)
Exemple #6
0
 def test_ipahealthcheck_hidden_replica(self):
     """Ensure that ipa-healthcheck runs successfully on all members
     of an IPA cluster that includes a hidden replica.
     """
     # verify state
     self._check_config([self.master], [self.replicas[0]])
     # A DNA range is needed on the replica for ipa-healthcheck to work.
     # Create a user so that the replica gets a range.
     tasks.user_add(self.replicas[0], 'testuser')
     tasks.user_del(self.replicas[0], 'testuser')
     for srv in (self.master, self.replicas[0]):
         returncode, _unused = run_healthcheck(srv, failures_only=True)
         assert returncode == 0
Exemple #7
0
    def tset_subid_auto_assign(self):
        tasks.kinit_admin(self.master)
        uid = "testuser_autoassign_user1"

        self.master.run_command(
            ["ipa", "config-mod", "--user-default-subid=true"])

        try:
            tasks.user_add(self.master, uid)
            self.assert_subid(uid, match=True)
        finally:
            self.master.run_command(
                ["ipa", "config-mod", "--user-default-subid=false"])
Exemple #8
0
    def install(cls, mh):
        super(TestIDViews, cls).install(mh)
        master = cls.master
        client = cls.clients[0]
        tasks.kinit_admin(master)

        tasks.user_add(master,
                       cls.user1,
                       first='Test1',
                       extra_args=[
                           '--uid',
                           str(cls.user1_uid),
                           '--gidnumber',
                           str(cls.user1_gid),
                       ])
        tasks.user_add(master,
                       cls.user2,
                       first='Test2',
                       extra_args=[
                           '--uid',
                           str(cls.user2_uid),
                           '--gidnumber',
                           str(cls.user2_gid),
                       ])
        tasks.group_add(master,
                        cls.group1,
                        extra_args=['--gid', str(cls.group1_gid)])

        master.run_command(['ipa', 'idview-add', cls.idview])

        # add overrides for user1 and its default user group
        master.run_command([
            'ipa', 'idoverrideuser-add', cls.idview, cls.user1, '--uid',
            str(cls.user1_uid_override), '--gid',
            str(cls.user1_gid_override), '--homedir',
            '/special-home/{}'.format(cls.user1), '--shell', '/bin/special'
        ])
        master.run_command([
            'ipa',
            'idoverridegroup-add',
            cls.idview,
            cls.group1,
            '--gid',
            str(cls.group1_gid_override),
        ])

        # ID view overrides don't work on IPA masters
        master.run_command(
            ['ipa', 'idview-apply', cls.idview, '--hosts', client.hostname])
        # finally restart SSSD to materialize idviews
        client.run_command(['systemctl', 'restart', 'sssd.service'])
Exemple #9
0
    def install(cls, mh):
        super(TestSSSDAuthCache, cls).install(mh)

        cls.ad = cls.ads[0]  # pylint: disable=no-member

        tasks.install_adtrust(cls.master)
        tasks.configure_dns_for_trust(cls.master, cls.ad)
        tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name)

        cls.users['ad']['name'] = cls.users['ad']['name_tmpl'].format(
            domain=cls.ad.domain.name)
        tasks.user_add(cls.master, cls.intermed_user)
        tasks.create_active_user(cls.master, cls.ipa_user,
                                 cls.ipa_user_password)
Exemple #10
0
    def test_ipa_subid_script(self):
        tasks.kinit_admin(self.master)

        tool = os.path.join(paths.LIBEXEC_IPA_DIR, "ipa-subids")
        users = []
        for i in range(1, 11):
            uid = f"testuser_script{i}"
            users.append(uid)
            tasks.user_add(self.master, uid)
            self.assert_subid(uid, match=False)

        cmd = [tool, "--verbose", "--group", "ipausers"]
        self.master.run_command(cmd)

        for uid in users:
            self.assert_subid(uid, match=True)
Exemple #11
0
    def install(cls, mh):
        super(TestSSSDWithAdTrust, cls).install(mh)

        cls.ad = cls.ads[0]

        tasks.install_adtrust(cls.master)
        tasks.configure_dns_for_trust(cls.master, cls.ad)
        tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name)

        cls.users['ad']['name'] = cls.users['ad']['name_tmpl'].format(
            domain=cls.ad.domain.name)
        cls.users['ad']['group'] = cls.users['ad']['group_tmpl'].format(
            domain=cls.ad.domain.name)
        tasks.user_add(cls.master, cls.intermed_user)
        tasks.create_active_user(cls.master, cls.ipa_user,
                                 cls.ipa_user_password)
Exemple #12
0
    def test_ipa_healthcheck_dna_plugin_returns_warning_pagure_issue_60(self):
        """
        This testcase checks that the status for IPADNARangeCheck on replica
        changes from WARNING to SUCCESS when user is added on the replica
        as the DNA range is set.
        Issue: freeipa/freeipa-healthcheck#60
        """
        returncode, data = run_healthcheck(
            self.master,
            "ipahealthcheck.ipa.dna",
            "IPADNARangeCheck",
        )
        assert returncode == 0
        for check in data:
            assert check["result"] == "SUCCESS"
        # Install ipa-healthcheck rpm on replica
        tasks.install_packages(self.replicas[0], HEALTHCHECK_PKG)
        returncode, data = run_healthcheck(
            self.replicas[0],
            "ipahealthcheck.ipa.dna",
            "IPADNARangeCheck",
        )
        assert returncode == 1
        for check in data:
            assert check["result"] == "WARNING"
            assert (
                check["kw"]["msg"] == "No DNA range defined. If no masters "
                "define a range then users and groups cannot be created.")

        # Now kinit as admin and add a user on replica which will create a
        # DNA configuration.
        tasks.kinit_admin(self.replicas[0])
        tasks.user_add(
            self.replicas[0],
            'ipauser1',
            first='Test',
            last='User',
        )
        # Now run the ipa-healthcheck command again
        returncode, data = run_healthcheck(
            self.replicas[0],
            "ipahealthcheck.ipa.dna",
            "IPADNARangeCheck",
        )
        assert returncode == 0
        for check in data:
            assert check["result"] == "SUCCESS"
Exemple #13
0
    def install(cls, mh):
        super(TestSSSDWithAdTrust, cls).install(mh)

        cls.ad = cls.ads[0]

        tasks.install_adtrust(cls.master)
        tasks.configure_dns_for_trust(cls.master, cls.ad)
        tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name)

        cls.users['ad']['name'] = cls.users['ad']['name_tmpl'].format(
            domain=cls.ad.domain.name)

        # Regression tests for cached_auth_timeout option
        # https://bugzilla.redhat.com/show_bug.cgi?id=1685581
        tasks.user_add(cls.master, cls.intermed_user)
        tasks.create_active_user(cls.master, cls.ipa_user,
                                 cls.ipa_user_password)
Exemple #14
0
    def install(cls, mh):
        super(TestIDViews, cls).install(mh)
        master = cls.master
        client = cls.clients[0]
        tasks.kinit_admin(master)

        tasks.user_add(
            master, cls.user1, first='Test1',
            extra_args=[
                '--uid', str(cls.user1_uid),
                '--gidnumber', str(cls.user1_gid),
            ]
        )
        tasks.user_add(
            master, cls.user2, first='Test2',
            extra_args=[
                '--uid', str(cls.user2_uid),
                '--gidnumber', str(cls.user2_gid),
            ]
        )
        tasks.group_add(
            master, cls.group1, extra_args=['--gid', str(cls.group1_gid)]
        )

        master.run_command(['ipa', 'idview-add', cls.idview])

        # add overrides for user1 and its default user group
        master.run_command([
            'ipa', 'idoverrideuser-add', cls.idview, cls.user1,
            '--uid', str(cls.user1_uid_override),
            '--gid', str(cls.user1_gid_override),
            '--homedir', '/special-home/{}'.format(cls.user1),
            '--shell', '/bin/special'
        ])
        master.run_command([
            'ipa', 'idoverridegroup-add', cls.idview, cls.group1,
            '--gid', str(cls.group1_gid_override),
        ])

        # ID view overrides don't work on IPA masters
        master.run_command([
            'ipa', 'idview-apply', cls.idview,
            '--hosts', client.hostname
        ])
        # finally restart SSSD to materialize idviews
        client.run_command(['systemctl', 'restart', 'sssd.service'])
Exemple #15
0
 def test_auth_keycloak_idp(self):
     keycloak_srv = self.replicas[0]
     create_quarkus.setup_keycloakserver(keycloak_srv)
     time.sleep(60)
     create_quarkus.setup_keycloak_client(keycloak_srv)
     tasks.kinit_admin(self.master)
     cmd = ["ipa", "idp-add", "keycloak", "--provider=keycloak",
            "--client-id=ipa_oidc_client", "--org=master",
            "--base-url={0}:8443/auth".format(keycloak_srv.hostname)]
     self.master.run_command(cmd, stdin_text="{0}\n{0}".format(
         keycloak_srv.config.admin_password))
     tasks.user_add(self.master, 'keycloakuser',
                    extra_args=["--user-auth-type=idp",
                                "[email protected]",
                                "--idp=keycloak"]
                    )
     tasks.clear_sssd_cache(self.master)
     kinit_idp(self.master, 'keycloakuser', keycloak_srv)
Exemple #16
0
    def test_ext_grp_with_ldap(self):
        """User and group with same name should not break reading AD user data.

        Regression test for https://pagure.io/SSSD/sssd/issue/4073

        When aduser is added in extrnal group and this group is added
        in group with same name of nonprivate ipa user and possix id, then
        lookup of aduser and group should be successful when cache is empty.
        """
        cmd = self.master.run_command(['sssd', '--version'])
        sssd_version = platform_tasks.parse_ipa_version(
            cmd.stdout_text.strip())
        if sssd_version <= platform_tasks.parse_ipa_version('2.2.2'):
            pytest.skip("Fix for https://pagure.io/SSSD/sssd/issue/4073 "
                        "unavailable with sssd-2.2.2")
        client = self.clients[0]
        user = '******'
        userid = '100996'
        ext_group = 'ext-ipatest'
        tasks.kinit_admin(self.master)
        # add user with same uid and gidnumber
        tasks.user_add(
            self.master,
            user,
            extra_args=['--noprivate', '--uid', userid, '--gidnumber', userid])
        # add group with same as user_name and user_id.
        tasks.group_add(self.master, user, extra_args=['--gid', userid])
        tasks.group_add(self.master, ext_group, extra_args=['--external'])
        self.master.run_command(
            ['ipa', 'group-add-member', '--group', ext_group, user])
        self.master.run_command([
            'ipa', '-n', 'group-add-member', '--external',
            self.users['ad']['name'], ext_group
        ])
        tasks.clear_sssd_cache(self.master)
        tasks.clear_sssd_cache(client)
        try:
            result = client.run_command(['id', self.users['ad']['name']])
            assert '{uid}({name})'.format(uid=userid,
                                          name=user) in result.stdout_text
        finally:
            self.master.run_command(['ipa', 'user-del', user])
            self.master.run_command(['ipa', 'group-del', user, ext_group])
Exemple #17
0
    def test_idp_backup_restore(self):
        """
        Test case to check that after restore data is retrieved
        with related idp configuration.
        """
        tasks.kinit_admin(self.master)
        user = "******"
        cmd = ["ipa", "idp-add", "testidp", "--provider=keycloak",
               "--client-id=ipa_oidc_client", "--org=master",
               "--base-url={0}:8443/auth".format(self.client.hostname)]
        self.master.run_command(cmd, stdin_text="{0}\n{0}".format(
            self.client.config.admin_password))

        tasks.user_add(self.master, user,
                       extra_args=["--user-auth-type=idp",
                                   "[email protected]",
                                   "--idp=testidp"]
                       )

        backup_path = tasks.get_backup_dir(self.master)
        # change data after backup
        self.master.run_command(['ipa', 'user-del', user])
        self.master.run_command(['ipa', 'idp-del', 'testidp'])
        dirman_password = self.master.config.dirman_password
        self.master.run_command(['ipa-restore', backup_path],
                                stdin_text=dirman_password + '\nyes')
        try:
            list_user = self.master.run_command(
                ['ipa', 'user-show', 'backupuser', '--all']
            ).stdout_text
            assert "External IdP configuration: testidp" in list_user
            assert "User authentication types: idp" in list_user
            assert ("External IdP user identifier: "
                    "*****@*****.**") in list_user
            list_idp = self.master.run_command(['ipa', 'idp-find', 'testidp'])
            assert "testidp" in list_idp.stdout_text
            kinit_idp(self.master, user, self.client)
        finally:
            tasks.kdestroy_all(self.master)
            tasks.kinit_admin(self.master)
            self.master.run_command(["rm", "-rf", backup_path])
            self.master.run_command(["ipa", "idp-del", "testidp"])
Exemple #18
0
    def test_EPN_smoketest_3(self):
        """Add a bunch of users with incrementally expiring passwords
           (one per day). Check --dry-run output.
        """

        users = {}
        userbase_str = "user"

        for i in range(30):
            uid = userbase_str + str(i)
            users[i] = dict(
                uid=uid,
                days=i,
                krbpasswordexpiration=datetime_to_generalized_time(
                    datetime.datetime.utcnow() + datetime.timedelta(days=i)
                ),
            )

        for key in users:
            tasks.user_add(
                self.master,
                users[key]["uid"],
                extra_args=[
                    "--password-expiration",
                    users[key]["krbpasswordexpiration"],
                ],
                password=None,
            )

        (stdout_text_client, unused, _unused) = self._check_epn_output(
            self.clients[0], dry_run=True
        )
        (stdout_text_master, unused, _unused) = self._check_epn_output(
            self.master, dry_run=True
        )
        assert stdout_text_master == stdout_text_client
        user_lst = []
        for user in json.loads(stdout_text_master):
            user_lst.append(user["uid"])
        expected_users = ["user1", "user3", "user7", "user14", "user28"]
        assert sorted(user_lst) == sorted(expected_users)
    def test_change_user_pwd_history_issue7181(self, pwpolicy_global):
        """
        Test that password history for a normal IPA user is honored.
        """
        user = '******'
        original_passwd = 'Secret123'
        new_passwd = 'userPasswd123'

        master = self.master

        tasks.user_add(master, user, password=original_passwd)

        tasks.ldappasswd_user_change(user, original_passwd, new_passwd, master)
        tasks.ldappasswd_user_change(user, new_passwd, original_passwd, master)
        try:
            tasks.ldappasswd_user_change(user, original_passwd, new_passwd,
                                         master)
        except CalledProcessError as e:
            if e.returncode != 1:
                raise
        else:
            pytest.fail("Password change violating policy did not fail")
Exemple #20
0
    def install(cls, mh):
        super(TestMemberManager, cls).install(mh)
        master = cls.master

        tasks.create_active_user(master, USER_MM, PASSWORD)
        tasks.create_active_user(master, USER_INDIRECT, PASSWORD)
        tasks.create_active_user(master, USER1, PASSWORD)

        tasks.kinit_admin(master)
        tasks.group_add(master, GROUP_INDIRECT)
        master.run_command([
            'ipa', 'group-add-member', GROUP_INDIRECT, '--users', USER_INDIRECT
        ])

        tasks.user_add(master, USER2)
        tasks.group_add(master, GROUP1)
        tasks.group_add(master, GROUP2)
        master.run_command(['ipa', 'hostgroup-add', HOSTGROUP1])

        # make mmuser a member manager for group and hostgroup
        master.run_command([
            'ipa', 'group-add-member-manager', GROUP1,
            '--users', USER_MM
        ])
        master.run_command([
            'ipa', 'hostgroup-add-member-manager', HOSTGROUP1,
            '--users', USER_MM
        ])
        # make indirect group member manager for group and hostgroup
        master.run_command([
            'ipa', 'group-add-member-manager', GROUP1,
            '--groups', GROUP_INDIRECT
        ])
        master.run_command([
            'ipa', 'hostgroup-add-member-manager', HOSTGROUP1,
            '--groups', GROUP_INDIRECT
        ])
        tasks.kdestroy_all(master)
    def test_full_backup_and_restore_with_replica(self, cert_sign_request):
        # check prerequisites
        self.check_replication_success(self.master)
        self.check_replication_success(self.replica1)

        self.master.run_command(
            ['ipa', 'service-add', 'TEST/' + self.master.hostname])

        tasks.user_add(self.master, 'test1_master')
        tasks.user_add(self.replica1, 'test1_replica')

        with restore_checker(self.master):
            backup_path = backup(self.master)

            # change data after backup
            self.master.run_command(['ipa', 'user-del', 'test1_master'])
            self.replica1.run_command(['ipa', 'user-del', 'test1_replica'])
            tasks.user_add(self.master, 'test2_master')
            tasks.user_add(self.replica1, 'test2_replica')

            # simulate master crash
            self.master.run_command(['ipactl', 'stop'])
            tasks.uninstall_master(self.master, clean=False)

            logger.info("Stopping and disabling oddjobd service")
            self.master.run_command([
                "systemctl", "stop", "oddjobd"
            ])
            self.master.run_command([
                "systemctl", "disable", "oddjobd"
            ])

            self.master.run_command(['ipa-restore', '-U', backup_path])

        status = self.master.run_command([
            "systemctl", "status", "oddjobd"
        ])
        assert "active (running)" in status.stdout_text

        # replication should not work after restoration
        # create users to force master and replica to try to replicate
        tasks.user_add(self.master, 'test3_master')
        tasks.user_add(self.replica1, 'test3_replica')
        self.check_replication_error(self.master)
        self.check_replication_error(self.replica1)
        assert {'admin', 'test1_master', 'test1_replica', 'test3_master'} == \
            self.get_users(self.master)
        assert {'admin', 'test2_master', 'test2_replica', 'test3_replica'} == \
            self.get_users(self.replica1)

        # reestablish and check replication
        self.replica1.run_command(['ipa-replica-manage', 're-initialize',
                                  '--from', self.master.hostname])
        # create users to force master and replica to try to replicate
        tasks.user_add(self.master, 'test4_master')
        tasks.user_add(self.replica1, 'test4_replica')
        self.check_replication_success(self.master)
        self.check_replication_success(self.replica1)
        assert {'admin', 'test1_master', 'test1_replica',
                'test3_master', 'test4_master', 'test4_replica'} == \
            self.get_users(self.master)
        assert {'admin', 'test1_master', 'test1_replica',
                'test3_master', 'test4_master', 'test4_replica'} == \
            self.get_users(self.replica1)

        # CA on master should be accesible from master and replica
        self.request_test_service_cert(
            self.master, cert_sign_request[self.master.hostname])
        self.request_test_service_cert(
            self.replica1, cert_sign_request[self.replica1.hostname])

        # replica should not be able to sign certificates without CA on master
        self.master.run_command(['ipactl', 'stop'])
        try:
            self.request_test_service_cert(
                self.replica1, cert_sign_request[self.replica1.hostname],
                expect_connection_error=True)
        finally:
            self.master.run_command(['ipactl', 'start'])

        tasks.install_ca(self.replica1)

        # now replica should be able to sign certificates without CA on master
        self.master.run_command(['ipactl', 'stop'])
        self.request_test_service_cert(
            self.replica1, cert_sign_request[self.replica1.hostname])
        self.master.run_command(['ipactl', 'start'])

        # check installation of new replica
        tasks.install_replica(self.master, self.replica2, setup_ca=True)
        check_replication(self.master, self.replica2, "testuser")

        # new replica should be able to sign certificates without CA on master
        # and old replica
        self.master.run_command(['ipactl', 'stop'])
        self.replica1.run_command(['ipactl', 'stop'])
        try:
            self.request_test_service_cert(
                self.replica2, cert_sign_request[self.replica2.hostname])
        finally:
            self.replica1.run_command(['ipactl', 'start'])
            self.master.run_command(['ipactl', 'start'])
    def test_full_backup_and_restore_with_replica(self, cert_sign_request):
        # check prerequisites
        self.check_replication_success(self.master)
        self.check_replication_success(self.replica1)

        self.master.run_command(
            ['ipa', 'service-add', 'TEST/' + self.master.hostname])

        tasks.user_add(self.master, 'test1_master')
        tasks.user_add(self.replica1, 'test1_replica')

        with restore_checker(self.master):
            backup_path = tasks.get_backup_dir(self.master)

            # change data after backup
            self.master.run_command(['ipa', 'user-del', 'test1_master'])
            self.replica1.run_command(['ipa', 'user-del', 'test1_replica'])
            tasks.user_add(self.master, 'test2_master')
            tasks.user_add(self.replica1, 'test2_replica')

            # simulate master crash
            self.master.run_command(['ipactl', 'stop'])
            tasks.uninstall_master(self.master, clean=False)

            logger.info("Stopping and disabling oddjobd service")
            self.master.run_command([
                "systemctl", "stop", "oddjobd"
            ])
            self.master.run_command([
                "systemctl", "disable", "oddjobd"
            ])

            self.master.run_command(['ipa-restore', '-U', backup_path])

        status = self.master.run_command([
            "systemctl", "status", "oddjobd"
        ])
        assert "active (running)" in status.stdout_text

        # replication should not work after restoration
        # create users to force master and replica to try to replicate
        tasks.user_add(self.master, 'test3_master')
        tasks.user_add(self.replica1, 'test3_replica')
        self.check_replication_error(self.master)
        self.check_replication_error(self.replica1)
        assert {'admin', 'test1_master', 'test1_replica', 'test3_master'} == \
            self.get_users(self.master)
        assert {'admin', 'test2_master', 'test2_replica', 'test3_replica'} == \
            self.get_users(self.replica1)

        # reestablish and check replication
        self.replica1.run_command(['ipa-replica-manage', 're-initialize',
                                  '--from', self.master.hostname])
        # create users to force master and replica to try to replicate
        tasks.user_add(self.master, 'test4_master')
        tasks.user_add(self.replica1, 'test4_replica')
        self.check_replication_success(self.master)
        self.check_replication_success(self.replica1)
        assert {'admin', 'test1_master', 'test1_replica',
                'test3_master', 'test4_master', 'test4_replica'} == \
            self.get_users(self.master)
        assert {'admin', 'test1_master', 'test1_replica',
                'test3_master', 'test4_master', 'test4_replica'} == \
            self.get_users(self.replica1)

        # CA on master should be accesible from master and replica
        self.request_test_service_cert(
            self.master, cert_sign_request[self.master.hostname])
        self.request_test_service_cert(
            self.replica1, cert_sign_request[self.replica1.hostname])

        # replica should not be able to sign certificates without CA on master
        self.master.run_command(['ipactl', 'stop'])
        try:
            self.request_test_service_cert(
                self.replica1, cert_sign_request[self.replica1.hostname],
                expect_connection_error=True)
        finally:
            self.master.run_command(['ipactl', 'start'])

        tasks.install_ca(self.replica1)

        # now replica should be able to sign certificates without CA on master
        self.master.run_command(['ipactl', 'stop'])
        self.request_test_service_cert(
            self.replica1, cert_sign_request[self.replica1.hostname])
        self.master.run_command(['ipactl', 'start'])

        # check installation of new replica
        tasks.install_replica(self.master, self.replica2, setup_ca=True)
        check_replication(self.master, self.replica2, "testuser")

        # new replica should be able to sign certificates without CA on master
        # and old replica
        self.master.run_command(['ipactl', 'stop'])
        self.replica1.run_command(['ipactl', 'stop'])
        try:
            self.request_test_service_cert(
                self.replica2, cert_sign_request[self.replica2.hostname])
        finally:
            self.replica1.run_command(['ipactl', 'start'])
            self.master.run_command(['ipactl', 'start'])
Exemple #23
0
    def test_renew_expired_cert_replica(self, expire_certs):
        """Test renewal of certificates on replica with ipa-cert-fix

        This is to check that ipa-cert-fix renews the certificates
        on replica

        related: https://pagure.io/freeipa/issue/7885
        """
        # wait for cert expiry
        check_status(self.master, 8, "CA_UNREACHABLE")

        self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n')

        check_status(self.master, 9, "MONITORING")

        # replica operations
        # 'Server-Cert cert-pki-ca' cert will be in CA_UNREACHABLE state
        cmd = self.replicas[0].run_command([
            'getcert', 'list', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n',
            'Server-Cert cert-pki-ca'
        ])
        req_id = get_certmonger_fs_id(cmd.stdout_text)
        tasks.wait_for_certmonger_status(self.replicas[0], ('CA_UNREACHABLE'),
                                         req_id,
                                         timeout=600)
        # get initial expiry date to compare later with renewed cert
        initial_expiry = get_cert_expiry(self.replicas[0],
                                         paths.PKI_TOMCAT_ALIAS_DIR,
                                         'Server-Cert cert-pki-ca')

        # check that HTTP,LDAP,PKINIT are renewed and in MONITORING state
        instance = realm_to_serverid(self.master.domain.realm)
        dirsrv_cert = paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance
        for cert in (paths.KDC_CERT, paths.HTTPD_CERT_FILE):
            cmd = self.replicas[0].run_command(['getcert', 'list', '-f', cert])
            req_id = get_certmonger_fs_id(cmd.stdout_text)
            tasks.wait_for_certmonger_status(self.replicas[0], ('MONITORING'),
                                             req_id,
                                             timeout=600)

        cmd = self.replicas[0].run_command(
            ['getcert', 'list', '-d', dirsrv_cert])
        req_id = get_certmonger_fs_id(cmd.stdout_text)
        tasks.wait_for_certmonger_status(self.replicas[0], ('MONITORING'),
                                         req_id,
                                         timeout=600)

        # check if replication working fine
        testuser = '******'
        password = '******'
        stdin = (f"{self.master.config.admin_password}\n"
                 f"{self.master.config.admin_password}\n"
                 f"{self.master.config.admin_password}\n")
        self.master.run_command(['kinit', 'admin'], stdin_text=stdin)
        tasks.user_add(self.master, testuser, password=password)
        self.replicas[0].run_command(['kinit', 'admin'], stdin_text=stdin)
        self.replicas[0].run_command(['ipa', 'user-show', testuser])

        # renew shared certificates by resubmitting to certmonger
        cmd = self.replicas[0].run_command(
            ['getcert', 'list', '-f', paths.RA_AGENT_PEM])
        req_id = get_certmonger_fs_id(cmd.stdout_text)
        if needs_resubmit(self.replicas[0], req_id):
            self.replicas[0].run_command(['getcert', 'resubmit', '-i', req_id])
            tasks.wait_for_certmonger_status(self.replicas[0], ('MONITORING'),
                                             req_id,
                                             timeout=600)
        for cert_nick in ('auditSigningCert cert-pki-ca',
                          'ocspSigningCert cert-pki-ca',
                          'subsystemCert cert-pki-ca'):
            cmd = self.replicas[0].run_command([
                'getcert', 'list', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n',
                cert_nick
            ])
            req_id = get_certmonger_fs_id(cmd.stdout_text)
            if needs_resubmit(self.replicas[0], req_id):
                self.replicas[0].run_command(
                    ['getcert', 'resubmit', '-i', req_id])
                tasks.wait_for_certmonger_status(self.replicas[0],
                                                 ('MONITORING'),
                                                 req_id,
                                                 timeout=600)

        self.replicas[0].run_command(['ipa-cert-fix', '-v'],
                                     stdin_text='yes\n')

        check_status(self.replicas[0], 9, "MONITORING")

        # Sometimes certmonger takes time to update the cert status
        # So check in nssdb instead of relying on getcert command
        renewed_expiry = get_cert_expiry(self.replicas[0],
                                         paths.PKI_TOMCAT_ALIAS_DIR,
                                         'Server-Cert cert-pki-ca')
        assert renewed_expiry > initial_expiry