def _back_to_local_users(self):
        extra_conf_lines = ''
        if self.sssd_version is not None:
            major, minor, _ = self.pm.parse_version_number(self.sssd_version)

            if major > 1 or (major == 1 and minor > 11):
                extra_conf_lines = '[domain/DEFAULT]\n'
                extra_conf_lines = extra_conf_lines + 'enumerate = TRUE\n'
                extra_conf_lines = extra_conf_lines + 'min_id = 500\n'
                extra_conf_lines = extra_conf_lines + 'max_id = 999\n'
                extra_conf_lines = extra_conf_lines + 'id_provider = local\n'
                extra_conf_lines = extra_conf_lines + 'auth_provider = local\n'
                extra_conf_lines = extra_conf_lines + '\n'

        self.logger.debug('Save /etc/sssd/sssd.conf file')
        # Save /etc/samba/sssd.conf file
        template = Template()
        template.source = get_data_file('templates/sssd.conf.local')
        template.destination = self.main_data_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00600
        template.variables = {'extra_conf_lines': extra_conf_lines}

        if not template.save():
            self.logger.error('Error saving /etc/sssd/sssd.conf file')
            return False
    def save(self, data):
        ''' Saving '''

        self.logger.debug('save - BEGIN')

        if data is None:
            raise ValueError('data is None')

        if not isinstance(data, WorkstationData):
            raise ValueError('data is not a WorkstationData instance')

        if data is None:
            raise ValueError('data is None')

        # Save name to pclabel file
        try:
            fd = open(self.pclabel_file, 'w')
            if fd != None:
                fd.write(data.get_name())
                fd.close()

        except Exception:
            self.logger.error('Error writing file: %s', self.pclabel_file)
            self.logger.error(str(traceback.format_exc()))

        # Do not save OU in GECOS CC at this point!!

        # save node_name to gcc.control file
        jsonUtil = JSONUtil()
        json_data = jsonUtil.loadJSONFromFile(self.gcc_control_file)
        uri_gcc = ''
        gcc_username = ''
        if json_data is not None:
            uri_gcc = json_data['uri_gcc']
            gcc_username = json_data['gcc_username']

        template = Template()
        template.source = get_data_file('templates/gcc.control')
        template.destination = self.gcc_control_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00755
        template.variables = {
            'uri_gcc': uri_gcc,
            'gcc_username': gcc_username,
            'gcc_nodename': data.get_node_name(),
            'ssl_verify': SSLUtil.isSSLCertificatesVerificationEnabled()
        }

        template.save()

        self.logger.debug('save - END')
    def delete(self, data):
        ''' Deleting '''

        self.logger.debug('delete - BEGIN')

        if data is None:
            raise ValueError('data is None')

        if not isinstance(data, WorkstationData):
            raise ValueError('data is not a WorkstationData instance')

        if data.get_name() is None:
            raise ValueError('data.name is None')

        # Remove pclabel_file
        try:
            if os.path.isfile(self.pclabel_file):
                os.remove(self.pclabel_file)

        except Exception:
            self.logger.error('Error removing file: %s', self.pclabel_file)
            self.logger.error(str(traceback.format_exc()))

        # Eliminate node_name from gcc.control file
        jsonUtil = JSONUtil()
        json_data = jsonUtil.loadJSONFromFile(self.gcc_control_file)
        uri_gcc = ''
        gcc_username = ''
        if json_data is not None:
            uri_gcc = json_data['uri_gcc']
            gcc_username = json_data['gcc_username']

        template = Template()
        template.source = get_data_file('templates/gcc.control')
        template.destination = self.gcc_control_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00755
        template.variables = {
            'uri_gcc': uri_gcc,
            'gcc_username': gcc_username,
            'gcc_nodename': '',
            'ssl_verify': SSLUtil.isSSLCertificatesVerificationEnabled()
        }

        template.save()

        self.logger.debug('delete - END')
    def syncrhonize(self):
        ''' Syncronizing time with systemd-timesyncd service '''

        if self.address is None or self.address.strip() == '':
            return False
        else:
            sysmanager = Utils.get_system_manager()
            if sysmanager == System_Manager.SYSV or sysmanager == System_Manager.UPSTART:
                p = subprocess.Popen(
                    'ntpdate-debian -u {}'.format(self.address),
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT)
                retval = p.wait()
                return retval == 0	

            elif sysmanager == System_Manager.SYSTEMD:
                template = Template()
                template.source = get_data_file('templates/timesyncd.conf')
                template.destination = '/etc/systemd/timesyncd.conf'
                template.owner = 'root'
                template.group = 'root'
                template.mode = 00644
                template.variables = { 'ntp_server':  self.address }
                template.save()

                subprocess.call(["systemctl", "enable", "systemd-timesyncd.service"])
                subprocess.call(["systemctl", "start", "systemd-timesyncd.service"])
                subprocess.call(["timedatectl", "set-local-rtc", "0"])
                subprocess.call(["timedatectl", "set-ntp", "true"])
                subprocess.call(["systemctl", "restart", "systemd-timesyncd.service"])
            
                p = subprocess.Popen(
                    "timedatectl status", 
                    shell=True, 
                    stdout=subprocess.PIPE, 
                    stderr=subprocess.STDOUT)

                for line in p.stdout.readlines():
                    if re.match(r'.*synchronized: yes', line):
                        self.logger.debug('NTP synchronized: %s', self.address)
                        return True

                self.logger.debug('NTP unsynchronized: %s', self.address)
                return False
Exemple #5
0
    def save(self, data):
        ''' Saving data '''
        self.logger.debug('save - BEGIN')

        if data is None:
            raise ValueError('data is None')

        if not isinstance(data, GecosAccessData):
            raise ValueError('data is not a GecosAccessData instance')

        # Insert the data in cache memory
        self.previous_saved_data = data

        # Get gcc_nodename from data file
        try:
            jsonUtil = JSONUtil()
            json_data = jsonUtil.loadJSONFromFile(self.data_file)
            gcc_nodename = ''
            if json_data is not None:
                gcc_nodename = json_data['gcc_nodename']

            if gcc_nodename is None or gcc_nodename.strip() == '':
                gcc_nodename = self.calculate_workstation_node_name()
        except Exception:
            # Can't get gcc_nodename from file, calculate it
            gcc_nodename = self.calculate_workstation_node_name()

        # Save data to data file
        template = Template()
        template.source = get_data_file('templates/gcc.control')
        template.destination = self.data_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00755
        url = data.get_url()
        if url.endswith('/'):
            url = url[0:-1]
        template.variables = {
            'uri_gcc': url,
            'gcc_username': data.get_login(),
            'gcc_nodename': gcc_nodename,
            'ssl_verify': SSLUtil.isSSLCertificatesVerificationEnabled()
        }

        return template.save()
    def save(self, ntp_server):
        ''' Saving data '''

        self.logger.debug('save - BEGIN')
        if ntp_server is None:
            raise ValueError('ntp_server is None')

        if not isinstance(ntp_server, NTPServer):
            raise ValueError('ntp_server is not a NTPServer instance')

        self.logger.debug('save("%s")', ntp_server.get_address())

        if self.initiated:
            # Check the previous value
            previous = self.load()
            if (previous is not None
                    and previous.get_address() == ntp_server.get_address()):
                return True

            # Save the value to data file
            template = Template()
            template.source = get_data_file('templates/timesyncd.conf') \
                    if self.sysmanager == System_Manager.SYSTEMD \
                    else get_data_file('templates/ntpdate')
            template.destination = self.data_file
            template.owner = 'root'
            template.group = 'root'
            template.mode = 00644
            template.variables = {'ntp_server': ntp_server.get_address()}

            return template.save()
        else:
            self.logger.warn(
                'NTPServerDAO used without a proper initialization!')

        return False
Exemple #7
0
                logging.debug("Error connecting to HTTPS server: %s", errormsg)
                if not debug_mode:
                    gecosCC.unregister_chef_node(
                        gecosAccessData, workstationData.get_node_name())
                clean_connection_files_on_error()
                sys.exit()

    template = Template()
    template.source = get_data_file('templates/client.rb')
    template.destination = 'c:\\chef\\client.rb'
    template.owner = 'root'
    template.group = 'root'
    template.mode = 00644
    template.variables = {
        'chef_url': chef_url,
        'chef_admin_name': chef_admin_name,
        'chef_node_name': workstationData.get_node_name(),
        'INSTDIR': os.environ["INSTDIR"].replace('\\', '/')
    }

    if not template.save():
        logging.error('Error saving c:\\chef\\client.rb')
        clean_connection_files_on_error()
        sys.exit()

    gemUtil = GemUtil()
    # Check installed GEMs
    for gem_name in necessary_gems:
        if not gemUtil.is_gem_intalled(gem_name):
            if not gemUtil.install_gem(gem_name):
                # Error installing a GEM
                logging.error("There was an error while installing a " +
    def _save_active_directory_normal(self, method):
        ''' Saving active directory user authentication method '''

        self.logger.debug('Saving active directory user authentication method')
        data = method.get_data()

        # Check data values
        if (data.get_ad_administrator_user() is None
                or data.get_ad_administrator_user().strip() == ''):
            raise ValueError('Active directory administrator user is empty!')

        if (data.get_ad_administrator_pass() is None
                or data.get_ad_administrator_pass().strip() == ''):
            raise ValueError(
                'Active directory administrator password is empty!')

        if (data.get_domain() is None or data.get_domain().strip() == ''):
            raise ValueError('Active directory domain name is empty!')

        if (data.get_workgroup() is None
                or data.get_workgroup().strip() == ''):
            raise ValueError('Active directory workgroup is empty!')

        self.logger.debug('Save /etc/samba/smb.conf file')
        # Save /etc/samba/smb.conf file
        template = Template()
        template.source = get_data_file('templates/smb.conf')
        template.destination = self.samba_conf_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {
            'ad_domain': data.get_domain().upper(),
            'ad_workgroup': data.get_workgroup()
        }

        if not template.save():
            self.logger.error('Error saving /etc/samba/smb.conf file')
            return False

        self.logger.debug('Save /etc/krb5.conf file')
        # Save /etc/krb5.conf file
        template = Template()
        template.source = get_data_file('templates/krb5.conf')
        template.destination = self.krb_conf_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {
            'ad_domain': data.get_domain(),
            'ad_domain_upper': data.get_domain().upper()
        }

        if not template.save():
            self.logger.error('Error saving /etc/krb5.conf file')
            return False

        commandUtil = CommandUtil()
        # Run "net ads join" command
        command = 'net ads join -U {0}%{1}'.format(
            data.get_ad_administrator_user(), data.get_ad_administrator_pass())
        self.logger.debug('running: %s', command)
        if not commandUtil.execute_command(command, {}):
            self.logger.warn('Error running command: %s', command)
            self.logger.warn('Check if the configuration was OK')

            command = 'net ads testjoin'
            self.logger.debug('running: %s', command)
            if not commandUtil.execute_command(command, {}):
                self.logger.error(
                    'Error testing if the workstation was joined to ' +
                    'the domain with command: %s', command)
                return False

        extra_conf_lines = ''
        if self.sssd_version is not None:
            major, minor, _ = self.pm.parse_version_number(self.sssd_version)

            if major > 1 or (major == 1 and minor > 11):
                extra_conf_lines = 'ad_gpo_map_interactive = +mdm, +polkit-1'

        self.logger.debug('Save /etc/sssd/sssd.conf file')
        # Save /etc/samba/sssd.conf file
        template = Template()
        template.source = get_data_file('templates/sssd.conf.ad')
        template.destination = self.main_data_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00600
        template.variables = {
            'ad_domain': data.get_domain(),
            'extra_conf_lines': extra_conf_lines
        }

        if not template.save():
            self.logger.error('Error saving /etc/sssd/sssd.conf file')
            return False

        # Restart SSSD service
        self.logger.debug('Restart SSSD service')
        p = subprocess.Popen('service sssd restart',
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        for line in p.stdout.readlines():
            self.logger.debug(line)

        retval = p.wait()
        if retval != 0:
            self.logger.error('Error running command: ' +
                              'service sssd restart')
            return False

        self.logger.debug('Save /usr/share/pam-configs/my_mkhomedir file')
        # Save /usr/share/pam-configs/my_mkhomedir file
        template = Template()
        template.source = get_data_file('templates/my_mkhomedir')
        template.destination = '/usr/share/pam-configs/my_mkhomedir'
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {}

        if not template.save():
            self.logger.error(
                'Error saving /usr/share/pam-configs/my_mkhomedir file')
            return False

        # Execute command pam-auth-update
        self.logger.debug('Execute command pam-auth-update')
        p = subprocess.Popen('pam-auth-update --package',
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        for line in p.stdout.readlines():
            self.logger.debug(line)

        retval = p.wait()
        if retval != 0:
            self.logger.error('Error running command: ' + 'pam-auth-update')
            return False

        self.logger.debug('Save /etc/gca-sssd.control file')
        # Save /etc/gca-sssd.control file
        template = Template()
        template.source = get_data_file('templates/gca-sssd.control')
        template.destination = '/etc/gca-sssd.control'
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {'auth_type': 'ad'}

        if not template.save():
            self.logger.error('Error saving /etc/gca-sssd.control file')
            return False

        return True
    def _save_active_directory_specific(self, method):
        ''' Saving specific active directory user authentication method '''

        self.logger.debug(
            'Saving specific active directory user authentication method')
        data = method.get_data()

        # Check data values
        if (data.get_ad_administrator_user() is None
                or data.get_ad_administrator_user().strip() == ''):
            raise ValueError('Active directory administrator user is empty!')

        if (data.get_ad_administrator_pass() is None
                or data.get_ad_administrator_pass().strip() == ''):
            raise ValueError(
                'Active directory administrator password is empty!')

        if (data.get_krb_5_conf() is None
                or data.get_krb_5_conf().strip() == ''):
            raise ValueError('krb5.conf file is empty!')

        if (data.get_sssd_conf() is None
                or data.get_sssd_conf().strip() == ''):
            raise ValueError('sssd.conf file is empty!')

        if (data.get_smb_conf() is None or data.get_smb_conf().strip() == ''):
            raise ValueError('smb.conf file is empty!')

        if (data.get_pam_conf() is None or data.get_pam_conf().strip() == ''):
            raise ValueError('pam.conf file is empty!')

        # Save files
        if not self._save_base64_file(self.main_data_file,
                                      data.get_sssd_conf()):
            self.logger.error("Error saving sssd.conf file!")
            return False

        if not self._save_base64_file(self.samba_conf_file,
                                      data.get_smb_conf()):
            self.logger.error("Error saving smb.conf file!")
            return False

        if not (self._save_base64_file(self.krb_conf_file,
                                       data.get_krb_5_conf())):
            self.logger.error("Error saving krb5.conf file!")
            return False

        if not self._save_base64_file('/etc/pam.conf', data.get_pam_conf()):
            self.logger.error("Error saving pam.conf file!")
            return False

        # Run "net ads join" command
        commandUtil = CommandUtil()
        command = 'net ads join -U {0}%{1}'.format(
            data.get_ad_administrator_user(), data.get_ad_administrator_pass())
        self.logger.debug('running: %s', command)

        if not commandUtil.execute_command(command, {}):
            self.logger.warn('Error running command: %s', command)
            self.logger.warn('Check if the configuration was OK')

            command = 'net ads testjoin'
            self.logger.debug('running: %s', command)
            if not commandUtil.execute_command(command, {}):
                self.logger.error(
                    'Error testing if the workstation was joined ' +
                    'to the domain with command: %s', command)
                return False

        # Restart SSSD service
        self.logger.debug('Restart SSSD service')
        p = subprocess.Popen('service sssd restart',
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        for line in p.stdout.readlines():
            self.logger.debug(line)

        retval = p.wait()
        if retval != 0:
            self.logger.error('Error running command: ' +
                              'service sssd restart')
            return False

        self.logger.debug('Save /usr/share/pam-configs/my_mkhomedir file')
        # Save /usr/share/pam-configs/my_mkhomedir file
        template = Template()
        template.source = get_data_file('templates/my_mkhomedir')
        template.destination = '/usr/share/pam-configs/my_mkhomedir'
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {}

        if not template.save():
            self.logger.error(
                'Error saving /usr/share/pam-configs/my_mkhomedir file')
            return False

        # Execute command pam-auth-update
        self.logger.debug('Execute command pam-auth-update')
        p = subprocess.Popen('pam-auth-update --package',
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        for line in p.stdout.readlines():
            self.logger.debug(line)

        retval = p.wait()
        if retval != 0:
            self.logger.error('Error running command: ' + 'pam-auth-update')
            return False

        self.logger.debug('Save /etc/gca-sssd.control file')
        # Save /etc/gca-sssd.control file
        template = Template()
        template.source = get_data_file('templates/gca-sssd.control')
        template.destination = '/etc/gca-sssd.control'
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {'auth_type': 'ad'}

        if not template.save():
            self.logger.error('Error saving /etc/gca-sssd.control file')
            return False

        return True
    def _save_ldap(self, method):
        ''' Saving LDAP user authentication method '''

        self.logger.debug('Saving LDAP user authentication method')
        data = method.get_data()

        # Check data values
        if data.get_uri() is None or data.get_uri().strip() == '':
            raise ValueError('LDAP URI is empty!')

        if data.get_base() is None or data.get_base().strip() == '':
            raise ValueError('LDAP base is empty!')

        self.logger.debug('Save /etc/sssd/sssd.conf file')
        # Save /etc/samba/sssd.conf file
        template = Template()
        template.source = get_data_file('templates/sssd.conf.ldap')
        template.destination = self.main_data_file
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00600
        template.variables = {
            'ldap_uri': data.get_uri(),
            'ldap_search_base': data.get_base()
        }

        if (data.get_bind_user_dn() is not None
                and data.get_bind_user_dn().strip() != ''
                and data.get_bind_user_pwd() is not None
                and data.get_bind_user_pwd().strip() != ''):
            template.variables['bind_dn'] = data.get_bind_user_dn()
            template.variables['bind_password'] = data.get_bind_user_pwd()

        if (data.get_base_group() is not None
                and data.get_base_group().strip() != ''):
            template.variables['base_group'] = data.get_base_group()

        if not template.save():
            self.logger.error('Error saving /etc/sssd/sssd.conf file')
            return False

        # Restart SSSD service
        self.logger.debug('Restart SSSD service')
        p = subprocess.Popen('service sssd restart',
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        for line in p.stdout.readlines():
            self.logger.debug(line)

        retval = p.wait()
        if retval != 0:
            self.logger.error('Error running command: ' +
                              'service sssd restart')
            return False

        self.logger.debug('Save /usr/share/pam-configs/my_mkhomedir file')
        # Save /usr/share/pam-configs/my_mkhomedir file
        template = Template()
        template.source = get_data_file('templates/my_mkhomedir')
        template.destination = '/usr/share/pam-configs/my_mkhomedir'
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {}

        if not template.save():
            self.logger.error(
                'Error saving /usr/share/pam-configs/my_mkhomedir file')
            return False

        # Execute command pam-auth-update
        self.logger.debug('Execute command pam-auth-update')
        p = subprocess.Popen('pam-auth-update --package',
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        for line in p.stdout.readlines():
            self.logger.debug(line)

        retval = p.wait()
        if retval != 0:
            self.logger.error('Error running command: ' + 'pam-auth-update')
            return False

        self.logger.debug('Save /etc/gca-sssd.control file')
        # Save /etc/gca-sssd.control file
        template = Template()
        template.source = get_data_file('templates/gca-sssd.control')
        template.destination = '/etc/gca-sssd.control'
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {'auth_type': 'ldap'}

        if not template.save():
            self.logger.error('Error saving /etc/gca-sssd.control file')
            return False

        return True
Exemple #11
0
        clean_disconnection_files_on_error()
        sys.exit()

    # Unlink from Chef
    logging.info("Unlink from Chef")

    logging.info("- Set c:\\chef\\client.rb with default values")
    template = Template()
    template.source = get_data_file('templates/client.rb')
    template.destination = 'c:\\chef\\client.rb'
    template.owner = 'root'
    template.group = 'root'
    template.mode = 00644
    template.variables = {
        'chef_url': 'CHEF_URL',
        'chef_admin_name': 'ADMIN_NAME',
        'chef_node_name': 'NODE_NAME',
        'INSTDIR': 'INSTALLATION_DIR'
    }

    if not template.save():
        logging.info("Can't create/modify c:\\chef\\client.rb file")
        clean_disconnection_files_on_error()
        sys.exit()

    logging.info("- Prepare c:\\chef\\knife.rb")
    chef_admin_name = gecosAccessData.get_login()
    chef_url = gecosAccessData.get_url()
    chef_url = chef_url.split('//')[1].split(':')[0]
    chef_url = "https://" + chef_url + '/'

    if (conf is not None and conf.has_key("chef")
    def runTest(self):
        template = Template()
        template.source = 'gecosws_config_assistant/tests/test.tmpl'
        template.destination = '/tmp/test1/test2/test3/test.file'
        template.owner = 'root'
        template.group = 'root'
        template.mode = 00644
        template.variables = {
            'test_value': 'TEST_VALUE_1',
            'test_2_value': 'TEST_2_VALUE_1'
        }

        # Delete the file is exist
        if os.path.isfile(template.destination):
            os.remove(template.destination)

        # Create the file
        template.save()
        self.assertTrue(self.findInFile(template.destination, 'TEST_VALUE_1'),
                        'Can not find TEST_VALUE_1!')
        self.assertTrue(
            self.findInFile(template.destination, 'TEST_2_VALUE_1'),
            'Can not find TEST_2_VALUE_1!')
        self.assertFalse(self.findInFile(template.destination, 'test_3_value'),
                         'Found test_3_value!')

        # update the file
        template.variables = {
            'test_value': 'TEST_VALUE_2',
            'test_3_value': 'TEST_3_VALUE_1'
        }
        template.save()
        self.assertTrue(self.findInFile(template.destination, 'TEST_VALUE_2'),
                        'Can not find TEST_VALUE_2!')
        self.assertTrue(
            self.findInFile(template.destination, 'TEST_3_VALUE_1'),
            'Can not find TEST_3_VALUE_1!')
        self.assertFalse(self.findInFile(template.destination, 'test_2_value'),
                         'Found test_2_value!')

        # Change mode and owner
        os.chmod(template.destination, 00666)
        uid = pwd.getpwnam('nobody').pw_uid
        gid = grp.getgrnam('nogroup').gr_gid
        os.chown(template.destination, uid, gid)

        # Test mode and owner
        template.save()

        stat_info = os.stat(template.destination)
        uid = stat_info.st_uid
        gid = stat_info.st_gid
        current_usr = pwd.getpwuid(uid)[0]
        current_grp = grp.getgrgid(gid)[0]
        m = stat_info.st_mode & 00777
        self.assertEqual(template.mode, m)
        self.assertEqual(current_usr, template.owner)
        self.assertEqual(current_grp, template.group)

        os.remove('/tmp/test1/test2/test3/test.file')
        os.rmdir('/tmp/test1/test2/test3')
        os.rmdir('/tmp/test1/test2')
        os.rmdir('/tmp/test1')