示例#1
0
    def test_installclient_as_user_admin(self):
        """ipa-client-install should not use hardcoded admin for principal

        In ipaclient-install.log it should use the username that was entered
        earlier in the install process at the prompt.
        Related to : https://pagure.io/freeipa/issue/5406
        """
        client = self.clients[0]
        tasks.install_master(self.master)
        tasks.kinit_admin(self.master)
        username = '******'
        password = '******'
        password_confirmation = "%s\n%s\n" % (password,
                                              password)

        self.master.run_command(['ipa', 'user-add', username,
                                 '--first', username,
                                 '--last', username,
                                 '--password'],
                                stdin_text=password_confirmation)

        role_add = ['ipa', 'role-add', 'useradmin']
        self.master.run_command(role_add)
        self.master.run_command(['ipa', 'privilege-add', 'Add Hosts'])
        self.master.run_command(['ipa', 'privilege-add-permission',
                                 '--permissions', 'System: Add Hosts',
                                 'Add Hosts'])

        self.master.run_command(['ipa', 'role-add-privilege', 'useradmin',
                                 '--privileges', 'Host Enrollment'])

        self.master.run_command(['ipa', 'role-add-privilege', 'useradmin',
                                 '--privileges', 'Add Hosts'])

        role_member_add = ['ipa', 'role-add-member', 'useradmin',
                           '--users={}'.format(username)]
        self.master.run_command(role_member_add)
        user_kinit = "%s\n%s\n%s\n" % (password, password, password)
        self.master.run_command(['kinit', username],
                                stdin_text=user_kinit)
        tasks.install_client(
            self.master, client,
            extra_args=['--request-cert'],
            user=username, password=password
        )
        msg = "args=['/usr/bin/getent', 'passwd', '%s@%s']" % \
              (username, client.domain.name)
        install_log = client.get_file_contents(paths.IPACLIENT_INSTALL_LOG,
                                               encoding='utf-8')
        assert msg in install_log

        # check that user is able to request a host cert, too
        result = tasks.run_certutil(client, ['-L'], paths.IPA_NSSDB_DIR)
        assert 'Local IPA host' in result.stdout_text
        result = tasks.run_certutil(
            client,
            ['-K', '-f', paths.IPA_NSSDB_PWDFILE_TXT],
            paths.IPA_NSSDB_DIR
        )
        assert 'Local IPA host' in result.stdout_text
示例#2
0
    def test_invalid_range_types(self):

        invalid_range_types = ['ipa-local',
                               'ipa-ad-winsync',
                               'ipa-ipa-trust',
                               'random-invalid',
                               're@ll%ybad12!']

        self.configure_dns_and_time(self.ad)
        try:
            for range_type in invalid_range_types:
                tasks.kinit_admin(self.master)

                result = self.master.run_command(
                    ['ipa', 'trust-add', '--type', 'ad', self.ad_domain,
                     '--admin', 'Administrator',
                     '--range-type', range_type, '--password'],
                    raiseonerr=False,
                    stdin_text=self.master.config.ad_admin_password)

                # The trust-add command is supposed to fail
                assert result.returncode == 1
                assert "ERROR: invalid 'range_type'" in result.stderr_text
        finally:
            tasks.unconfigure_dns_for_trust(self.master, self.ad)
示例#3
0
 def test_list_help_topics(self):
     tasks.kinit_admin(self.master)
     result = self.master.run_command(
         ["ipa", "help", "topics"],
         raiseonerr=False
     )
     assert result.returncode == 0
示例#4
0
    def install(cls, mh):
        super(TestRulesWithServicePrincipals, cls).install(mh)
        master = cls.master
        tasks.kinit_admin(master)
        cls.replica = "replica.%s" % master.domain.name
        master.run_command(['ipa', 'host-add', cls.replica, '--force'])
        cls.service_name = "svc/%s" % master.hostname
        cls.replica_service_name = "svc/%s" % cls.replica
        master.run_command("ipa service-add %s" % cls.service_name)
        master.run_command("ipa service-add %s --force" %
                           cls.replica_service_name)
        master.run_command("ipa service-add-host %s --hosts %s" % (
            cls.service_name, cls.replica))
        master.run_command("ipa caacl-add %s --desc \"test\"" % cls.caacl)
        master.run_command("ipa caacl-add-host %s --hosts %s" % (cls.caacl,
                                                                 cls.replica))
        master.run_command("ipa caacl-add-service %s --services"
                           " svc/`hostname`" % cls.caacl)
        master.run_command("ipa-getkeytab -p host/%s@%s -k %s" % (
            cls.replica, master.domain.realm, cls.keytab))
        master.run_command("kinit -kt %s host/%s" % (cls.keytab, cls.replica))

        # Prepare a CSR

        cls.prepare_config()
        stdin_text = "qwerty\nqwerty\n%s\n" % cls.replica

        master.run_command(['openssl', 'req', '-config', cls.csr_conf, '-new',
                            '-out', cls.csr], stdin_text=stdin_text)
示例#5
0
    def test_delete_preserve_as_alternate_admin(self):
        """
        Test that a user member of admins group can call delete --preserve.

        This is a test case for issue 7342
        """

        # kinit admin
        tasks.kinit_admin(self.master)

        # Create a new user 'testuser' with a password
        testuser = '******'
        password = '******'
        testuser_password_confirmation = "%s\n%s\n" % (password,
                                                       password)
        self.master.run_command(['ipa', 'user-add', testuser,
                                 '--first', testuser,
                                 '--last', testuser,
                                 '--password'],
                                stdin_text=testuser_password_confirmation)

        # kinit as altadmin
        self.master.run_command(['kinit', self.altadmin],
                                stdin_text=self.master.config.admin_password)

        # call ipa user-del --preserve
        self.master.run_command(['ipa', 'user-del', '--preserve', testuser])
示例#6
0
    def test_stageuser_show_as_alternate_admin(self):
        """
        Test that a user member of admins group can call stageuser-show
        and read the 'Kerberos Keys available' information.

        This is a test case for issue 7342
        """
        # kinit admin
        tasks.kinit_admin(self.master)

        # Create a new stage user 'stageuser' with a password
        stageuser = '******'
        password = '******'
        stageuser_password_confirmation = "%s\n%s\n" % (password,
                                                        password)
        self.master.run_command(['ipa', 'stageuser-add', stageuser,
                                 '--first', stageuser,
                                 '--last', stageuser,
                                 '--password'],
                                stdin_text=stageuser_password_confirmation)

        # kinit as altadmin
        self.master.run_command(['kinit', self.altadmin],
                                stdin_text=self.master.config.admin_password)

        # call ipa stageuser-show
        # the field Kerberos Keys available must contain True
        result = self.master.run_command(['ipa', 'stageuser-show', stageuser])
        assert 'Kerberos keys available: True' in result.stdout_text
示例#7
0
    def test_change_selinuxusermaporder(self):
        """
        An update file meant to ensure a more sane default was
        overriding any customization done to the order.
        """
        maporder = "unconfined_u:s0-s0:c0.c1023"

        # set a new default
        tasks.kinit_admin(self.master)
        result = self.master.run_command(
            ["ipa", "config-mod",
             "--ipaselinuxusermaporder={}".format(maporder)],
            raiseonerr=False
        )
        assert result.returncode == 0

        # apply the update
        result = self.master.run_command(
            ["ipa-server-upgrade"],
            raiseonerr=False
        )
        assert result.returncode == 0

        # ensure result is the same
        result = self.master.run_command(
            ["ipa", "config-show"],
            raiseonerr=False
        )
        assert result.returncode == 0
        assert "SELinux user map order: {}".format(
            maporder) in result.stdout_text
    def _full_backup_restore_with_DNS_zone(self, reinstall=False):
        """backup, uninstall, restore"""
        with restore_checker(self.master):
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example_test_zone,
            ])

            tasks.resolve_record(self.master.ip, self.example_test_zone)

            backup_path = backup(self.master)

            self.master.run_command(['ipa-server-install',
                                     '--uninstall',
                                     '-U'])

            if reinstall:
                tasks.install_master(self.master, setup_dns=True)

            dirman_password = self.master.config.dirman_password
            self.master.run_command(['ipa-restore', backup_path],
                                    stdin_text=dirman_password + '\nyes')

            tasks.resolve_record(self.master.ip, self.example_test_zone)

            tasks.kinit_admin(self.master)
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example2_test_zone,
            ])

            tasks.resolve_record(self.master.ip, self.example2_test_zone)
示例#9
0
    def test_add_permission_failure_issue5923(self):
        # https://pagure.io/freeipa/issue/5923
        # error response used to contain bytes instead of text

        tasks.kinit_admin(self.master)
        # neither privilege nor permission exists
        result = self.master.run_command(
            ["ipa", "privilege-add-permission", "loc",
             "--permission='System: Show IPA Locations"],
            raiseonerr=False
        )
        assert result.returncode == 2
        err = result.stderr_text.strip()  # pylint: disable=no-member
        assert err == "ipa: ERROR: loc: privilege not found"
        # add privilege
        result = self.master.run_command(
            ["ipa", "privilege-add", "loc"],
        )
        assert 'Added privilege "loc"' in result.stdout_text
        # permission is still missing
        result = self.master.run_command(
            ["ipa", "privilege-add-permission", "loc",
             "--permission='System: Show IPA Locations"],
            raiseonerr=False
        )
        assert result.returncode == 1
        assert "Number of permissions added 0" in result.stdout_text
示例#10
0
    def test_create_and_retrieve_shared_vault_replica_without_kra(self):
        # create vault
        self.replicas[0].run_command([
            "ipa", "vault-add",
            self.shared_vault_name_replica_without_KRA,
            "--shared",
            "--type", "standard",
        ])

        # archive secret
        self.replicas[0].run_command([
            "ipa", "vault-archive",
            self.shared_vault_name_replica_without_KRA,
            "--shared",
            "--data", self.vault_data,
        ])
        time.sleep(WAIT_AFTER_ARCHIVE)

        # add non-admin user
        self.replicas[0].run_command([
            'ipa', 'user-add', self.vault_user,
            '--first', self.vault_user,
            '--last', self.vault_user,
            '--password'],
            stdin_text=self.vault_user_password)

        # add it to vault
        self.replicas[0].run_command([
            "ipa", "vault-add-member",
            self.shared_vault_name_replica_without_KRA,
            "--shared",
            "--users", self.vault_user,
        ])

        self.replicas[0].run_command([
            'kdestroy', '-A'])

        user_kinit = "%s\n%s\n%s\n" % (self.vault_user_password,
                                       self.vault_user_password,
                                       self.vault_user_password)

        self.replicas[0].run_command([
            'kinit', self.vault_user],
            stdin_text=user_kinit)

        # TODO: possibly refactor with:
        # self._retrieve_secret([self.vault_name_replica_without_KRA])

        self.replicas[0].run_command([
            "ipa", "vault-retrieve",
            "--shared",
            self.shared_vault_name_replica_without_KRA,
            "--out=test.txt"])

        self.replicas[0].run_command([
            'kdestroy', '-A'])

        tasks.kinit_admin(self.replicas[0])
示例#11
0
    def test_ssh_key_connection(self, tmpdir):
        """
        Integration test for https://pagure.io/SSSD/sssd/issue/3747
        """

        test_user = '******'
        external_master_hostname = \
            self.master.external_hostname  # pylint: disable=no-member

        pub_keys = []

        for i in range(40):
            ssh_key_pair = tasks.generate_ssh_keypair()
            pub_keys.append(ssh_key_pair[1])
            with open(os.path.join(
                    tmpdir, 'ssh_priv_{}'.format(i)), 'w') as fp:
                fp.write(ssh_key_pair[0])

        tasks.kinit_admin(self.master)
        self.master.run_command(['ipa', 'user-add', test_user,
                                 '--first=tester', '--last=tester'])

        keys_opts = ' '.join(['--ssh "{}"'.format(k) for k in pub_keys])
        cmd = 'ipa user-mod {} {}'.format(test_user, keys_opts)
        self.master.run_command(cmd)

        # connect with first SSH key
        first_priv_key_path = os.path.join(tmpdir, 'ssh_priv_1')
        # change private key permission to comply with SS rules
        os.chmod(first_priv_key_path, 0o600)

        sshcon = paramiko.SSHClient()
        sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # first connection attempt is a workaround for
        # https://pagure.io/SSSD/sssd/issue/3669
        try:
            sshcon.connect(external_master_hostname, username=test_user,
                           key_filename=first_priv_key_path, timeout=1)
        except (paramiko.AuthenticationException, paramiko.SSHException):
            pass

        try:
            sshcon.connect(external_master_hostname, username=test_user,
                           key_filename=first_priv_key_path, timeout=1)
        except (paramiko.AuthenticationException,
                paramiko.SSHException) as e:
            pytest.fail('Authentication using SSH key not successful', e)

        journal_cmd = ['journalctl', '--since=today', '-u', 'sshd']
        result = self.master.run_command(journal_cmd)
        output = result.stdout_text
        assert not re.search('exited on signal 13', output)

        # cleanup
        self.master.run_command(['ipa', 'user-del', test_user])
示例#12
0
    def test_service_as_user_admin(self):
        """Test that a service in User Administrator role can manage users"""

        service_name1 = 'testservice1/%s@%s' % (self.master.hostname,
                                                self.master.domain.realm)
        keytab_file1 = os.path.join(self.master.config.test_dir,
                                    'testservice_keytab1')

        # Prepare a service

        self.master.run_command(['ipa', 'service-add', service_name1])

        self.master.run_command(['ipa-getkeytab',
                                 '-p', service_name1,
                                 '-k', keytab_file1,
                                 '-s', self.master.hostname])

        # Check that the service cannot add a user

        self.master.run_command(['kdestroy'])
        self.master.run_command(['kinit', '-k', service_name1,
                                 '-t', keytab_file1])

        result = self.master.run_command(['ipa', 'role-add-member',
                                          'User Administrator',
                                          '--service', service_name1],
                                         raiseonerr=False)
        assert result.returncode > 0

        # Add service to User Administrator role

        self.master.run_command(['kdestroy'])
        tasks.kinit_admin(self.master)

        self.master.run_command(['ipa', 'role-add-member',
                                 'User Administrator',
                                 '--service', service_name1])

        # Check that the service now can add a user

        self.master.run_command(['kdestroy'])
        self.master.run_command(['kinit', '-k', service_name1,
                                 '-t', keytab_file1])

        self.master.run_command(['ipa', 'user-add', 'tuser',
                                 '--first', 'a', '--last', 'b', '--random'])

        # Clean up

        self.master.run_command(['kdestroy'])
        tasks.kinit_admin(self.master)

        self.master.run_command(['ipa', 'service-del', service_name1])
        self.master.run_command(['ipa', 'user-del', 'tuser'])
示例#13
0
def run_advice(master, advice_id, advice_regex, raiseerr=True):
    # Obtain the advice from the server
    tasks.kinit_admin(master)
    result = master.run_command(['ipa-advise', advice_id],
                                     raiseonerr=raiseerr)

    if not result.stdout_text:
        advice = result.stderr_text
    else:
        advice = result.stdout_text

    assert re.search(advice_regex, advice, re.S)
示例#14
0
    def test_service_access(self):
        """ Test that user is granted access when authenticated using
        credentials that are sufficient for a service, and denied access
        when using insufficient credentials"""

        service_name2 = 'testservice2/%s@%s' % (self.master.hostname,
                                                self.master.domain.realm)

        keytab_file2 = os.path.join(self.master.config.test_dir,
                                    'testservice_keytab2')

        # Prepare a service without authentication indicator
        self.master.run_command(['ipa', 'service-add', service_name2])

        self.master.run_command(['ipa-getkeytab',
                                 '-p', service_name2,
                                 '-k', keytab_file2])

        # Set authentication-type for admin user
        self.master.run_command(['ipa', 'user-mod', 'admin',
                                 '--user-auth-type=password',
                                 '--user-auth-type=otp'])

        # Authenticate
        self.master.run_command(['kinit', '-k', service_name2,
                                 '-t', keytab_file2])

        # Verify access to service is granted
        result = self.master.run_command(['kvno', service_name2],
                                         raiseonerr=False)
        assert result.returncode == 0

        # Obtain admin ticket to be able to update service
        tasks.kinit_admin(self.master)

        # Modify service to have authentication indicator
        self.master.run_command(['ipa', 'service-mod', service_name2,
                                 '--auth-ind=otp'])

        self.master.run_command(['ipa-getkeytab',
                                 '-p', service_name2,
                                 '-k', keytab_file2])

        # Authenticate
        self.master.run_command(['kinit', '-k', service_name2,
                                 '-t', keytab_file2])

        # Verify access to service is rejected
        result = self.master.run_command(['kvno', service_name2],
                                         raiseonerr=False)
        assert result.returncode > 0
示例#15
0
    def test_apply_advice(self):
        # Obtain the advice from the server
        tasks.kinit_admin(self.master)
        result = self.master.run_command(['ipa-advise', self.advice_id])
        advice = result.stdout_text

        # Apply the advice on the legacy client
        advice_path = os.path.join(self.legacy_client.config.test_dir,
                                   'advice.sh')
        self.legacy_client.put_file_contents(advice_path, advice)
        result = self.legacy_client.run_command(['bash', '-x', '-e',
                                                 advice_path])

        # Restart SSHD to load new PAM configuration
        self.legacy_client.run_command([paths.SBIN_SERVICE, 'sshd', 'restart'])
示例#16
0
 def execute_advise(self, host, advice_id, *args):
     # ipa-advise script is only available on a server
     tasks.kinit_admin(self.master)
     advice = self.master.run_command(['ipa-advise', advice_id])
     # execute script on host (client or master)
     if host is not self.master:
         tasks.kinit_admin(host)
     filename = tasks.upload_temp_contents(host, advice.stdout_text)
     cmd = ['sh', filename]
     cmd.extend(args)
     try:
         result = host.run_command(cmd)
     finally:
         host.run_command(['rm', '-f', filename])
     return advice, result
示例#17
0
    def test_ipa_console(self):
        tasks.kinit_admin(self.master)
        result = self.master.run_command(
            ["ipa", "console"],
            stdin_text="api.env"
        )
        assert "ipalib.config.Env" in result.stdout_text

        filename = tasks.upload_temp_contents(
            self.master,
            "print(api.env)\n"
        )
        result = self.master.run_command(
            ["ipa", "console", filename],
        )
        assert "ipalib.config.Env" in result.stdout_text
示例#18
0
    def test_establish_nonexternal_treedomain_trust(self):
        self.configure_dns_and_time(self.tree_ad)
        try:
            tasks.kinit_admin(self.master)

            result = self.master.run_command([
                'ipa', 'trust-add', '--type', 'ad', self.ad_treedomain,
                '--admin',
                'Administrator', '--password', '--range-type', 'ipa-ad-trust'
            ], stdin_text=self.master.config.ad_admin_password,
                raiseonerr=False)

            assert result != 0
            assert ("Domain '{0}' is not a root domain".format(
                self.ad_treedomain) in result.stderr_text)
        finally:
            tasks.unconfigure_dns_for_trust(self.master, self.tree_ad)
示例#19
0
def restore_checker(host):
    """Check that the IPA at host works the same at context enter and exit"""
    tasks.kinit_admin(host)

    results = []
    for check, assert_func in CHECKS:
        logger.info('Storing result for %s', check.__name__)
        results.append(check(host))

    yield

    tasks.kinit_admin(host)

    for (check, assert_func), expected in zip(CHECKS, results):
        logger.info('Checking result for %s', check.__name__)
        got = check(host)
        assert_func(expected, got)
示例#20
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'])
示例#21
0
    def _full_backup_restore_with_vault(self, reinstall=False):
        with restore_checker(self.master):
            # create vault
            self.master.run_command([
                "ipa", "vault-add",
                self.vault_name,
                "--password", self.vault_password,
                "--type", "symmetric",
            ])

            # archive secret
            self.master.run_command([
                "ipa", "vault-archive",
                self.vault_name,
                "--password", self.vault_password,
                "--data", self.vault_data,
            ])

            # retrieve secret
            self.master.run_command([
                "ipa", "vault-retrieve",
                self.vault_name,
                "--password", self.vault_password,
            ])

            backup_path = backup(self.master)

            self.master.run_command(['ipa-server-install',
                                     '--uninstall',
                                     '-U'])

            if reinstall:
                tasks.install_master(self.master, setup_dns=True)

            dirman_password = self.master.config.dirman_password
            self.master.run_command(['ipa-restore', backup_path],
                                    stdin_text=dirman_password + '\nyes')

            tasks.kinit_admin(self.master)
            # retrieve secret after restore
            self.master.run_command([
                "ipa", "vault-retrieve",
                self.vault_name,
                "--password", self.vault_password,
            ])
示例#22
0
    def test_ssh_leak(self):
        """
        Integration test for https://pagure.io/SSSD/sssd/issue/3794
        """

        def count_pipes():

            res = self.master.run_command(['pidof', 'sssd_ssh'])
            pid = res.stdout_text.strip()
            proc_path = '/proc/{}/fd'.format(pid)
            res = self.master.run_command(['ls', '-la', proc_path])
            fds_text = res.stdout_text.strip()
            return sum((1 for _ in re.finditer(r'pipe', fds_text)))

        test_user = '******'

        tasks.kinit_admin(self.master)
        self.master.run_command(['ipa', 'user-add', test_user,
                                 '--first=tester', '--last=tester'])

        certs = []

        # we are ok with whatever certificate for this test
        external_ca = ExternalCA()
        for _dummy in range(3):
            cert = external_ca.create_ca()
            cert = tasks.strip_cert_header(cert.decode('utf-8'))
            certs.append('"{}"'.format(cert))

        cert_args = list(
            chain.from_iterable(list(zip(repeat('--certificate'), certs))))
        cmd = 'ipa user-add-cert {} {}'.format(test_user, ' '.join(cert_args))
        self.master.run_command(cmd)

        tasks.clear_sssd_cache(self.master)

        num_of_pipes = count_pipes()

        for _dummy in range(3):
            self.master.run_command([paths.SSS_SSH_AUTHORIZEDKEYS, test_user])
            current_num_of_pipes = count_pipes()
            assert current_num_of_pipes == num_of_pipes

        # cleanup
        self.master.run_command(['ipa', 'user-del', test_user])
示例#23
0
    def test_add_remove_segment(self):
        """
        Make sure a topology segment can be manually created and deleted
        with the influence on the real topology
        Testcase http://www.freeipa.org/page/V4/Manage_replication_topology/
        Test_plan#Test_case:_Basic_CRUD_test
        """
        tasks.kinit_admin(self.master)
        # Install the second replica
        tasks.install_replica(self.master, self.replicas[1], setup_ca=False,
                              setup_dns=False)
        # turn a star into a ring
        segment, err = tasks.create_segment(self.master,
                                            self.replicas[0],
                                            self.replicas[1])
        assert err == "", err
        # Make sure the new segment is shown by `ipa topologysegment-find`
        result1 = self.master.run_command(['ipa', 'topologysegment-find',
                                           DOMAIN_SUFFIX_NAME]).stdout_text
        assert(segment['name'] in result1), (
            "%s: segment not found" % segment['name'])
        # Remove master <-> replica2 segment and make sure that the changes get
        # there through replica1
        # Since segment name can be one of master-to-replica2 or
        # replica2-to-master, we need to determine the segment name dynamically

        deleteme = find_segment(self.master, self.replicas[1])
        returncode, error = tasks.destroy_segment(self.master, deleteme)
        assert returncode == 0, error
        # Wait till replication ends and make sure replica1 does not have
        # segment that was deleted on master
        master_ldap = self.master.ldap_connect()
        tasks.wait_for_replication(master_ldap)
        result3 = self.replicas[0].run_command(['ipa', 'topologysegment-find',
                                               DOMAIN_SUFFIX_NAME]).stdout_text
        assert(deleteme not in result3), "%s: segment still exists" % deleteme
        # Create test data on master and make sure it gets all the way down to
        # replica2 through replica1
        self.master.run_command(['ipa', 'user-add', 'someuser',
                                 '--first', 'test',
                                 '--last', 'user'])
        tasks.wait_for_replication(master_ldap)
        result4 = self.replicas[1].run_command(['ipa', 'user-find'])
        assert('someuser' in result4.stdout_text), 'User not found: someuser'
示例#24
0
 def test_topology_updated_on_replica_install_remove(self):
     """
     Install and remove a replica and make sure topology information is
     updated on all other replicas
     Testcase: http://www.freeipa.org/page/V4/Manage_replication_topology/
     Test_plan#Test_case:
     _Replication_topology_should_be_saved_in_the_LDAP_tree
     """
     tasks.kinit_admin(self.master)
     result1 = self.master.run_command(
         ['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]).stdout_text
     segment_name = self.segmentnames_re.findall(result1)[0]
     assert (self.master.hostname in segment_name), (
         "Segment %s does not contain master hostname" % segment_name)
     assert (self.replicas[0].hostname in segment_name), (
         "Segment %s does not contain replica hostname" % segment_name)
     tasks.install_replica(self.master,
                           self.replicas[1],
                           setup_ca=False,
                           setup_dns=False)
     # We need to make sure topology information is consistent across all
     # replicas
     result2 = self.master.run_command(
         ['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME])
     result3 = self.replicas[0].run_command(
         ['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME])
     result4 = self.replicas[1].run_command(
         ['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME])
     segments = self.tokenize_topologies(result2.stdout_text)
     assert (len(segments) == 2), "Unexpected number of segments found"
     assert_deepequal(result2.stdout_text, result3.stdout_text)
     assert_deepequal(result3.stdout_text, result4.stdout_text)
     # Now let's check that uninstalling the replica will update the topology
     # info on the rest of replicas.
     # first step of uninstallation is removal of the replica on other
     # master, then it can be uninstalled. Doing it the other way is also
     # possible, but not reliable - some data might not be replicated.
     tasks.clean_replication_agreement(self.master, self.replicas[1])
     tasks.uninstall_master(self.replicas[1])
     result5 = self.master.run_command(
         ['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME])
     num_entries = self.noentries_re.search(result5.stdout_text).group(1)
     assert (num_entries == "1"), "Incorrect number of entries displayed"
示例#25
0
    def test_2fa_disable_single_prompt(self):
        """Test ssh with 2FA when single prompt is disabled.

        Test for : https://pagure.io/SSSD/sssd/issue/3264

        When [prompting/2fa/sshd] with single_prompt = False is set
        then during ssh it should be prompted with given message
        for first factor and then for second factor.

        This requires paramiko until the 2-prompt sshpass RFE is
        fulfilled: https://sourceforge.net/p/sshpass/feature-requests/5/
        """
        if self.master.is_fips_mode:  # pylint: disable=no-member
            pytest.skip("paramiko is not compatible with FIPS mode")

        master = self.master
        USER2 = 'sshuser2'
        sssd_conf_backup = tasks.FileBackup(master, paths.SSSD_CONF)
        first_prompt = 'Enter first factor:'
        second_prompt = 'Enter second factor:'
        add_contents = textwrap.dedent('''
            [prompting/2fa/sshd]
            single_prompt = False
            first_prompt = {0}
            second_prompt = {1}
            ''').format(first_prompt, second_prompt)
        set_sssd_conf(master, add_contents)
        tasks.create_active_user(master, USER2, PASSWORD)
        tasks.kinit_admin(master)
        master.run_command(['ipa', 'user-mod', USER2, '--user-auth-type=otp'])
        try:
            otpuid, totp = add_otptoken(master, USER2, otptype='totp')
            master.run_command(['ipa', 'otptoken-show', otpuid])
            otpvalue = totp.generate(int(time.time())).decode('ascii')
            answers = {first_prompt: PASSWORD, second_prompt: otpvalue}
            ssh_2f(master.hostname, USER2, answers)
            # check if user listed in output
            cmd = self.master.run_command(['semanage', 'login', '-l'])
            assert USER2 in cmd.stdout_text
        finally:
            master.run_command(['ipa', 'user-del', USER2])
            self.master.run_command(['semanage', 'login', '-D'])
            sssd_conf_backup.restore()
def restore_checker(host):
    """Check that the IPA at host works the same at context enter and exit"""
    tasks.kinit_admin(host)

    results = []
    for check, assert_func in CHECKS:
        logger.info('Storing result for %s', check.__name__)
        results.append(check(host))

    yield

    # Wait for SSSD to become online before doing any other check
    tasks.wait_for_sssd_domain_status_online(host)
    tasks.kinit_admin(host)

    for (check, assert_func), expected in zip(CHECKS, results):
        logger.info('Checking result for %s', check.__name__)
        got = check(host)
        assert_func(expected, got)
示例#27
0
    def test_certmap_match_issue7520(self):
        # https://pagure.io/freeipa/issue/7520
        tasks.kinit_admin(self.master)
        result = self.master.run_command(
            ['ipa', 'certmap-match', paths.IPA_CA_CRT],
            raiseonerr=False
        )
        assert result.returncode == 1
        assert not result.stderr_text
        assert "0 users matched" in result.stdout_text

        cab64 = self.get_cert_base64(self.master, paths.IPA_CA_CRT)
        result = self.master.run_command(
            ['ipa', 'certmap-match', '--certificate', cab64],
            raiseonerr=False
        )
        assert result.returncode == 1
        assert not result.stderr_text
        assert "0 users matched" in result.stdout_text
示例#28
0
    def test_prepare_users(self):

        users = {"athena": "p", "euripides": "s"}
        temp_pass = '******'
        for user in users:
            self.master.run_command([
                "ipa", "user-add",
                "%s" % user, "--first",
                "%s" % user, "--last",
                "%s" % users[user], '--password'
            ],
                                    stdin_text="%s\n%s\n" %
                                    (temp_pass, temp_pass))
            self.master.run_command(["kdestroy", "-A"])
            password = "******"
            user_kinit = "%s\n%s\n%s\n" % (temp_pass, password, password)
            self.master.run_command(['kinit', user], stdin_text=user_kinit)
            self.master.run_command(["kdestroy", "-A"])
            tasks.kinit_admin(self.master)
示例#29
0
    def install(cls, mh):
        super(BaseTestLegacyClient, cls).install(mh)

        tasks.kinit_admin(cls.master)

        password_confirmation = (
            cls.master.config.admin_password +
            '\n' +
            cls.master.config.admin_password
            )

        cls.master.run_command(['ipa', 'user-add', 'disabledipauser',
                                        '--first', 'disabled',
                                        '--last', 'ipauser',
                                        '--password'],
                                 stdin_text=password_confirmation)

        cls.master.run_command(['ipa', 'user-disable', 'disabledipauser'])

        cls.ad = cls.ad_domains[0].ads[0]

        cls.legacy_client = cls.host_by_role(cls.required_extra_roles[0])

        # Determine whether the subdomain AD is available
        try:
            child_ad = cls.host_by_role(cls.optional_extra_roles[0])
            cls.ad_subdomain = '.'.join(
                child_ad.hostname.split('.')[1:])
        except LookupError:
            cls.ad_subdomain = None

        # Determine whether the tree domain AD is available
        try:
            cls.tree_ad = cls.host_by_role(cls.optional_extra_roles[1])
            cls.ad_treedomain = '.'.join(
                cls.tree_ad.hostname.split('.')[1:])
        except LookupError:
            cls.ad_treedomain = None

        tasks.apply_common_fixes(cls.legacy_client)

        for f in cls.backup_files:
            tasks.backup_file(cls.legacy_client, f)
示例#30
0
    def install(cls, mh):
        super(BaseTestLegacyClient, cls).install(mh)

        tasks.kinit_admin(cls.master)

        password_confirmation = (
            cls.master.config.admin_password +
            '\n' +
            cls.master.config.admin_password
            )

        cls.master.run_command(['ipa', 'user-add', 'disabledipauser',
                                        '--first', 'disabled',
                                        '--last', 'ipauser',
                                        '--password'],
                                 stdin_text=password_confirmation)

        cls.master.run_command(['ipa', 'user-disable', 'disabledipauser'])

        cls.ad = cls.ad_domains[0].ads[0]

        cls.legacy_client = cls.host_by_role(cls.required_extra_roles[0])

        # Determine whether the subdomain AD is available
        try:
            child_ad = cls.host_by_role(cls.optional_extra_roles[0])
            cls.ad_subdomain = '.'.join(
                child_ad.hostname.split('.')[1:])
        except LookupError:
            cls.ad_subdomain = None

        # Determine whether the tree domain AD is available
        try:
            cls.tree_ad = cls.host_by_role(cls.optional_extra_roles[1])
            cls.ad_treedomain = '.'.join(
                cls.tree_ad.hostname.split('.')[1:])
        except LookupError:
            cls.ad_treedomain = None

        tasks.apply_common_fixes(cls.legacy_client)

        for f in cls.backup_files:
            tasks.backup_file(cls.legacy_client, f)
示例#31
0
    def install(cls, mh):
        super(TestACMEwithExternalCA, cls).install(mh)

        # install master with external-ca
        result = install_server_external_ca_step1(cls.master)
        assert result.returncode == 0
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            cls.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA)

        install_server_external_ca_step2(cls.master, ipa_ca_fname,
                                         root_ca_fname)
        tasks.kinit_admin(cls.master)

        tasks.install_client(cls.master, cls.clients[0])
        tasks.config_host_resolvconf_with_master_data(cls.master,
                                                      cls.clients[0])
        tasks.install_replica(cls.master, cls.replicas[0])
        tasks.config_host_resolvconf_with_master_data(cls.master,
                                                      cls.replicas[0])
示例#32
0
    def test_ccache_sweep_expired(self, reset_to_default_policy):
        """Test that the ccache sweeper works on expired ccaches

           - Force wipe all existing ccaches
           - Set the ticket policy to a short value, 20 seconds.
           - Do a series of kinit, ipa command, kdestroy to generate ccaches
           - sleep() for expiration
           - Run the sweeper
           - Verify that all expired ccaches are gone
        """
        MAXLIFE = 20
        reset_to_default_policy(self.master)  # this will reset at END of test
        tasks.kinit_admin(self.master)
        self.master.run_command(
            ['ipa', 'krbtpolicy-mod', '--maxlife', str(MAXLIFE)]
        )
        tasks.kdestroy_all(self.master)
        self.master.run_command(
            ['find', paths.IPA_CCACHES, '-type', 'f', '-delete']
        )
        for _i in range(5):
            tasks.kinit_admin(self.master)
            self.master.run_command(['ipa', 'user-show', 'admin'])
            tasks.kdestroy_all(self.master)

        result = self.master.run_command(
            "ls -1 {0} | wc -l".format(paths.IPA_CCACHES)
        )
        assert int(result.stdout_text.strip()) == 5

        # let ccache expire
        time.sleep(MAXLIFE)
        ccache_sweep_cmd = ["/usr/libexec/ipa/ipa-ccache-sweeper", "-m", "0"]

        # should be run as ipaapi for GSSProxy
        self.master.run_command(
            ["runuser", "-u", IPAAPI_USER, "--"] + ccache_sweep_cmd
        )

        result = self.master.run_command(
            "ls -1 {0} | wc -l".format(paths.IPA_CCACHES)
        )
        assert int(result.stdout_text.strip()) == 0
示例#33
0
    def test_establish_nonexternal_treedomain_trust(self):
        tasks.configure_dns_for_trust(self.master, self.ad, self.tree_ad)
        try:
            tasks.kinit_admin(self.master)

            result = self.master.run_command(
                [
                    'ipa', 'trust-add', '--type', 'ad', self.ad_treedomain,
                    '--admin', 'Administrator', '--password', '--range-type',
                    'ipa-ad-trust'
                ],
                stdin_text=self.master.config.ad_admin_password,
                raiseonerr=False)

            assert result != 0
            assert ("Domain '{0}' is not a root domain".format(
                self.ad_treedomain) in result.stderr_text)
        finally:
            tasks.unconfigure_dns_for_trust(self.master, self.ad, self.tree_ad)
    def test_aes_sha_kerberos_enctypes(self):
        """Test AES SHA 256 and 384 Kerberos enctypes enabled

        AES SHA 256 and 384-bit enctypes supported by MIT kerberos but
        was not enabled in IPA. This test is to check if these types are
        enabled.

        related: https://pagure.io/freeipa/issue/8110
        """
        tasks.kinit_admin(self.master)
        dn = DN(("cn", self.master.domain.realm), ("cn", "kerberos"),
                realm_to_suffix(self.master.domain.realm))
        result = tasks.ldapsearch_dm(self.master,
                                     str(dn), ["krbSupportedEncSaltTypes"],
                                     scope="base")
        assert "aes128-sha2:normal" in result.stdout_text
        assert "aes128-sha2:special" in result.stdout_text
        assert "aes256-sha2:normal" in result.stdout_text
        assert "aes256-sha2:special" in result.stdout_text
示例#35
0
    def test_certmap_match_issue7520(self):
        # https://pagure.io/freeipa/issue/7520
        tasks.kinit_admin(self.master)
        result = self.master.run_command(
            ['ipa', 'certmap-match', paths.IPA_CA_CRT],
            raiseonerr=False
        )
        assert result.returncode == 1
        assert not result.stderr_text
        assert "0 users matched" in result.stdout_text

        cab64 = self.get_cert_base64(self.master, paths.IPA_CA_CRT)
        result = self.master.run_command(
            ['ipa', 'certmap-match', '--certificate', cab64],
            raiseonerr=False
        )
        assert result.returncode == 1
        assert not result.stderr_text
        assert "0 users matched" in result.stdout_text
示例#36
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])
示例#37
0
    def _full_backup_and_restore_with_DNSSEC_zone(self, reinstall=False):
        with restore_checker(self.master):
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example_test_zone,
                '--dnssec', 'true',
            ])

            assert (
                wait_until_record_is_signed(
                    self.master.ip, self.example_test_zone)
            ), "Zone is not signed"

            backup_path = backup(self.master)

            self.master.run_command(['ipa-server-install',
                                     '--uninstall',
                                     '-U'])

            if reinstall:
                tasks.install_master(self.master, setup_dns=True)

            dirman_password = self.master.config.dirman_password
            self.master.run_command(['ipa-restore', backup_path],
                                    stdin_text=dirman_password + '\nyes')

            assert (
                wait_until_record_is_signed(
                    self.master.ip, self.example_test_zone)
            ), "Zone is not signed after restore"

            tasks.kinit_admin(self.master)
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example2_test_zone,
                '--dnssec', 'true',
            ])

            assert (
                wait_until_record_is_signed(
                    self.master.ip, self.example2_test_zone)
            ), "A new zone is not signed"
示例#38
0
 def test_auth_sudo_idp(self):
     """
     Test case to check that sudorule is working as
     expected for user configured with external idp.
     """
     tasks.kdestroy_all(self.master)
     tasks.kinit_admin(self.master)
     #  rule: keycloakuser are allowed to execute yum on
     #  the client machine as root.
     cmdlist = [
         ["ipa", "sudocmd-add", "/usr/bin/yum"],
         ["ipa", "sudorule-add", "sudorule"],
         ['ipa', 'sudorule-add-user', '--users=keycloakuser',
          'sudorule'],
         ['ipa', 'sudorule-add-host', '--hosts',
          self.client.hostname, 'sudorule'],
         ['ipa', 'sudorule-add-runasuser',
          '--users=root', 'sudorule'],
         ['ipa', 'sudorule-add-allow-command',
          '--sudocmds=/usr/bin/yum', 'sudorule'],
         ['ipa', 'sudorule-show', 'sudorule', '--all'],
         ['ipa', 'sudorule-add-option',
          'sudorule', '--sudooption', "!authenticate"]
     ]
     for cmd in cmdlist:
         self.master.run_command(cmd)
     tasks.clear_sssd_cache(self.master)
     tasks.clear_sssd_cache(self.client)
     try:
         cmd = 'sudo -ll -U keycloakuser'
         test = self.client.run_command(cmd).stdout_text
         assert "User keycloakuser may run the following commands" in test
         assert "/usr/bin/yum" in test
         kinit_idp(self.client, 'keycloakuser', self.client)
         test_sudo = 'su -c "sudo yum list wget" keycloakuser'
         self.client.run_command(test_sudo)
         list_fail = self.master.run_command(cmd).stdout_text
         assert "User keycloakuser is not allowed to run sudo" in list_fail
     finally:
         tasks.kinit_admin(self.master)
         self.master.run_command(['ipa', 'sudorule-del', 'sudorule'])
         self.master.run_command(["ipa", "sudocmd-del", "/usr/bin/yum"])
示例#39
0
    def test_ipa_getcert_san_aci(self):
        """Test for DNS and IP SAN extensions + ACIs
        """
        hostname = self.clients[0].hostname
        certfile = '/etc/pki/tls/certs/test2.pem'

        tasks.kinit_admin(self.master)
        name, zone = hostname.split('.', 1)
        self.master.run_command(['ipa', 'dnsrecord-show', zone, name])
        tasks.kdestroy_all(self.master)

        cmd_arg = [
            'ipa-getcert',
            'request',
            '-v',
            '-w',
            '-f',
            certfile,
            '-k',
            '/etc/pki/tls/private/test2.key',
            '-K',
            f'test/{hostname}',
            '-D',
            hostname,
            '-A',
            self.clients[0].ip,
        ]
        result = self.clients[0].run_command(cmd_arg)
        request_id = re.findall(r'\d+', result.stdout_text)

        # check if certificate is in MONITORING state
        status = tasks.wait_for_request(self.clients[0], request_id[0], 50)
        assert status == "MONITORING"

        certdata = self.clients[0].get_file_contents(certfile)
        cert = x509.load_pem_x509_certificate(certdata, default_backend())
        ext = cert.extensions.get_extension_for_oid(
            ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
        dnsnames = ext.value.get_values_for_type(x509.DNSName)
        assert dnsnames == [self.clients[0].hostname]
        ipaddrs = ext.value.get_values_for_type(x509.IPAddress)
        assert ipaddrs == [ipaddress.ip_address(self.clients[0].ip)]
示例#40
0
    def _full_backup_restore_with_DNS_zone(self, reinstall=False):
        """backup, uninstall, restore.

        Test for bug https://pagure.io/freeipa/issue/7630.
        """
        with restore_checker(self.master):
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example_test_zone,
            ])

            tasks.resolve_record(self.master.ip, self.example_test_zone)

            backup_path = tasks.get_backup_dir(self.master)

            self.master.run_command(['ipa-server-install',
                                     '--uninstall',
                                     '-U'])

            tasks.uninstall_packages(self.master, ['*ipa-server-dns'])

            dirman_password = self.master.config.dirman_password
            result = self.master.run_command(
                ['ipa-restore', backup_path],
                stdin_text=dirman_password + '\nyes',
                raiseonerr=False)
            assert 'Please install the package' in result.stderr_text

            tasks.install_packages(self.master, ['*ipa-server-dns'])
            if reinstall:
                tasks.install_master(self.master, setup_dns=True)
            self.master.run_command(['ipa-restore', backup_path],
                                    stdin_text=dirman_password + '\nyes')
            tasks.resolve_record(self.master.ip, self.example_test_zone)

            tasks.kinit_admin(self.master)
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example2_test_zone,
            ])

            tasks.resolve_record(self.master.ip, self.example2_test_zone)
示例#41
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"])
示例#42
0
    def _full_backup_and_restore_with_DNSSEC_zone(self, reinstall=False):
        with restore_checker(self.master):
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example_test_zone,
                '--dnssec', 'true',
            ])

            assert (
                wait_until_record_is_signed(
                    self.master.ip, self.example_test_zone)
            ), "Zone is not signed"

            backup_path = tasks.get_backup_dir(self.master)

            self.master.run_command(['ipa-server-install',
                                     '--uninstall',
                                     '-U'])

            if reinstall:
                tasks.install_master(self.master, setup_dns=True)

            dirman_password = self.master.config.dirman_password
            self.master.run_command(['ipa-restore', backup_path],
                                    stdin_text=dirman_password + '\nyes')

            assert (
                wait_until_record_is_signed(
                    self.master.ip, self.example_test_zone)
            ), "Zone is not signed after restore"

            tasks.kinit_admin(self.master)
            self.master.run_command([
                'ipa', 'dnszone-add',
                self.example2_test_zone,
                '--dnssec', 'true',
            ])

            assert (
                wait_until_record_is_signed(
                    self.master.ip, self.example2_test_zone)
            ), "A new zone is not signed"
示例#43
0
 def install(cls, mh):
     cls.username = '******'
     tasks.install_master(cls.master, domain_level=cls.domain_level)
     password = cls.master.config.dirman_password
     cls.new_password = '******'
     adduser_stdin_text = "%s\n%s\n" % (cls.master.config.admin_password,
                                        cls.master.config.admin_password)
     user_kinit_stdin_text = "%s\n%s\n%s\n" % (password, cls.new_password,
                                               cls.new_password)
     tasks.kinit_admin(cls.master)
     cls.master.run_command([
         'ipa', 'user-add', cls.username, '--password', '--first', 'John',
         '--last', 'Donn'
     ],
                            stdin_text=adduser_stdin_text)
     # Now we need to change the password for the user
     cls.master.run_command(['kinit', cls.username],
                            stdin_text=user_kinit_stdin_text)
     # And again kinit admin
     tasks.kinit_admin(cls.master)
示例#44
0
    def test_hidden_replica_backup_and_restore(self):
        """Exercises backup+restore and hidden replica uninstall
        """
        self._check_server_role(self.replicas[0], 'hidden')
        # backup
        backup_path = tasks.get_backup_dir(self.replicas[0])
        # uninstall
        tasks.uninstall_master(self.replicas[0])
        # restore
        dirman_password = self.master.config.dirman_password
        self.replicas[0].run_command(['ipa-restore', backup_path],
                                     stdin_text=dirman_password + '\nyes')

        tasks.kinit_admin(self.master)
        tasks.kinit_admin(self.replicas[0])

        # restore turns a hidden replica into an enabled replica
        # https://pagure.io/freeipa/issue/7894
        self._check_config([self.master, self.replicas[0]])
        self._check_server_role(self.replicas[0], 'enabled')
示例#45
0
    def test_hidden_replica_backup_and_restore(self):
        """Exercises backup+restore and hidden replica uninstall
        """
        self._check_server_role(self.replicas[0], 'hidden')
        # backup
        backup_path = backup(self.replicas[0])
        # uninstall
        tasks.uninstall_master(self.replicas[0])
        # restore
        dirman_password = self.master.config.dirman_password
        self.replicas[0].run_command(['ipa-restore', backup_path],
                                     stdin_text=dirman_password + '\nyes')

        # give replication some time
        time.sleep(5)
        tasks.kinit_admin(self.replicas[0])

        # FIXME: restore turns hidden replica into enabled replica
        self._check_config([self.master, self.replicas[0]])
        self._check_server_role(self.replicas[0], 'enabled')
示例#46
0
    def install(cls, mh):
        super(TestOTPToken, cls).install(mh)
        master = cls.master

        tasks.kinit_admin(master)
        # create service with OTP auth indicator
        cls.service_name = f"otponly/{master.hostname}"
        master.run_command(
            ["ipa", "service-add", cls.service_name, "--auth-ind=otp"]
        )
        # service needs a keytab before user can acquire a ticket for it
        keytab = "/tmp/otponly.keytab"
        master.run_command(
            ["ipa-getkeytab", "-p", cls.service_name, "-k", keytab]
        )
        master.run_command(["rm", "-f", keytab])

        tasks.create_active_user(master, USER, PASSWORD)
        tasks.kinit_admin(master)
        master.run_command(["ipa", "user-mod", USER, "--user-auth-type=otp"])
示例#47
0
    def test_establish_trust(self):
        """ Tests establishing non-external trust with Active Directory """
        self.master.run_command(['kinit', '-kt', paths.HTTP_KEYTAB,
                                 'HTTP/%s' % self.master.hostname])
        self.master.run_command(['systemctl', 'restart', 'krb5kdc.service'])
        self.master.run_command(['kdestroy', '-A'])

        tasks.kinit_admin(self.master)
        self.master.run_command(['klist'])
        self.master.run_command(['smbcontrol', 'all', 'debug', '100'])

        result = self.master.run_command([
            'ipa', 'trust-add', '--type', 'ad', self.ad_treedomain, '--admin',
            'Administrator', '--password', '--range-type', 'ipa-ad-trust'
            ], stdin_text=self.master.config.ad_admin_password,
            raiseonerr=False)

        assert result != 0
        assert ("Domain '{0}' is not a root domain".format(
            self.ad_treedomain) in result.stderr_text)
示例#48
0
    def test_password_login_as_aduser(self):
        """Test if AD user can login with password to Web UI"""
        ad_admin = 'Administrator@%s' % self.ad_domain

        tasks.kdestroy_all(self.master)
        user_and_password = ('user=%s&password=%s' %
                             (ad_admin, self.master.config.ad_admin_password))
        host = self.master.hostname
        cmd_args = [
            paths.BIN_CURL,
            '-v',
            '-H', 'referer:https://{}/ipa'.format(host),
            '-H', 'Content-Type:application/x-www-form-urlencoded',
            '-H', 'Accept:text/plain',
            '--cacert', paths.IPA_CA_CRT,
            '--data', user_and_password,
            'https://{}/ipa/session/login_password'.format(host)]
        result = self.master.run_command(cmd_args)
        assert "Set-Cookie: ipa_session=MagBearerToken" in result.stderr_text
        tasks.kinit_admin(self.master)
示例#49
0
    def test_cert_find_issue7520(self):
        # https://pagure.io/freeipa/issue/7520
        tasks.kinit_admin(self.master)
        subject = 'CN=Certificate Authority,O={}'.format(
            self.master.domain.realm)

        # by cert file
        result = self.master.run_command(
            ['ipa', 'cert-find', '--file', paths.IPA_CA_CRT]
        )
        assert subject in result.stdout_text
        assert '1 certificate matched' in result.stdout_text

        # by base64 cert
        cab64 = self.get_cert_base64(self.master, paths.IPA_CA_CRT)
        result = self.master.run_command(
            ['ipa', 'cert-find', '--certificate', cab64]
        )
        assert subject in result.stdout_text
        assert '1 certificate matched' in result.stdout_text
示例#50
0
    def test_sudorules_ad_groups(self):
        """Verify trusted domain groups can be added to sudorules"""

        tasks.kdestroy_all(self.master)
        tasks.kinit_admin(self.master)

        testuser = '******' % (self.master.config.ad_admin_name, self.ad_domain)
        testgroup = 'Enterprise Admins@%s' % self.ad_domain
        expected = "(root) NOPASSWD: ALL"
        with self.check_sudorules_for("group", testuser, testuser,
                                      expected) as sudorule:
            # Remove the user and instead add a group
            self.master.run_command([
                'ipa', 'sudorule-remove-user', sudorule.name, '--users',
                sudorule.user
            ])
            self.master.run_command([
                'ipa', 'sudorule-add-user', sudorule.name, '--groups',
                testgroup
            ])
 def test_replica_after_domain_upgrade(self):
     tasks.kinit_admin(self.master)
     tasks.kinit_admin(self.replicas[0])
     self.master.run_command([
         'ipa', 'user-add', self.username, '--first', 'test', '--last',
         'user'
     ])
     tasks.wait_for_replication(self.replicas[0].ldap_connect())
     self.master.run_command(
         ['ipa', 'domainlevel-set',
          str(DOMAIN_LEVEL_1)])
     result = self.replicas[0].run_command(
         ['ipa', 'user-show', self.username])
     assert ("User login: %s" % self.username in result.stdout_text), (
         "A testuser was not found on replica after domain upgrade")
     self.replicas[0].run_command(['ipa', 'user-del', self.username])
     tasks.wait_for_replication(self.master.ldap_connect())
     result1 = self.master.run_command(['ipa', 'user-show', self.username],
                                       raiseonerr=False)
     assert_error(result1, "%s: user not found" % self.username, 2)
示例#52
0
    def test_external_group_member_mismatch(self, user_origin):
        """Prevent adding IPA objects as external group external members

        External groups must only allow adding non-IPA objects as external
        members in 'ipa group-add-member foo --external bar'.
        """
        master = self.master
        tasks.clear_sssd_cache(master)
        tasks.kinit_admin(master)
        master.run_command(['ipa', 'group-add', '--external', 'ext-ipatest'])
        try:
            master.run_command([
                'ipa', '-n', 'group-add-member', 'ext-ipatest', '--external',
                self.users[user_origin]['name']
            ])
        except subprocess.CalledProcessError:
            # Only 'ipa' origin should throw a validation error
            assert user_origin == 'ipa'
        finally:
            master.run_command(['ipa', 'group-del', 'ext-ipatest'])
示例#53
0
    def test_cert_find_issue7520(self):
        # https://pagure.io/freeipa/issue/7520
        tasks.kinit_admin(self.master)
        subject = 'CN=Certificate Authority,O={}'.format(
            self.master.domain.realm)

        # by cert file
        result = self.master.run_command(
            ['ipa', 'cert-find', '--file', paths.IPA_CA_CRT]
        )
        assert subject in result.stdout_text
        assert '1 certificate matched' in result.stdout_text

        # by base64 cert
        cab64 = self.get_cert_base64(self.master, paths.IPA_CA_CRT)
        result = self.master.run_command(
            ['ipa', 'cert-find', '--certificate', cab64]
        )
        assert subject in result.stdout_text
        assert '1 certificate matched' in result.stdout_text
示例#54
0
 def test_topology_updated_on_replica_install_remove(self):
     """
     Install and remove a replica and make sure topology information is
     updated on all other replicas
     Testcase: http://www.freeipa.org/page/V4/Manage_replication_topology/
     Test_plan#Test_case:
     _Replication_topology_should_be_saved_in_the_LDAP_tree
     """
     tasks.kinit_admin(self.master)
     result1 = self.master.run_command(['ipa', 'topologysegment-find',
                                        DOMAIN_SUFFIX_NAME]).stdout_text
     segment_name = self.segmentnames_re.findall(result1)[0]
     assert(self.master.hostname in segment_name), (
         "Segment %s does not contain master hostname" % segment_name)
     assert(self.replicas[0].hostname in segment_name), (
         "Segment %s does not contain replica hostname" % segment_name)
     tasks.install_replica(self.master, self.replicas[1], setup_ca=False,
                           setup_dns=False)
     # We need to make sure topology information is consistent across all
     # replicas
     result2 = self.master.run_command(['ipa', 'topologysegment-find',
                                        DOMAIN_SUFFIX_NAME])
     result3 = self.replicas[0].run_command(['ipa', 'topologysegment-find',
                                             DOMAIN_SUFFIX_NAME])
     result4 = self.replicas[1].run_command(['ipa', 'topologysegment-find',
                                             DOMAIN_SUFFIX_NAME])
     segments = self.tokenize_topologies(result2.stdout_text)
     assert(len(segments) == 2), "Unexpected number of segments found"
     assert_deepequal(result2.stdout_text, result3.stdout_text)
     assert_deepequal(result3.stdout_text,  result4.stdout_text)
     # Now let's check that uninstalling the replica will update the topology
     # info on the rest of replicas.
     # first step of uninstallation is removal of the replica on other
     # master, then it can be uninstalled. Doing it the other way is also
     # possible, but not reliable - some data might not be replicated.
     tasks.clean_replication_agreement(self.master, self.replicas[1])
     tasks.uninstall_master(self.replicas[1])
     result5 = self.master.run_command(['ipa', 'topologysegment-find',
                                        DOMAIN_SUFFIX_NAME])
     num_entries = self.noentries_re.search(result5.stdout_text).group(1)
     assert(num_entries == "1"), "Incorrect number of entries displayed"
示例#55
0
 def test_krbtpolicy_otp(self):
     """Test otp ticket policy"""
     master = self.master
     tasks.kinit_admin(self.master)
     master.run_command(['ipa', 'user-mod', USER1,
                         '--user-auth-type', 'otp'])
     master.run_command(['ipa', 'config-mod',
                         '--user-auth-type', 'otp'])
     master.run_command(['ipa', 'krbtpolicy-mod', USER1,
                         '--otp-maxrenew=90', '--otp-maxlife=60'])
     armor = tasks.create_temp_file(self.master, create_file=False)
     otpuid, totp = add_otptoken(master, USER1, otptype="totp")
     otpvalue = totp.generate(int(time.time())).decode("ascii")
     try:
         tasks.kdestroy_all(master)
         # create armor for FAST
         master.run_command(['kinit', '-n', '-c', armor])
         # expect ticket expire in otp-maxlife=60 seconds
         master.run_command(
             ['kinit', '-T', armor, USER1, '-r', '90'],
             stdin_text='{0}{1}\n'.format(PASSWORD, otpvalue))
         master.run_command(['ipa', 'user-find', USER1])
         time.sleep(30)
         # when user kerberos ticket expired but still within renew time,
         #  kinit -R should give user new life
         master.run_command(['kinit', '-R', USER1])
         master.run_command(['ipa', 'user-find', USER1])
         time.sleep(60)
         # when renew time expires, kinit -R should fail
         result1 = master.run_command(['kinit', '-R', USER1],
                                      raiseonerr=False)
         tasks.assert_error(
             result1,
             "kinit: Ticket expired while renewing credentials", 1)
         master.run_command(['ipa', 'user-find', USER1],
                            ok_returncode=1)
     finally:
         del_otptoken(master, otpuid)
         reset_to_default_policy(master, USER1)
         self.master.run_command(['rm', '-f', armor])
         master.run_command(['ipa', 'config-mod', '--user-auth-type='])
示例#56
0
    def nested_group_setup(self, tmpdir):
        """Setup and Clean up groups and user created"""
        master = self.master
        client = self.clients[0]

        # add a user and set password
        tasks.create_active_user(master, self.username, self.userpasswd)
        tasks.kinit_admin(master)

        privkey, pubkey = tasks.generate_ssh_keypair()
        with open(os.path.join(tmpdir, 'ssh_priv_key'), 'w') as fp:
            fp.write(privkey)

        master.run_command(
            ['ipa', 'user-mod', self.username, '--ssh', "{}".format(pubkey)])

        master.put_file_contents('/tmp/user_ssh_priv_key', privkey)
        master.run_command(['chmod', '600', '/tmp/user_ssh_priv_key'])

        # add group groupa
        cmd_output = master.run_command(['ipa', 'group-add', 'groupa'])
        assert 'Added group "groupa"' in cmd_output.stdout_text

        # add group groupb
        cmd_output = master.run_command(['ipa', 'group-add', 'groupb'])
        assert 'Added group "groupb"' in cmd_output.stdout_text

        # add group groupc
        cmd_output = master.run_command(['ipa', 'group-add', 'groupc'])
        assert 'Added group "groupc"' in cmd_output.stdout_text

        client.put_file_contents('/tmp/user_ssh_priv_key', privkey)
        client.run_command(['chmod', '600', '/tmp/user_ssh_priv_key'])
        yield
        # test cleanup
        for group in ['groupa', 'groupb', 'groupc']:
            self.master.run_command(['ipa', 'group-del', group, '--continue'])
        self.master.run_command(
            ['ipa', 'user-del', self.username, '--no-preserve', '--continue'])
        tasks.kdestroy_all(self.master)
        tasks.kdestroy_all(self.clients[0])
示例#57
0
    def test_user_add_withradius(self):
        """
        Test that a user with User Administrator role can call
        ipa user-add --radius myradius
        to create a user with an assigned Radius Proxy Server.

        This is a test case for issue 7570
        """
        # kinit admin
        tasks.kinit_admin(self.master)

        # Create a radius proxy server
        radiusproxy = 'myradius'
        secret = 'Secret123'
        radius_secret_confirmation = "%s\n%s\n" % (secret, secret)
        self.master.run_command(
            ['ipa', 'radiusproxy-add', radiusproxy,
             '--server', 'radius.example.com', '--secret'],
            stdin_text=radius_secret_confirmation)

        # Create a user with 'User Administrator' role
        altuser = '******'
        password = '******'
        password_confirmation = "%s\n%s\n" % (password, password)
        self.master.run_command(
            ['ipa', 'user-add', altuser, '--first', altuser, '--last', altuser,
             '--password'],
            stdin_text=password_confirmation)
        self.master.run_command(
            ['ipa', 'role-add-member', "User Administrator",
             '--user', altuser])

        # kinit as altuser to initialize the password
        altuser_kinit = "%s\n%s\n%s\n" % (password, password, password)
        self.master.run_command(['kinit', altuser], stdin_text=altuser_kinit)
        # call ipa user-add with --radius=...
        # this call requires read access to radius proxy servers
        self.master.run_command(
            ['ipa', 'user-add', '--first', 'test', '--last', 'test',
             '--user-auth-type', 'radius', '--radius-username', 'testradius',
             'testradius', '--radius', radiusproxy])
示例#58
0
    def test_find_by_member_manager(self):
        master = self.master
        tasks.kinit_admin(master)

        result = master.run_command([
            'ipa', 'group-find', '--membermanager-users', USER_MM
        ])
        assert GROUP1 in result.stdout_text

        result = master.run_command([
            'ipa', 'group-find', '--membermanager-groups', GROUP_INDIRECT
        ])
        assert GROUP1 in result.stdout_text

        result = master.run_command(
            [
                'ipa', 'group-find', '--membermanager-users', USER1
            ],
            raiseonerr=False
        )
        assert result.returncode == 1
        assert "0 groups matched" in result.stdout_text

        result = master.run_command([
            'ipa', 'hostgroup-find', '--membermanager-users', USER_MM
        ])
        assert HOSTGROUP1 in result.stdout_text

        result = master.run_command([
            'ipa', 'hostgroup-find', '--membermanager-groups', GROUP_INDIRECT
        ])
        assert HOSTGROUP1 in result.stdout_text

        result = master.run_command(
            [
                'ipa', 'hostgroup-find', '--membermanager-users', USER1
            ],
            raiseonerr=False
        )
        assert result.returncode == 1
        assert "0 hostgroups matched" in result.stdout_text
示例#59
0
    def test_fake_mname_param(self):
        """Test that fake_mname param is set using dnsserver-mod option.

        Test for BZ 1488732 which checks that  --soa-mname-override option
        from dnsserver-mod sets the fake_mname.
        """
        tasks.kinit_admin(self.master)
        self.master.run_command(['ipa', 'dnsserver-mod', self.master.hostname,
                                 '--soa-mname-override', 'fake'])
        tasks.restart_named(self.master)
        cmd = self.master.run_command(['dig', '+short', '-t', 'SOA',
                                       self.master.domain.name])
        assert 'fake' in cmd.stdout_text

        # reverting the fake_mname change to check it is reverted correctly
        self.master.run_command(['ipa', 'dnsserver-mod', self.master.hostname,
                                 '--soa-mname-override', ''])
        tasks.restart_named(self.master)
        cmd = self.master.run_command(['dig', '+short', '-t', 'SOA',
                                       self.master.domain.name])
        assert 'fake' not in cmd.stdout_text
示例#60
0
    def test_selinux_user_optimized(self):
        """
        Check that SELinux login context is set on first login for the
        user, even if the user is not mapped to a specific SELinux user.

        Related ticket https://pagure.io/SSSD/sssd/issue/3819.
        """
        # Scenario: add an IPA user with non-default home dir, login through
        # ssh as this user and check that there is a SELinux user mapping
        # for the user with `semanage login -l`.

        # kinit admin
        tasks.kinit_admin(self.master)

        testuser = '******'
        password = '******'
        testuser_password_confirmation = "%s\n%s\n" % (password,
                                                       password)
        self.master.run_command(['ipa', 'user-add', testuser,
                                 '--first', testuser,
                                 '--last', testuser,
                                 '--password',
                                 '--homedir',
                                 '/root/{}'.format(testuser)],
                                stdin_text=testuser_password_confirmation)

        # login to the system
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(self.master.hostname,
                       username=testuser,
                       password=password)
        client.close()

        # check if user listed in output
        cmd = self.master.run_command(['semanage', 'login', '-l'])
        assert testuser in cmd.stdout_text

        # call ipa user-del
        self.master.run_command(['ipa', 'user-del', testuser])