URL: https://github.com/SSSD/sssd/pull/651
Author: mrniranjan
 Title: #651: test-library:  fixes related to KCM, TLS on Directory server
Action: opened

PR body:
"""
Fixes related to enabling of ssl in Directory Server
Minor fixes on KCM, adding new exceptions

Signed-off-by: Niranjan M.R <mrniran...@redhat.com>
"""

To pull the PR as Git branch:
git remote add ghsssd https://github.com/SSSD/sssd
git fetch ghsssd pull/651/head:pr651
git checkout pr651
From 7a9c84626c3f0301d432e73e06a447b3c89c6386 Mon Sep 17 00:00:00 2001
From: "Niranjan M.R" <mrniran...@redhat.com>
Date: Tue, 11 Sep 2018 17:54:16 +0530
Subject: [PATCH] test-library:  fixes related to KCM, TLS on Directory server

Fixes related to enabling of ssl in Directory Server
Minor fixes on KCM, adding new exceptions

Signed-off-by: Niranjan M.R <mrniran...@redhat.com>
---
 .../python/sssd/testlib/common/exceptions.py  |  6 ++
 .../python/sssd/testlib/common/libdirsrv.py   | 90 +++++++++++++------
 .../python/sssd/testlib/common/qe_class.py    |  9 +-
 src/tests/python/sssd/testlib/common/utils.py | 80 ++++++++++-------
 4 files changed, 122 insertions(+), 63 deletions(-)

diff --git a/src/tests/python/sssd/testlib/common/exceptions.py b/src/tests/python/sssd/testlib/common/exceptions.py
index 1839a5910..c28a39ba2 100644
--- a/src/tests/python/sssd/testlib/common/exceptions.py
+++ b/src/tests/python/sssd/testlib/common/exceptions.py
@@ -54,3 +54,9 @@ class RPMException(StandardException):
     """
     Override StandardException, This exception is to be used for RPM Errors
     """
+
+
+class SSSDException(StandardException):
+    """
+     Override StandardException, This exception is to be used for SSSD Errors
+    """
diff --git a/src/tests/python/sssd/testlib/common/libdirsrv.py b/src/tests/python/sssd/testlib/common/libdirsrv.py
index 4ace65f86..5c3927f7e 100644
--- a/src/tests/python/sssd/testlib/common/libdirsrv.py
+++ b/src/tests/python/sssd/testlib/common/libdirsrv.py
@@ -125,6 +125,50 @@ def remove_ds(self, inst_name=None):
         except subprocess.CalledProcessError:
             raise
 
+    def _copy_pkcs12(self, ssl_dir):
+        """ Copy the pkcs12 files from ssl_dir to
+        DS instance directory """
+
+        nss_db_files = ['ca.p12', 'server.p12', 'pin.txt', 'pwfile']
+        for db_file in nss_db_files:
+            source = os.path.join(ssl_dir, db_file)
+            destination = os.path.join(self.dsinst_path, db_file)
+            self.multihost.transport.put_file(source, destination)
+        for db_file in nss_db_files:
+            ls_cmd = 'ls %s/%s' % (self.dsinst_path, db_file)
+            cmd = self.multihost.run_command(ls_cmd)
+            if cmd.returncode != 0:
+                return False
+        return True
+
+    def _import_certs(self, pkcs12_path, pwfile):
+        """ Import the certs from pkcs12 """
+        pk12_cmd = 'pk12util -i %s -d %s -k %s'\
+                   ' -w %s' % (pkcs12_path, self.dsinst_path, pwfile, pwfile)
+        cmd = self.multihost.run_command(pk12_cmd)
+        if cmd.returncode == 0:
+            return True
+
+    def _set_dsperms(self, file_path):
+        """ Set DSUSER permissions on files """
+        change_ownership = ['chown', DS_USER, file_path]
+        change_group = ['chgrp', DS_GROUP, file_path]
+        chmod_file = ['chmod', '600', file_path]
+        try:
+            self.multihost.run_command(change_ownership)
+        except subprocess.CalledProcessError:
+            raise DirSrvException(
+                'fail to user change ownership of pin.txt fail')
+        try:
+            self.multihost.run_command(change_group)
+        except subprocess.CalledProcessError:
+            raise DirSrvException(
+                'fail to change group ownership of pin.txt file')
+        try:
+            self.multihost.run_command(chmod_file)
+        except subprocess.CalledProcessError:
+            raise DirSrvException('fail to change permissions of pin.txt file')
+
     def setup_certs(self, ssl_dir):
         """copy CA and Server certs to all DS instances.
 
@@ -145,39 +189,35 @@ def setup_certs(self, ssl_dir):
         try:
             self.multihost.run_command(stop_ds)
         except subprocess.CalledProcessError:
-            return True
+            raise DirSrvException("Unable to stop Directory Server instance")
         else:
             self.multihost.log.info('DS instance stopped successfully')
-        nss_db_files = ['cert9.db', 'key4.db', 'pin.txt']
-        dirsrv_cert_path = '/etc/dirsrv/' + self.ds_inst_name + '/cacert.pem'
+            self._copy_pkcs12(ssl_dir)
         cacert_file_path = '%s/cacert.pem' % ('/etc/openldap/cacerts')
-        for db_file in nss_db_files:
-            source = os.path.join(ssl_dir, db_file)
-            destination = os.path.join(self.dsinst_path, db_file)
-            self.multihost.transport.put_file(source, destination)
         target_pin_file = os.path.join(self.dsinst_path, 'pin.txt')
-        change_ownership = ['chown', DS_USER, target_pin_file]
-        change_group = ['chgrp', DS_GROUP, target_pin_file]
-        chmod_file = ['chmod', '600', target_pin_file]
-        # copy the cacert file to test_dir
+        pwfile = os.path.join(self.dsinst_path, 'pwfile')
+        ca_p12 = os.path.join(self.dsinst_path, 'ca.p12')
+        server_p12 = os.path.join(self.dsinst_path, 'server.p12')
+        # recreate the database
+        certutil_cmd = 'certutil -N -d %s -f %s' % (self.dsinst_path, pwfile)
+        self.multihost.run_command(certutil_cmd)
         create_cert_dir = 'mkdir -p /etc/openldap/cacerts'
+        # recreate the database
         self.multihost.run_command(create_cert_dir)
+        pkcs12_file = [ca_p12, server_p12]
+        for pkcs_file in pkcs12_file:
+            if not self._import_certs(pkcs_file, pwfile):
+                raise DirSrvException("importing certificates failed")
+        set_trust_cmd = 'certutil -M -d %s -n "Example CA"'\
+                        ' -t "CTu,u,u" -f %s' % (self.dsinst_path, pwfile)
+        self.multihost.run_command(create_cert_dir)
+        self.multihost.run_command(set_trust_cmd)
         self.multihost.transport.put_file(os.path.join(
             ssl_dir, 'cacert.pem'), cacert_file_path)
         try:
-            self.multihost.run_command(change_ownership)
-        except subprocess.CalledProcessError:
-            raise DirSrvException(
-                'fail to user change ownership of pin.txt fail')
-        try:
-            self.multihost.run_command(change_group)
-        except subprocess.CalledProcessError:
-            raise DirSrvException(
-                'fail to change group ownership of pin.txt file')
-        try:
-            self.multihost.run_command(chmod_file)
-        except subprocess.CalledProcessError:
-            raise DirSrvException('fail to change permissions of pin.txt file')
+            self._set_dsperms(target_pin_file)
+        except DirSrvException:
+            raise
         start_ds = ['systemctl', 'start', 'dirsrv@%s' % (self.instance_name)]
         try:
             self.multihost.run_command(start_ds)
@@ -185,8 +225,6 @@ def setup_certs(self, ssl_dir):
             raise DirSrvException('Could not Start DS Instance')
         else:
             self.multihost.log.info('DS instance started successfully')
-            ca = self.multihost.get_file_contents(cacert_file_path)
-            self.multihost.transport.put_file_contents(dirsrv_cert_path, ca)
 
     def enable_ssl(self, binduri, tls_port):
         """sets TLS Port and enabled TLS on Directory Server.
diff --git a/src/tests/python/sssd/testlib/common/qe_class.py b/src/tests/python/sssd/testlib/common/qe_class.py
index b2c28d93d..31cd927e7 100644
--- a/src/tests/python/sssd/testlib/common/qe_class.py
+++ b/src/tests/python/sssd/testlib/common/qe_class.py
@@ -4,6 +4,7 @@
 import logging
 import pytest
 import time
+from .exceptions import SSSDException
 
 
 class QeConfig(pytest_multihost.config.Config):
@@ -109,7 +110,7 @@ def service_sssd(self, action):
                 time.sleep(10)
                 return cmd.returncode
             else:
-                raise Exception('Unable to %s sssd' % action, 1)
+                raise SSSDException('Unable to %s sssd' % action, 1)
         elif '7.' or '8.' in self.distro.split()[6]:
             cmd = self.run_command(['systemctl', action, 'sssd'],
                                    raiseonerr=False)
@@ -117,7 +118,7 @@ def service_sssd(self, action):
                 time.sleep(10)
                 return cmd.returncode
             else:
-                raise Exception('Unable to %s sssd' % action, 1)
+                raise SSSDException('Unable to %s sssd' % action, 1)
         elif '6.' in self.distro.split()[6]:
             cmd = self.run_command(['service', 'sssd', action],
                                    raiseonerr=False)
@@ -125,7 +126,7 @@ def service_sssd(self, action):
                 time.sleep(10)
                 return cmd.returncode
             else:
-                raise Exception('Unable to %s sssd' % action, 1)
+                raise SSSDException('Unable to %s sssd' % action, 1)
         elif 'Atomic' in self.distro.split():
             cmd = self.run_command(['systemctl', action, 'sssd'],
                                    raiseonerr=False)
@@ -133,7 +134,7 @@ def service_sssd(self, action):
                 time.sleep(10)
                 return cmd.returncode
             else:
-                raise Exception('Unable to %s sssd' % action, 1)
+                raise SSSDException('Unable to %s sssd' % action, 1)
 
     def yum_install(self, package):
         """ Install packages through yum
diff --git a/src/tests/python/sssd/testlib/common/utils.py b/src/tests/python/sssd/testlib/common/utils.py
index cdc076d3e..5f3596c68 100644
--- a/src/tests/python/sssd/testlib/common/utils.py
+++ b/src/tests/python/sssd/testlib/common/utils.py
@@ -24,6 +24,8 @@
 from ldap import modlist
 from .authconfig import RedHatAuthConfig
 from .exceptions import PkiLibException
+from .exceptions import LdapException
+from .exceptions import OSException
 
 
 PARAMIKO_VERSION = (int(paramiko.__version__.split('.')[0]),
@@ -46,22 +48,20 @@ def update_resolv_conf(self, ip_addr):
 
             :param str ip_addr: IP Address to be added in resolv.conf
             :return: None
-            :Exception: Raises exception of builtin type Exception
+            :Exception: Raises OSException of builtin type Exception
         """
         self.multihost.log.info("Taking backup of /etc/resolv.conf")
-        output = self.multihost.run_command(['cp', '-f', '/etc/resolv.conf',
-                                             '/etc/resolv.conf.backup'],
-                                            set_env=False, raiseonerr=False)
-        if output.returncode == 0:
-            self.multihost.log.info("/etc/resolv.conf successfully backed up")
-            self.multihost.log.info("Add ip addr %s in resolv.conf" % ip_addr)
-            nameserver = 'nameserver %s\n' % ip_addr
-            contents = self.multihost.get_file_contents('/etc/resolv.conf')
-            if not contents.startswith(nameserver):
-                contents = nameserver + contents.replace(nameserver, '')
-                self.multihost.put_file_contents('/etc/resolv.conf', contents)
+        bkup_cmd = 'cp -f /etc/resolv.conf /etc/resolv.conf.bkup'
+        output = self.multihost.run_command(bkup_cmd, raiseonerr=False)
+        self.multihost.log.info("/etc/resolv.conf successfully backed up")
+        self.multihost.log.info("Add ip addr %s in resolv.conf" % ip_addr)
+        nameserver = 'nameserver %s\n' % ip_addr
+        contents = self.multihost.get_file_contents('/etc/resolv.conf')
+        if not contents.startswith(nameserver):
+            contents = nameserver + contents.replace(nameserver, '')
+            self.multihost.put_file_contents('/etc/resolv.conf', contents)
         else:
-            raise Exception("Updating resolv.conf with ip %s failed" % ip_addr)
+            raise OSException("modifying resolv.conf failed")
 
     def config_authconfig(self, hostname, domainname):
         """ Run authconfig to configure Kerberos and SSSD auth on remote host
@@ -325,7 +325,6 @@ def config_etckrb5(self, realm, krb5_server=None):
             krb5config.set("libdefaults", "default_realm", realm.upper())
             krb5config.set("libdefaults", "dns_lookup_realm", "false")
             krb5config.set("libdefaults", "dns_lookup_kdc", "false")
-            krb5config.set("libdefaults", "allow_weak_crypto", "yes")
             krb5config.set("libdefaults", "forwardable", "true")
             krb5config.set("libdefaults", "rdns", "false")
             krb5config.add_section("realms")
@@ -358,17 +357,21 @@ def enable_kcm(self):
             :Return: None
             :Exception: Raise Exception("message")
         """
-        kcm_cache_file = '/etc/krb5.conf.d/kcm_default_ccache'
-        config = ConfigParser.SafeConfigParser()
-        config.optionxform = str
-        config.add_section('libdefaults')
-        config.set('libdefaults', 'default_ccache_name', "KCM:")
-        temp_fd, temp_file_path = tempfile.mkstemp(suffix='conf',
-                                                   prefix='krb5cc')
-        with open(temp_file_path, 'w') as kcmfile:
-            config.write(kcmfile)
-        self.multihost.transport.put_file(temp_file_path, kcm_cache_file)
-        os.close(temp_fd)
+        self.multihost.transport.get_file('/etc/krb5.conf', '/tmp/krb5.conf')
+        str1 = 'includedir /var/lib/sss/pubconf/krb5.include.d/'
+        str2 = 'includedir /etc/krb5.conf.d/'
+        with open('/tmp/krb5.conf', 'r') as krb_org_file:
+            with open('/tmp/krb5.conf.kcm', 'w+') as krb_new_file:
+                krb_new_file.write(str1)
+                krb_new_file.write('\n')
+                krb_new_file.write(str2)
+                krb_new_file.write('\n')
+                krb_new_file.write('\n')
+                krb_new_file.write(krb_org_file.read())
+        backup_krb5_conf = 'cp -f /etc/krb5.conf /etc/krb5.conf.orig'
+        self.multihost.run_command(backup_krb5_conf)
+        self.multihost.transport.put_file('/tmp/krb5.conf.kcm',
+                                          '/etc/krb5.conf')
         enable_sssd_kcm_socket = 'systemctl enable sssd-kcm.socket'
         cmd = self.multihost.run_command(enable_sssd_kcm_socket,
                                          raiseonerr=False)
@@ -383,8 +386,8 @@ def enable_kcm(self):
                                          raiseonerr=False)
         if cmd.returncode != 0:
             raise Exception("sssd-kcm.socket service not started")
-        start_sssd_kcm_service = 'systemctl enable sssd-kcm.service'
-        cmd = self.multihost.run_command(start_sssd_kcm_service,
+        enable_kcm_service = 'systemctl enable sssd-kcm.service'
+        cmd = self.multihost.run_command(enable_kcm_service,
                                          raiseonerr=False)
         symlink = '/etc/systemd/system/sockets.target.wants/sssd-kcm.socket'
         if cmd.returncode != 0:
@@ -564,7 +567,7 @@ def posix_group(self, org_unit, basedn, group_attr, memberUid=False):
             :param memberUid: set by default to false, True when
              posix group add with memberUid
             :Return bool: Return True
-            :Exception: Raise Exception if unable to add user
+            :Exception: Raise LdapException if unable to add user
         """
         attr = {}
         group_cn = group_attr['cn']
@@ -585,7 +588,7 @@ def posix_group(self, org_unit, basedn, group_attr, memberUid=False):
         group_dn = 'cn=%s,%s,%s' % (group_cn, org_unit, basedn)
         (ret, _) = self.add_entry(attr, group_dn)
         if ret != 'Success':
-            raise Exception('Unable to add group to ldap')
+            raise LdapException('Unable to add group to ldap')
 
     def enable_autofs_schema(self, basedn):
         """ Enable autofs schema
@@ -739,9 +742,10 @@ def createselfsignedcerts(self,
         pin_filename = 'pin.txt'
         nss_dir = self.create_nssdb()
         pin_filepath = os.path.join(nss_dir, pin_filename)
-        ca_certpath = os.path.join(nss_dir, 'cacert.der')
         ca_pempath = os.path.join(nss_dir, 'cacert.pem')
         server_pempath = os.path.join(nss_dir, 'server.pem')
+        ca_p12_path = os.path.join(nss_dir, 'ca.p12')
+        server_p12_path = os.path.join(nss_dir, 'server.p12')
         with open(self.noisefilepath, 'w') as outfile:
             outfile.write(str(self.noise))
         ca_args = 'certutil -d %s -f %s -S -n "%s" -s %s' \
@@ -750,9 +754,8 @@ def createselfsignedcerts(self,
                                            self.noisefilepath)
 
         ca_pem = 'certutil -d %s -f %s -L -n "%s"' \
-                 '-a -o %s' % (nss_dir, self.pwdfilepath,
-                               canickname, ca_pempath)
-
+                 ' -a -o %s' % (nss_dir, self.pwdfilepath,
+                                canickname, ca_pempath)
         with open(pin_filepath, 'w') as outfile:
             outfile.write('Internal (Software) Token:%s' % nss_passphrase)
         _, _, return_code = self.execute(shlex.split(ca_args))
@@ -785,6 +788,17 @@ def createselfsignedcerts(self,
                 _, _, return_code = self.execute(shlex.split(server_pem))
                 if return_code != 0:
                     raise PkiLibException('Could not create Server pem file')
+                export_ca_p12 = 'pk12util -d %s -o %s -n "%s"'\
+                                ' -k %s -w %s' % (nss_dir, ca_p12_path,
+                                                  canickname, self.pwdfilepath,
+                                                  self.pwdfilepath)
+                _, _, return_code = self.execute(shlex.split(export_ca_p12))
+                export_svr_p12 = 'pk12util -d %s -o %s -n %s'\
+                                 ' -k %s -w %s' % (nss_dir, server_p12_path,
+                                                   server_nickname,
+                                                   self.pwdfilepath,
+                                                   self.pwdfilepath)
+                _, _, return_code = self.execute(shlex.split(export_svr_p12))
                 return nss_dir
 
 
_______________________________________________
sssd-devel mailing list -- sssd-devel@lists.fedorahosted.org
To unsubscribe send an email to sssd-devel-le...@lists.fedorahosted.org
Fedora Code of Conduct: https://getfedora.org/code-of-conduct.html
List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines
List Archives: 
https://lists.fedorahosted.org/archives/list/sssd-devel@lists.fedorahosted.org

Reply via email to