Exemplo n.º 1
0
    def change_permissions_for_local_users(self):
        if self.disable_local_users is False:
            content = Util.read_file('/etc/passwd')
            change_permisson = "chmod -R 700 {}"
            for p in pwd.getpwall():
                self.logger.info(
                    "User: '******' will change home directory of username".
                    format(p.pw_name))
                if not sysx.shell_is_interactive(p.pw_shell):
                    continue
                if p.pw_uid == 0:
                    continue
                if p.pw_name in content:
                    Util.execute(change_permisson.format(p.pw_dir))

        add_user_conf_file = "/etc/adduser.conf"
        file_dir_mode = open(add_user_conf_file, 'r')
        file_data = file_dir_mode.read()
        file_data = file_data.replace("DIR_MODE=0755", "DIR_MODE=0700")
        file_dir_mode.close()

        file_dir_mode = open(add_user_conf_file, 'w')
        file_dir_mode.write(file_data)
        file_dir_mode.close()
        self.logger.info("add user mode changed to 0700 in file {}".format(
            add_user_conf_file))
Exemplo n.º 2
0
    def purge_and_unregister(self):
        try:

            self.logger.info('Ahenk conf cleaned')
            self.logger.info('Ahenk conf cleaning from db')
            self.unregister()
            self.logger.info('Purge ldap packages')
            Util.execute(
                "sudo apt purge libpam-ldap libnss-ldap ldap-utils -y")
            # self.logger.info('Purge ahenk packages')
            # Util.execute("sudo apt purge ahenk ahenk-* -y")
            Util.execute("sudo apt autoremove -y")
            self.change_configs_after_purge()
            self.logger.info('purging successfull')
            self.logger.info('Cleaning ahenk conf..')
            self.clean()
            self.logger.info('Ahenk conf cleaned from db')
            self.logger.info('Enable Users')
            self.enable_local_users()
            Util.shutdown()

        except Exception as e:
            self.logger.error(
                "Error while running purge_and_unregister process.. Error Message  "
                + str(e))
Exemplo n.º 3
0
 def machine_model():
     try:
         result_code, p_out, p_err = Util.execute(
             'sudo dmidecode --string system-version')
         return str(p_out)
     except:
         raise
Exemplo n.º 4
0
 def manufacturer():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-manufacturer')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 5
0
 def product_name():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-product-name')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 6
0
 def release_date():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string bios-release-date')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 7
0
 def serial_number():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-serial-number')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 8
0
 def asset_tag():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-asset-tag')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 9
0
 def version():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string bios-version')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 10
0
 def usb_devices():
     result_code, p_out, p_err = Util.execute('lsusb')
     arr = []
     if result_code == 0:
         for line in p_out.splitlines():
             if ':' in line and 'Device 001' not in line.split(':')[0]:
                 arr.append(line)
     return arr
Exemplo n.º 11
0
 def screens():
     result_code, p_out, p_err = Util.execute('xrandr')
     arr = []
     if result_code == 0:
         for line in p_out.splitlines():
             if len(list(set(line.split(' ')).intersection(['connected']))) > 0:
                 arr.append(line)
     return arr
Exemplo n.º 12
0
    def execute_script(self, arg):
        try:
            self.logger.debug('Executing script...')
            messenger = Scope().get_instance().get_messenger()

            json_data = json.loads(arg)
            result_code, p_out, p_err = Util.execute(str(json_data['command']))

            self.logger.debug('Executed script')

            data = dict()
            data['type'] = 'SCRIPT_RESULT'
            data['timestamp'] = str(Util.timestamp())

            if result_code == 0:
                self.logger.debug('Command execution was finished successfully')
                try:
                    temp_name = str(Util.generate_uuid())
                    temp_full_path = System.Ahenk.received_dir_path() + temp_name
                    self.logger.debug('Writing result to file')
                    Util.write_file(temp_full_path, str(p_out))
                    md5 = Util.get_md5_file(temp_full_path)
                    Util.rename_file(temp_full_path, System.Ahenk.received_dir_path() + md5)

                    file_manager = FileTransferManager(json_data['fileServerConf']['protocol'],
                                                       json_data['fileServerConf']['parameterMap'])
                    file_manager.transporter.connect()
                    self.logger.debug('File transfer connection was created')
                    success = file_manager.transporter.send_file(System.Ahenk.received_dir_path() + md5, md5)
                    self.logger.debug('File was transferred')
                    file_manager.transporter.disconnect()
                    self.logger.debug('File transfer connection was closed')

                    if success is False:
                        self.logger.error('A problem occurred while file transferring')
                        data['resultCode'] = '-1'
                        data[
                            'errorMessage'] = 'Command executed successfully but a problem occurred while sending result file'

                    else:
                        data['md5'] = md5

                except Exception as e:
                    self.logger.error(
                        'A problem occurred while file transferring. Error Message :{0}'.format(
                            str(e)))
                    raise
            else:
                self.logger.error(
                    'Command execution was failed. Error Message :{0}'.format(str(result_code)))
                data['resultCode'] = str(result_code)
                data['errorMessage'] = str(p_err)

            messenger.send_direct_message(json.dumps(data))
        except Exception as e:
            self.logger.error(
                'A problem occurred while running execute script action. Error Message :{0}'.format(
                    str(e)))
Exemplo n.º 13
0
    def execute_script(self, arg):
        try:
            self.logger.debug('Executing script...')
            messenger = Scope().get_instance().get_messenger()

            json_data = json.loads(arg)
            result_code, p_out, p_err = Util.execute(str(json_data['command']))

            self.logger.debug('Executed script')

            data = dict()
            data['type'] = 'SCRIPT_RESULT'
            data['timestamp'] = str(Util.timestamp())

            if result_code == 0:
                self.logger.debug('Command execution was finished successfully')
                try:
                    temp_name = str(Util.generate_uuid())
                    temp_full_path = System.Ahenk.received_dir_path() + temp_name
                    self.logger.debug('Writing result to file')
                    Util.write_file(temp_full_path, str(p_out))
                    md5 = Util.get_md5_file(temp_full_path)
                    Util.rename_file(temp_full_path, System.Ahenk.received_dir_path() + md5)

                    file_manager = FileTransferManager(json_data['fileServerConf']['protocol'],
                                                       json_data['fileServerConf']['parameterMap'])
                    file_manager.transporter.connect()
                    self.logger.debug('File transfer connection was created')
                    success = file_manager.transporter.send_file(System.Ahenk.received_dir_path() + md5, md5)
                    self.logger.debug('File was transferred')
                    file_manager.transporter.disconnect()
                    self.logger.debug('File transfer connection was closed')

                    if success is False:
                        self.logger.error('A problem occurred while file transferring')
                        data['resultCode'] = '-1'
                        data[
                            'errorMessage'] = 'Command executed successfully but a problem occurred while sending result file'

                    else:
                        data['md5'] = md5

                except Exception as e:
                    self.logger.error(
                        'A problem occurred while file transferring. Error Message :{0}'.format(
                            str(e)))
                    raise
            else:
                self.logger.error(
                    'Command execution was failed. Error Message :{0}'.format(str(result_code)))
                data['resultCode'] = str(result_code)
                data['errorMessage'] = str(p_err)

            messenger.send_direct_message(json.dumps(data))
        except Exception as e:
            self.logger.error(
                'A problem occurred while running execute script action. Error Message :{0}'.format(
                    str(e)))
Exemplo n.º 14
0
 def system_definitions():
     result_code, p_out, p_err = Util.execute('dmidecode -t system')
     arr = []
     if result_code == 0:
         for line in p_out.splitlines():
             line = line.strip()
             if len(list(set(line.split(' ')).intersection(['Manufacturer:', 'Product']))) > 0:
                 arr.append(line)
     return arr
Exemplo n.º 15
0
    def ask(self, username, display):

        result = self.db_service.select('contract', ['content', 'title', 'id'],
                                        'id =(select MAX(id) from contract)')

        if result is None or len(result) < 1:
            content = 'Ahenk kurulu bu bilgisayarda ilk defa oturum açıyorsunuz. ' \
                      'Devam ederseniz Lider-Ahenk in bilgisayar üzeride yapacağı ' \
                      'tüm işlemlere onay vermiş sayılacaksınız. Kabul ediyor musunuz?' \
                      ' \n(Tanımlanmış zaman aralığında olumlu cevaplandırmadığınız takdirde oturumunuz ' \
                      'sonlandırılacaktır.)'
            title = 'Ahenk Kurulu Bilgisayar Kullanım Anlaşması'
            contract_id = '-1'
        else:
            content = str(result[0][0])
            title = result[0][1]
            contract_id = result[0][2]
        try:
            agreement_path = System.Ahenk.received_dir_path(
            ) + Util.generate_uuid()
            Util.write_file(agreement_path, content)
            Util.set_permission(agreement_path, 777)
            command = 'export DISPLAY={0};su - {1} -c \'python3 {2} \"$(cat {3})\" \"{4}\"\''.format(
                display, username, self.ask_path, agreement_path, title)
            result_code, p_out, p_err = Util.execute(command)

            pout = str(p_out).replace('\n', '')
            if pout != 'Error':
                if pout == 'Y':
                    self.logger.debug(
                        'Agreement was accepted by {0}.'.format(username))
                    self.db_service.update(
                        'agreement', self.db_service.get_cols('agreement'),
                        [contract_id, username,
                         Util.timestamp(), 'Y'])
                elif pout == 'N':
                    self.db_service.update(
                        'agreement', self.db_service.get_cols('agreement'),
                        [contract_id, username,
                         Util.timestamp(), 'N'])
                    self.logger.debug(
                        'Agreement was ignored by {0}. Session will be closed'.
                        format(username))
                else:
                    self.logger.error(
                        'A problem occurred while executing ask.py. Error Message: {0}'
                        .format(str(pout)))
                Util.delete_file(agreement_path)
            else:
                self.logger.error(
                    'A problem occurred while executing ask.py (Probably argument fault). Error Message: {0}'
                    .format(str(pout)))

        except Exception as e:
            self.logger.error(
                'A Problem occurred while displaying agreement. Error Message: {0}'
                .format(str(e)))
Exemplo n.º 16
0
        def monitors():
            edid_list = glob.glob('/sys/class/drm/*/edid')

            monitor_list = list()
            for edid in edid_list:
                result_code, p_out, p_err = Util.execute('parse-edid < {0}'.format(edid))

                if result_code == 0:
                    monitor_list.append(System.Hardware.screen_info_json_obj(p_out))

            return monitor_list
Exemplo n.º 17
0
    def disable_local_users(self):
        passwd_cmd = 'passwd -l {}'
        change_home = 'usermod -m -d {0} {1}'
        change_username = '******'
        content = Util.read_file('/etc/passwd')
        kill_all_process = 'killall -KILL -u {}'
        change_permisson = "chmod -R 700 {}"

        add_user_conf_file = "/etc/adduser.conf"
        file_dir_mode = open(add_user_conf_file, 'r')
        file_data = file_dir_mode.read()
        file_data = file_data.replace("DIR_MODE=0755", "DIR_MODE=0700")
        file_dir_mode.close()

        file_dir_mode = open(add_user_conf_file, 'w')
        file_dir_mode.write(file_data)
        file_dir_mode.close()

        self.logger.info("add user mode changed to 0700 in file {}".format(
            add_user_conf_file))

        for p in pwd.getpwall():
            self.logger.info(
                "User: '******' will be disabled and changed username and home directory of username"
                .format(p.pw_name))
            if not sysx.shell_is_interactive(p.pw_shell):
                continue
            if p.pw_uid == 0:
                continue
            if p.pw_name in content:
                new_home_dir = p.pw_dir.rstrip('/') + '-local/'
                new_username = p.pw_name + '-local'
                Util.execute(kill_all_process.format(p.pw_name))
                Util.execute(passwd_cmd.format(p.pw_name))
                Util.execute(change_username.format(new_username, p.pw_name))
                Util.execute(change_home.format(new_home_dir, new_username))
                Util.execute(change_permisson.format(new_home_dir))
Exemplo n.º 18
0
    def disable_local_users(self):
        passwd_cmd = 'passwd -l {}'
        change_home = 'usermod -m -d {0} {1}'
        change_username = '******'
        content = Util.read_file('/etc/passwd')
        kill_all_process = 'killall -KILL -u {}'
        change_permisson = "chmod -R 700 {}"

        for p in pwd.getpwall():
            self.logger.info(
                "User: '******' will be disabled and changed username and home directory of username"
                .format(p.pw_name))
            if not sysx.shell_is_interactive(p.pw_shell):
                continue
            if p.pw_uid == 0:
                continue
            if p.pw_name in content:
                new_home_dir = p.pw_dir.rstrip('/') + '-local/'
                new_username = p.pw_name + '-local'
                Util.execute(kill_all_process.format(p.pw_name))
                Util.execute(passwd_cmd.format(p.pw_name))
                Util.execute(change_username.format(new_username, p.pw_name))
                Util.execute(change_home.format(new_home_dir, new_username))
                Util.execute(change_permisson.format(new_home_dir))
Exemplo n.º 19
0
    def check_registration(self):
        """ docstring"""
        # max_attempt_number = int(System.Hardware.Network.interface_size()) * 3
        max_attempt_number = 2
        # self.logger.debug()
        # logger = Scope.getInstance().getLogger()
        registration = Scope.get_instance().get_registration()

        try:
            #if registration.is_registered() is False:
            #    self.logger.debug('Ahenk is not registered. Attempting for registration')
            #    if registration.registration_request() == False:
            #        self.registration_failed()

            while registration.is_registered() is False:
                print("Registration attempt")
                max_attempt_number -= 1
                self.logger.debug(
                    'Ahenk is not registered. Attempting for registration')
                # registration.registration_request(self.register_hostname,self.register_user_name,self.register_user_password,self.register_directory_server)
                registration.registration_request(self.register_hostname,
                                                  self.register_user_name,
                                                  self.register_user_password)
                if max_attempt_number < 0:
                    self.logger.warning(
                        'Number of Attempting for registration is over')
                    Util.execute("/etc/init.d/ahenk stop")
                    break
                #if max_attempt_number < 0:
                #    self.logger.warning('Number of Attempting for registration is over')
                #    self.registration_failed()
                #    break
        except Exception as e:
            self.registration_failed()
            self.logger.error('Registration failed. Error message: {0}'.format(
                str(e)))
Exemplo n.º 20
0
    def check_sssd_settings(self):
        # configure sssd for language environment
        sssd_language_conf = "/etc/default/sssd"
        sssd_conf_path = "/etc/sssd/sssd.conf"
        ad_info = "/etc/ahenk/ad_info"
        registration = Scope.get_instance().get_registration()
        if registration.is_registered() and Util.is_exist(sssd_language_conf):
            file_default_sssd = open(sssd_language_conf, 'r')
            file_data = file_default_sssd.read()
            file_default_sssd.close()

            if "LC_ALL=\"tr_CY.UTF-8\"" not in file_data:
                file_data = file_data + "\n" + "LC_ALL=\"tr_CY.UTF-8\""
                self.logger.info("added language environment for sssd")
                file_default_sssd = open(sssd_language_conf, 'w')
                file_default_sssd.write(file_data)
                file_default_sssd.close()
                Util.execute("systemctl restart sssd.service")

        if registration.is_registered() and Util.is_exist(sssd_conf_path) and Util.is_exist(ad_info):
            sssd_conf_data = Util.read_file_by_line(sssd_conf_path)

            isExist = False
            for line in sssd_conf_data:
                if "ad_domain" in line:
                    isExist = True
            if isExist:
                sssd_conf_temp = open(sssd_conf_path, 'w')
                for line in sssd_conf_data:
                    if "ad_domain" in line:
                        line = line.replace("ad_domain", "ad_server")
                    sssd_conf_temp.write(line)
                sssd_conf_temp.close()
                Util.execute("systemctl restart sssd.service")
                self.logger.info("replaced ad_domain parameter with ad_server")
                sssd_conf_temp.close()
Exemplo n.º 21
0
    def ask(self, username, display):

        result = self.db_service.select('contract', ['content', 'title', 'id'], 'id =(select MAX(id) from contract)')

        if result is None or len(result) < 1:
            content = 'Ahenk kurulu bu bilgisayarda ilk defa oturum açıyorsunuz. ' \
                      'Devam ederseniz Lider-Ahenk in bilgisayar üzeride yapacağı ' \
                      'tüm işlemlere onay vermiş sayılacaksınız. Kabul ediyor musunuz?' \
                      ' \n(Tanımlanmış zaman aralığında olumlu cevaplandırmadığınız takdirde oturumunuz ' \
                      'sonlandırılacaktır.)'
            title = 'Ahenk Kurulu Bilgisayar Kullanım Anlaşması'
            contract_id = '-1'
        else:
            content = str(result[0][0])
            title = result[0][1]
            contract_id = result[0][2]
        try:
            agreement_path = System.Ahenk.received_dir_path() + Util.generate_uuid()
            Util.write_file(agreement_path, content)
            Util.set_permission(agreement_path, 777)
            command = 'export DISPLAY={0};su - {1} -c \'python3 {2} \"$(cat {3})\" \"{4}\"\''.format(display, username,
                                                                                                     self.ask_path,
                                                                                                     agreement_path,
                                                                                                     title)
            result_code, p_out, p_err = Util.execute(command)
            pout = str(p_out).replace('\n', '')
            if pout != 'Error':
                if pout == 'Y':
                    self.logger.debug('Agreement was accepted by {0}.'.format(username))
                    self.db_service.update('agreement', self.db_service.get_cols('agreement'),
                                           [contract_id, username, Util.timestamp(), 'Y'])
                elif pout == 'N':
                    self.db_service.update('agreement', self.db_service.get_cols('agreement'),
                                           [contract_id, username, Util.timestamp(), 'N'])
                    self.logger.debug(
                        'Agreement was ignored by {0}. Session will be closed'.format(username))
                else:
                    self.logger.error(
                        'A problem occurred while executing ask.py. Error Message: {0}'.format(str(pout)))
                Util.delete_file(agreement_path)
            else:
                self.logger.error(
                    'A problem occurred while executing ask.py (Probably argument fault). Error Message: {0}'.format(
                        str(pout)))

        except Exception as e:
            self.logger.error(
                'A Problem occurred while displaying agreement. Error Message: {0}'.format(str(e)))
Exemplo n.º 22
0
    def run_command_from_fifo(self, num, stack):
        """ docstring"""

        while True:
            try:
                event = Commander().get_event()
                if event is None:
                    break
                json_data = json.loads(event)
            except Exception as e:
                self.logger.error(
                    'A problem occurred while loading json. Check json format! Error Message: {0}.'
                    ' Event = {1}'.format(str(e), str(event)))
                return

            if json_data is not None:

                self.logger.debug('Signal handled')
                self.logger.debug('Signal is :{0}'.format(
                    str(json_data['event'])))

                if str(json_data['event']
                       ) == 'login' and self.check_last_login():
                    username = json_data['username']
                    display = json_data['display']
                    desktop = json_data['desktop']

                    ip = None
                    if 'ip' in json_data:
                        ip = json_data['ip']

                    self.logger.info(
                        'login event is handled for user: {0}'.format(
                            username))
                    Util.execute("systemctl restart sssd.service")
                    login_message = self.message_manager.login_msg(
                        username, ip)
                    self.messenger.send_direct_message(login_message)

                elif str(json_data['event']) == 'logout':
                    username = json_data['username']
                    self.db_service.delete('session',
                                           'username=\'{0}\''.format(username))
                    self.execute_manager.remove_user_executed_policy_dict(
                        username)
                    # TODO delete all user records while initializing
                    self.logger.info(
                        'logout event is handled for user: {0}'.format(
                            username))
                    ip = None
                    if 'ip' in json_data:
                        ip = json_data['ip']
                    logout_message = self.message_manager.logout_msg(
                        username, ip)
                    self.messenger.send_direct_message(logout_message)

                    self.logger.info('Ahenk polkit file deleting..')
                    self.delete_polkit_user()

                    self.plugin_manager.process_mode('logout', username)
                    self.plugin_manager.process_mode('safe', username)

                elif str(json_data['event']) == 'send':
                    self.logger.info(
                        'Sending message over ahenkd command. Response Message: {0}'
                        .format(json.dumps(json_data['message'])))
                    message = json.dumps(json_data['message'])
                    self.messenger.send_direct_message(message)

                elif str(json_data['event']) == 'unregister':
                    self.logger.info('Unregistering..')
                    unregister_message = self.message_manager.unregister_msg()
                    if unregister_message is not None:
                        self.messenger.send_direct_message(unregister_message)

                elif str(json_data['event']) == 'load':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are loading to ahenk')
                        self.plugin_manager.load_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is loading to ahenk'.format(
                                    p_name))
                            self.plugin_manager.load_single_plugin(p_name)

                elif str(json_data['event']) == 'reload':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are reloading to ahenk')
                        self.plugin_manager.reload_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is reloading to ahenk'.format(
                                    p_name))
                            self.plugin_manager.reload_single_plugin(p_name)

                elif str(json_data['event']) == 'remove':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug(
                            'All plugins are removing from ahenk')
                        self.plugin_manager.remove_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is removing from ahenk'.format(
                                    p_name))
                            self.plugin_manager.remove_single_plugin(p_name)

                elif str(json_data['event']) == 'stop':
                    self.plugin_manager.process_mode('shutdown')
                    self.logger.info('Shutdown mode activated.')

                    # TODO timeout
                    while self.running_plugin() is False:
                        self.logger.debug('Waiting for progress of plugins...')
                        time.sleep(0.5)

                    Util.delete_file(System.Ahenk.fifo_file())
                    Scope().get_instance().get_custom_param(
                        'ahenk_daemon').stop()
                else:
                    self.logger.error('Unknown command error. Command:' +
                                      json_data['event'])
                self.logger.debug('Processing of handled event is completed')
Exemplo n.º 23
0
 def release_date():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string bios-release-date')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 24
0
 def product_name():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-product-name')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 25
0
 def serial_number():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-serial-number')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 26
0
 def asset_tag():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-asset-tag')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 27
0
 def version():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string bios-version')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 28
0
class ExecuteCancelLDAPLogin:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.util = Util()

    def cancel(self):
        self.logger.info('Purge ldap packages')
        self.util.execute("apt-get install sudo -y")
        self.util.execute(
            "apt purge libpam-ldap libnss-ldap ldap-utils sudo-ldap nss-updatedb libnss-db libpam-ccreds -y"
        )
        self.util.execute("apt autoremove -y")

        self.logger.info('purging successfull')

        # pattern for clearing file data from spaces, tabs and newlines
        pattern = re.compile(r'\s+')

        ldap_back_up_file_path = "/usr/share/ahenk/pam_scripts_original/ldap"
        ldap_original_file_path = "/usr/share/pam-configs/ldap"

        pam_script_back_up_file_path = "/usr/share/ahenk/pam_scripts_original/pam_script"
        pam_script_original_file_path = "/usr/share/pam-configs/pam_script"

        if self.util.is_exist(ldap_back_up_file_path):
            self.logger.info("Replacing {0} with {1}".format(
                ldap_original_file_path, ldap_back_up_file_path))
            self.util.copy_file(ldap_back_up_file_path,
                                ldap_original_file_path)
            self.logger.info("Deleting {0}".format(ldap_back_up_file_path))
            self.util.delete_file(ldap_back_up_file_path)

        if self.util.is_exist(pam_script_back_up_file_path):
            self.logger.info("Replacing {0} with {1}".format(
                pam_script_original_file_path, pam_script_back_up_file_path))
            self.util.copy_file(pam_script_back_up_file_path,
                                pam_script_original_file_path)
            self.logger.info(
                "Deleting {0}".format(pam_script_back_up_file_path))
            self.util.delete_file(pam_script_back_up_file_path)

        (result_code, p_out, p_err) = self.util.execute(
            "DEBIAN_FRONTEND=noninteractive pam-auth-update --package")
        if result_code == 0:
            self.logger.info(
                "'DEBIAN_FRONTEND=noninteractive pam-auth-update --package' has run successfully"
            )
        else:
            self.logger.error(
                "'DEBIAN_FRONTEND=noninteractive pam-auth-update --package' could not run successfully: "
                + p_err)

        # Configure nsswitch.conf
        file_ns_switch = open("/etc/nsswitch.conf", 'r')
        file_data = file_ns_switch.read()

        # cleared file data from spaces, tabs and newlines
        text = pattern.sub('', file_data)

        did_configuration_change = False
        if "passwd:compatldap[NOTFOUND=return]db" in text:
            file_data = file_data.replace(
                "passwd:         compat ldap [NOTFOUND=return] db",
                "passwd:         compat")
            did_configuration_change = True

        if "group:compatldap[NOTFOUND=return]db" in text:
            file_data = file_data.replace(
                "group:          compat ldap [NOTFOUND=return] db",
                "group:          compat")
            did_configuration_change = True

        if "shadow:compatldap" in text:
            file_data = file_data.replace("shadow:         compat ldap",
                                          "shadow:         compat")
            did_configuration_change = True

        if "#gshadow:files" in text:
            file_data = file_data.replace("#gshadow:        files",
                                          "gshadow:        files")
            did_configuration_change = True

        if did_configuration_change:
            self.logger.info("nsswitch.conf configuration has been configured")
        else:
            self.logger.info("nsswitch.conf has already been configured")

        file_ns_switch.close()
        file_ns_switch = open("/etc/nsswitch.conf", 'w')
        file_ns_switch.write(file_data)
        file_ns_switch.close()

        # Configure ldap-cache
        nss_update_cron_job_file_path = "/etc/cron.daily/nss-updatedb"
        if self.util.is_exist(nss_update_cron_job_file_path):
            self.util.delete_file(nss_update_cron_job_file_path)
            self.logger.info(
                "{0} is deleted.".format(nss_update_cron_job_file_path))

        # Configure lightdm.service
        pardus_xfce_path = "/usr/share/lightdm/lightdm.conf.d/99-pardus-xfce.conf"
        if self.util.is_exist(pardus_xfce_path):
            self.logger.info("99-pardus-xfce.conf exists. Deleting file.")
            self.util.delete_file(pardus_xfce_path)

        self.util.execute("systemctl restart nscd.service")
        self.logger.info("Operation finished")
Exemplo n.º 29
0
class ExecuteCancelSSSDAdAuthentication:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.util = Util()
        self.ad_info_path = "/etc/ahenk/ad_info"

    def cancel(self):
        try:
            # Deleting packages require for AD entegration
            self.util.execute(
                "apt purge realmd sssd sssd-tools adcli krb5-user packagekit samba-common samba-common-bin samba-libs -y"
            )
            self.util.execute("apt autoremove -y")

            # Read information about AD
            if self.util.is_exist(self.ad_info_path):
                file_data = self.util.read_file_by_line(self.ad_info_path)
                self.ip_address = file_data[0].strip("\n")
                self.host_name = file_data[1].strip("\n")
                self.logger.info(self.ip_address)
                self.logger.info(self.host_name)
                self.logger.info("Information read successfully from ad_info.")
            else:
                self.logger.error("ad_info file not found")

            if self.util.is_exist("/etc/sssd"):
                # self.util.delete_folder("/etc/sssd")
                self.logger.info("SSSD is deleted")
            else:
                self.logger.info("SSSD is not exist")

            # Re-Configure dhclient.conf deleting AD IP address
            dhclient_conf_path = "/etc/dhcp/dhclient.conf"
            file_dhclient = open(dhclient_conf_path, 'r')
            file_data = file_dhclient.read()

            if "prepend domain-name-servers {};".format(
                    self.ip_address) in file_data:
                file_data = file_data.replace(
                    ("prepend domain-name-servers {};".format(
                        self.ip_address)),
                    "#prepend domain-name-servers 127.0.0.1;")
                self.logger.info("dhclient is reconfigured")
            else:
                self.logger.error("dhclient is'not reconfigured")

            file_dhclient.close()
            file_dhclient = open(dhclient_conf_path, 'w')
            file_dhclient.write(file_data)
            file_dhclient.close()

            # Configure hosts for deleting AD  "IP address" and "AD hostname"
            hosts_conf_path = "/etc/hosts"
            file_hosts = open(hosts_conf_path, 'r')
            file_data = file_hosts.read()

            if ("{0}    {1}".format(self.ip_address,
                                    self.host_name)) in file_data:
                file_data = file_data.replace(
                    ("{0}    {1}".format(self.ip_address, self.host_name)),
                    " ")
                self.logger.info("hosts is configured")
            else:
                self.logger.error("hosts is not configured")
            file_hosts.close()
            file_hosts = open(hosts_conf_path, 'w')
            file_hosts.write(file_data)
            file_hosts.close()

            # Configure common-session for deleting home directories for AD users
            common_session_conf_path = "/etc/pam.d/common-session"
            file_common_session = open(common_session_conf_path, 'r')
            file_data = file_common_session.read()

            if "session optional pam_mkhomedir.so skel=/etc/skel umask=077" in file_data:
                file_data = file_data.replace(
                    "session optional pam_mkhomedir.so skel=/etc/skel umask=077",
                    " ")
                self.logger.info("common-session is configured")
            else:
                self.logger.error("common session is not configured")

            file_common_session.close()
            file_common_session = open(common_session_conf_path, 'w')
            file_common_session.write(file_data)
            file_common_session.close()

            # Configure resolv.conf for deleting AD IP address
            resolv_conf_path = "/etc/resolv.conf"
            file_resolv = open(resolv_conf_path, 'r')
            file_data = file_resolv.read()

            if ("nameserver {0}".format(self.ip_address)) in file_data:
                file_data = file_data.replace(
                    ("nameserver {0}".format(self.ip_address)), "")
                self.logger.info("resolv.conf is configured")
            else:
                self.logger.error("resolv is not configured")

            file_resolv.close()
            file_resolv = open(resolv_conf_path, 'w')
            file_resolv.write(file_data)
            file_resolv.close()

            # Deleting ad_info file
            if self.util.is_exist(self.ad_info_path):
                self.util.delete_file(self.ad_info_path)
                self.logger.info("Deleted ad_info file")
            else:
                self.logger.error("ad_info file not found")

            # Configure lightdm.service
            pardus_xfce_path = "/usr/share/lightdm/lightdm.conf.d/99-pardus-xfce.conf"
            if self.util.is_exist(pardus_xfce_path):
                self.logger.info("99-pardus-xfce.conf exists. Deleting file.")
                self.util.delete_file(pardus_xfce_path)
                self.util.execute("systemctl restart nscd.service")
            else:
                self.logger.info("99-pardus-xfce.conf not found")

            self.logger.info("AD Login iptal etme işlemi başarı ile sağlandı.")
            return True

        except Exception as e:
            self.logger.error(str(e))
            self.logger.info(
                "AD Login İptal etme işlemi esnasında hata oluştu.")
            return False
class ExecuteCancelSSSDAdAuthentication:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.util = Util()
        self.system = System()
        self.ad_info_path = "/etc/ahenk/ad_info"

    def cancel(self):
        try:

            # Read information about AD
            if self.util.is_exist(self.ad_info_path):
                file_data = self.util.read_file_by_line(self.ad_info_path)
                self.ip_list = file_data[0].strip("\n").replace("[",
                                                                "").replace(
                                                                    "]", "")
                self.host_list = file_data[1].strip("\n").replace("[",
                                                                  "").replace(
                                                                      "]", "")
                self.domain_name = file_data[2].strip("\n")

                self.ip_address = self.ip_list.split(", ")
                self.host_name = self.host_list.split(", ")

                self.ip_address[0] = self.ip_address[0].replace("'", "")
                self.host_name[0] = self.host_name[0].replace("'", "")

                self.logger.info(self.ip_address)
                self.logger.info(self.host_name)
                self.logger.info(self.domain_name)
                self.logger.info(self.ip_list)
                self.logger.info(self.host_list)

                self.logger.info("Information read successfully from ad_info.")
            else:
                self.logger.error("ad_info file not found")

            # Leave old domain
            (result_code, p_out, p_err) = self.util.execute("realm leave ")
            if (result_code == 0):
                self.logger.info("Realm Leave komutu başarılı")
            else:
                self.logger.error("Realm Leave komutu başarısız : " +
                                  str(p_err))

            # Re-Configure dhclient.conf deleting AD IP address
            dhclient_conf_path = "/etc/dhcp/dhclient.conf"
            file_dhclient = open(dhclient_conf_path, 'r')
            file_data = file_dhclient.read()

            if "prepend domain-name-servers {};".format(
                    self.ip_address[0]) in file_data:
                file_data = file_data.replace(
                    ("prepend domain-name-servers {};".format(
                        self.ip_address[0])),
                    "#prepend domain-name-servers 127.0.0.1;")
                self.logger.info("dhclient is reconfigured")
            else:
                self.logger.error("dhclient is'not reconfigured")

            file_dhclient.close()
            file_dhclient = open(dhclient_conf_path, 'w')
            file_dhclient.write(file_data)
            file_dhclient.close()

            # Configure hosts for deleting AD  "IP address" and "AD hostname"
            hosts_conf_path = "/etc/hosts"
            file_hosts = open(hosts_conf_path, 'r')
            file_data = file_hosts.read()

            for ip, host in zip(self.ip_address, self.host_name):
                ip = ip.replace("'", "")
                host = host.replace("'", "")
                if ("{0}       {1} {2}".format(ip, host,
                                               self.domain_name)) in file_data:
                    file_data = file_data.replace(("{0}       {1} {2}".format(
                        ip, host, self.domain_name)), " ")

            file_hosts.close()
            file_hosts = open(hosts_conf_path, 'w')
            file_hosts.write(file_data)
            file_hosts.close()

            # Configure common-session for deleting home directories for AD users
            common_session_conf_path = "/etc/pam.d/common-session"
            file_common_session = open(common_session_conf_path, 'r')
            file_data = file_common_session.read()

            if "session optional        pam_mkhomedir.so skel=/etc/skel umask=077" in file_data:
                file_data = file_data.replace(
                    "session optional        pam_mkhomedir.so skel=/etc/skel umask=077",
                    " ")
                self.logger.info("common-session is configured")
            else:
                self.logger.error("common session is not configured")

            file_common_session.close()
            file_common_session = open(common_session_conf_path, 'w')
            file_common_session.write(file_data)
            file_common_session.close()

            # Configure resolv.conf for deleting AD IP address
            resolv_conf_path = "/etc/resolv.conf"
            file_resolv = open(resolv_conf_path, 'r')
            file_data = file_resolv.read()

            if ("nameserver {0}".format(self.ip_address[0])) in file_data:
                file_data = file_data.replace(
                    ("nameserver {0}".format(self.ip_address[0])), "")
                self.logger.info("resolv.conf is configured")
            else:
                self.logger.error("resolv is not configured")

            file_resolv.close()
            file_resolv = open(resolv_conf_path, 'w')
            file_resolv.write(file_data)
            file_resolv.close()

            # Deleting ad_info file
            if self.util.is_exist(self.ad_info_path):
                self.util.delete_file(self.ad_info_path)
                self.logger.info("Deleted ad_info file")
            else:
                self.logger.error("ad_info file not found")

            self.logger.info("AD Login iptal etme işlemi başarı ile sağlandı.")
            return True

        except Exception as e:
            self.logger.error(str(e))
            self.logger.info(
                "AD Login İptal etme işlemi esnasında hata oluştu.")
            return False
Exemplo n.º 31
0
    def run_command_from_fifo(self, num, stack):
        """ docstring"""

        while True:
            try:
                event = Commander().get_event()
                if event is None:
                    break
                json_data = json.loads(event)
                self.logger.info(event)

            except Exception as e:
                self.logger.error(
                    'A problem occurred while loading json. Check json format! Error Message: {0}.'
                    ' Event = {1}'.format(str(e), str(event)))
                return

            if json_data is not None:
                self.logger.debug('Signal handled')
                self.logger.debug('Signal is :{0}'.format(
                    str(json_data['event'])))

                if str(json_data['event']
                       ) == 'login' and self.check_last_login():
                    username = json_data['username']
                    if username != "Debian-gdm" and username != "gdm":
                        display = json_data['display']
                        desktop = json_data['desktop']

                        ip = None
                        if 'ip' in json_data:
                            ip = json_data['ip']

                        domain = None
                        if 'domain' in json_data:
                            domain = json_data['domain']

                        self.logger.info(
                            'login event is handled for user: {0}'.format(
                                username))
                        self.logger.info(
                            'login parameters of login user, username: {0}, display: {1}, desktop: {2}, domain: {3}'
                            .format(username, display, desktop, domain))

                        Util.execute("systemctl restart sssd.service")
                        login_message = self.message_manager.login_msg(
                            username, ip)
                        self.messenger.send_direct_message(login_message)
                        agreement = Agreement()
                        agreement_choice = None

                        if agreement.check_agreement(
                                username
                        ) is not True and System.Ahenk.agreement() == '1':
                            self.logger.debug(
                                'User {0} has not accepted agreement.'.format(
                                    username))
                            thread_ask = Process(target=agreement.ask,
                                                 args=(
                                                     username,
                                                     display,
                                                 ))
                            thread_ask.start()
                            agreement_timeout = self.conf_manager.get(
                                'SESSION', 'agreement_timeout')
                            timeout = int(agreement_timeout)  # sec
                            timer = time.time()
                            while 1:
                                if thread_ask.is_alive() is False:
                                    self.logger.warning(
                                        '{0} was answered the question '.
                                        format(username))
                                    if Agreement().check_agreement(
                                            username) is True:
                                        self.logger.warning(
                                            'Choice of {0} is YES'.format(
                                                username))
                                        agreement_choice = True
                                        break
                                    elif Agreement().check_agreement(
                                            username) is False:
                                        self.logger.warning(
                                            'Choice of {0} is NO'.format(
                                                username))
                                        agreement_choice = False
                                        Util.close_session(username)
                                        break

                                if (time.time() - timer) > timeout:
                                    if thread_ask.is_alive():
                                        thread_ask.terminate()
                                    Util.close_session(username)
                                    self.logger.warning(
                                        'Session of {0} was ended because of timeout of contract agreement'
                                        .format(username))
                                    break
                                time.sleep(1)

                            if agreement_choice is not None:
                                self.messenger.send_direct_message(
                                    self.message_manager.agreement_answer_msg(
                                        username, agreement_choice))
                        else:
                            agreement_choice = True

                        if agreement_choice is True or System.Ahenk.agreement(
                        ) != '1':
                            self.db_service.delete('session', '1=1')
                            self.logger.info(
                                'Display is {0}, desktop env is {1} for {2}'.
                                format(display, desktop, username))
                            session_columns = self.db_service.get_cols(
                                'session')
                            # ['username', 'display', 'desktop', 'timestamp', 'ip', 'domain']
                            self.db_service.update(
                                'session', session_columns, [
                                    username, display, desktop,
                                    str(int(time.time())), ip, domain
                                ])

                            # Default policy for users --->> START
                            self.logger.info(
                                "Applying default policies for user {0}".
                                format(Util.get_username()))
                            self.default_policy.default_firefox_policy(
                                Util.get_username())
                            self.default_policy.disable_update_package_notify(
                                Util.get_username())
                            self.default_policy.create_pulseaudio_autostart()
                            # Default policy for users --->> STOP

                            get_policy_message = self.message_manager.policy_request_msg(
                                username)
                            self.plugin_manager.process_mode('safe', username)
                            self.plugin_manager.process_mode('login', username)

                            kward = dict()
                            kward['timeout_args'] = username
                            kward['checker_args'] = username

                            SetupTimer.start(
                                Timer(
                                    timeout=System.Ahenk.get_policy_timeout(),
                                    timeout_function=self.execute_manager.
                                    execute_default_policy,
                                    checker_func=self.execute_manager.
                                    is_policy_executed,
                                    kwargs=kward))

                            self.logger.info(
                                'Requesting updated policies from Lider. If Ahenk could not reach updated '
                                'policies in {0} sec, booked policies will be executed'
                                .format(System.Ahenk.get_policy_timeout()))
                            self.messenger.send_direct_message(
                                get_policy_message)

                elif str(json_data['event']) == 'logout':
                    username = json_data['username']
                    if username != "Debian-gdm" and username != "gdm":
                        self.execute_manager.remove_user_executed_policy_dict(
                            username)
                        self.plugin_manager.process_mode('logout', username)
                        self.plugin_manager.process_mode('safe', username)
                        if username != "Debian-gdm":
                            self.db_service.delete('session', '1=1')
                        # TODO delete all user records while initializing
                        self.logger.info(
                            'logout event is handled for user: {0}'.format(
                                username))
                        ip = None
                        if 'ip' in json_data:
                            ip = json_data['ip']

                        logout_message = self.message_manager.logout_msg(
                            username, ip)
                        self.messenger.send_direct_message(logout_message)
                        self.logger.info('Ahenk polkit file deleting..')
                        self.delete_polkit_user()
                        # self.db_service.delete('session', 'username=\'{0}\''.format(username))

                elif str(json_data['event']) == 'send':
                    self.logger.info(
                        'Sending message over ahenkd command. Response Message: {0}'
                        .format(json.dumps(json_data['message'])))
                    message = json.dumps(json_data['message'])
                    self.messenger.send_direct_message(message)

                elif str(json_data['event']) == 'unregister' and len(
                        json_data) == 1:
                    self.logger.info('Unregistering..')
                    self.execute_manager.set_unregister_credential_params(
                        None, None)
                    unregister_message = self.message_manager.unregister_msg(
                        None, None)
                    if unregister_message is not None:
                        self.messenger.send_direct_message(unregister_message)

                elif str(json_data['event']) == 'unregister' and len(
                        json_data) == 3:
                    self.logger.info('Unregistering..')
                    usernameForCheck = json_data['userName']
                    passwordForCheck = json_data['password']
                    ## send user credential info to execution manager for hide user notify when remote unregister
                    self.execute_manager.set_unregister_credential_params(
                        usernameForCheck, usernameForCheck)
                    self.logger.info('Unregistering by username+' +
                                     str(usernameForCheck))
                    unregister_message = self.message_manager.unregister_msg(
                        usernameForCheck, passwordForCheck)
                    if unregister_message is not None:
                        self.messenger.send_direct_message(unregister_message)

                elif str(json_data['event']) == 'load':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are loading to ahenk')
                        self.plugin_manager.load_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is loading to ahenk'.format(
                                    p_name))
                            self.plugin_manager.load_single_plugin(p_name)

                elif str(json_data['event']) == 'reload':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are reloading to ahenk')
                        self.plugin_manager.reload_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is reloading to ahenk'.format(
                                    p_name))
                            self.plugin_manager.reload_single_plugin(p_name)

                elif str(json_data['event']) == 'remove':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug(
                            'All plugins are removing from ahenk')
                        self.plugin_manager.remove_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is removing from ahenk'.format(
                                    p_name))
                            self.plugin_manager.remove_single_plugin(p_name)

                elif str(json_data['event']) == 'stop':
                    self.plugin_manager.process_mode('shutdown')
                    self.logger.info('Shutdown mode activated.')

                    # TODO timeout
                    while self.running_plugin() is False:
                        self.logger.debug('Waiting for progress of plugins...')
                        time.sleep(0.5)

                    Util.delete_file(System.Ahenk.fifo_file())
                    Scope().get_instance().get_custom_param(
                        'ahenk_daemon').stop()
                else:
                    self.logger.error('Unknown command error. Command:' +
                                      json_data['event'])
                self.logger.debug('Processing of handled event is completed')
Exemplo n.º 32
0
class DefaultPolicy:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.util = Util()

    ## default firefox policy for user
    def default_firefox_policy(self, username):
        exec_command = None
        firefox_path = None

        if self.util.is_exist("/usr/lib/firefox-esr/"):
            firefox_path = "/usr/lib/firefox-esr/"
            exec_command = "firefox-esr"

        elif self.util.is_exist('/opt/firefox-esr/'):
            firefox_path = "/opt/firefox-esr/"
            exec_command = "firefox-esr"

        elif self.util.is_exist('/usr/lib/iceweasel/'):
            firefox_path = "/usr/lib/iceweasel/"
            exec_command = "iceweasel"

        elif self.util.is_exist('/opt/firefox/'):
            firefox_path = "/opt/firefox/"
            exec_command = "firefox"

        else:
            self.logger.error('Firefox installation path not found')

        self.logger.info(
            "if mozilla profile is not created run firefox to create profile for user: "******"Get home directory is {0} of {1} for firefox default policy".
            format(homedir, username))
        if not Util.is_exist("{0}/.mozilla/".format(homedir)):
            self.logger.info(
                "firefox profile does not exist. Check autostart file.")
            if not Util.is_exist("{0}/.config/autostart/".format(homedir)):
                self.logger.info(
                    ".config/autostart folder does not exist. Creating folder."
                )
                Util.create_directory("{0}/.config/autostart/".format(homedir))
            else:
                self.logger.info(".config/autostart folder exists.")
                self.logger.info(
                    "Checking if {0}-autostart-for-profile.desktop autorun file exists."
                    .format(exec_command))
            if not Util.is_exist(
                    "{0}/.config/autostart/{1}-autostart-for-profile.desktop".
                    format(homedir, exec_command)):
                self.logger.info(
                    "{0}-autostart-for-profile.desktop autorun file does not exists. Creating file."
                    .format(exec_command))
                Util.create_file(
                    "{0}/.config/autostart/{1}-autostart-for-profile.desktop".
                    format(homedir, exec_command))
                content = "[Desktop Entry]\n\n" \
                          "Type=Application\n\n" \
                          "Exec={0}{1} www.liderahenk.org".format(firefox_path, exec_command)
                Util.write_file(
                    "{0}/.config/autostart/{1}-autostart-for-profile.desktop".
                    format(homedir, exec_command), content)
                self.logger.info(
                    "Autorun config is written to {0}-autostart-for-profile.desktop."
                    .format(exec_command))
                gid = self.util.file_group(homedir)
                cmd = "chown -R {0}:{1} {2}/.config/autostart".format(
                    username, gid, homedir)
                self.util.execute(cmd)
                self.logger.info(
                    "Set permissons for {0}/.config/autostart directory".
                    format(homedir))
            else:
                self.logger.info(
                    "{0}-autostart-for-profile.desktop exists".format(
                        exec_command))
        else:
            self.logger.info(
                ".mozilla firefox profile path exists. Delete autorun file.")
            Util.delete_file(
                "{0}/.config/autostart/{1}-autostart-for-profile.desktop".
                format(homedir, exec_command))

    ## disabled update package notify for user
    def disable_update_package_notify(self, username):
        homedir = self.util.get_homedir(username)
        self.logger.info(
            "Get home directory is {0} of {1} for disable update package notify"
            .format(homedir, username))
        xfce4_notify_template_path = "/usr/share/ahenk/base/default_policy/config-files/xfce4-notifyd.xml"
        fileName = "{0}/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-notifyd.xml".format(
            homedir)

        if not self.util.is_exist(fileName):
            ## if configuration file does not exist will be create  /home/{username}/.config/xfce4/xfconf/xfce-perchannel-xml/
            self.logger.info("Configuration file does not exist")
            self.util.create_directory(
                "{0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(
                    homedir))
            self.logger.info(
                "Created directory {0}/.config/xfce4/xfconf/xfce-perchannel-xml/"
                .format(homedir))
            self.util.copy_file(
                xfce4_notify_template_path,
                "{0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(
                    homedir))
            self.logger.info("Copy xfce4-notifyd.xml template file")
            gid = self.util.file_group(homedir)
            cmd = "chown -R {0}:{1} {2}/.config".format(username, gid, homedir)
            self.util.execute(cmd)
            self.logger.info(
                "Set permissons for {0}/.config directory".format(homedir))
            self.notifyd_xml_parser(username, homedir)
        else:
            self.logger.info("Configuration file exist")
            self.notifyd_xml_parser(username, homedir)
        pk_update_icon_file = "/etc/xdg/autostart/pk-update-icon.desktop"
        if self.util.is_exist(pk_update_icon_file):
            self.logger.info("{0} file exists".format(pk_update_icon_file))
            self.util.rename_file(pk_update_icon_file,
                                  pk_update_icon_file + ".ahenk")
            self.logger.info(
                "Renamed from {0} to {0}.ahenk".format(pk_update_icon_file))
            self.logger.info("Disabled autostart for pk-update-icon")
        else:
            self.logger.info("File not found")
        self.logger.info(
            "Disable notifications if there is a package update notification for user: "******"{0}/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-notifyd.xml".format(
            homedir)
        tree = ET.parse(fileName)
        root = tree.getroot()
        app_name_for_blocking = "pk-update-icon"
        element = root.find("./property/[@name='applications']")
        if element is None:
            self.logger.info("applications element could not be found.")
        else:
            element = root.find(
                "./property/property[@name='muted_applications']")
            if element is None:
                self.logger.info(
                    "muted_applications element could not be found.")
                self.logger.info(
                    "adding muted_applications element to applications tag.")
                element = root.find("./property/[@name='applications']")
                new_element = ET.SubElement(element, 'property')
                new_element.attrib["name"] = 'muted_applications'
                new_element.attrib["type"] = 'array'
                tree.write(fileName)
            else:
                self.logger.info("muted_applications tag exists.")

            self.logger.info("checking if '" + app_name_for_blocking +
                             "' exists in muted_applications tag.")
            element = root.find(
                "./property/property[@name='muted_applications']/value[@value='{0}']"
                .format(app_name_for_blocking))
            if element is None:
                self.logger.info(
                    "'" + app_name_for_blocking +
                    "' is not found in muted_applications element.")
                self.logger.info("'" + app_name_for_blocking +
                                 "' will be added to muted_applications tag.")
                element = root.find(
                    "./property/property[@name='muted_applications']")
                new_element = ET.SubElement(element, 'value')
                new_element.attrib["type"] = 'string'
                new_element.attrib["value"] = app_name_for_blocking
                tree.write(fileName)
            else:
                self.logger.info(
                    "'" + app_name_for_blocking +
                    "' is already added to muted_applications tag.")
Exemplo n.º 33
0
 def manufacturer():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-manufacturer')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Exemplo n.º 34
0
class Registration:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.message_manager = scope.get_message_manager()
        self.event_manager = scope.get_event_manager()
        self.messenger = scope.get_messenger()
        self.conf_manager = scope.get_configuration_manager()
        self.db_service = scope.get_db_service()
        self.util = Util()
        self.servicename = 'im.liderahenk.org'
        self.local_user_disable = None

        #self.event_manager.register_event('REGISTRATION_RESPONSE', self.registration_process)
        self.event_manager.register_event('REGISTRATION_SUCCESS',
                                          self.registration_success)
        self.event_manager.register_event('REGISTRATION_ERROR',
                                          self.registration_error)

        self.ldap_login_cancel = ExecuteCancelSSSDAuthentication()
        self.ad_login_cancel = ExecuteCancelSSSDAdAuthentication()
        self.ldap_login = ExecuteSSSDAuthentication()
        self.ad_login = ExecuteSSSDAdAuthentication()

        self.directory_server = None

        if self.is_registered():
            self.logger.debug('Ahenk already registered')
        else:
            self.register(True)

    def registration_request(self, hostname, username, password):

        self.logger.debug('Requesting registration')
        # SetupTimer.start(Timer(System.Ahenk.registration_timeout(), timeout_function=self.registration_timeout,checker_func=self.is_registered, kwargs=None))

        self.servicename = self.conf_manager.get("CONNECTION", "servicename")

        self.host = hostname
        self.user_name = username
        self.user_password = password

        if (username is None and password is None and self.host is None):

            self.host = self.conf_manager.get("CONNECTION", "host")

            user_name = os.getlogin()
            self.logger.debug('User : '******'Makineyi Lider MYS sistemine kaydetmek için bilgileri ilgili alanlara giriniz. LÜTFEN DEVAM EDEN İŞLEMLERİ SONLANDIRDIĞINZA EMİN OLUNUZ !',
                'LIDER MYS SISTEMINE KAYIT', self.host)
            self.logger.debug('pout : ' + str(pout))
            field_values = pout.split(' ')
            user_registration_info = list(field_values)

            if self.host == '':
                self.host = user_registration_info[0]
                self.user_name = user_registration_info[1]
                self.user_password = user_registration_info[2]
                self.directory_server = user_registration_info[3]

            else:
                self.user_name = user_registration_info[0]
                self.user_password = user_registration_info[1]
                self.directory_server = user_registration_info[2]

        #anon_messenger = AnonymousMessenger(self.message_manager.registration_msg(user_name,user_password), self.host,self.servicename)
        #anon_messenger.connect_to_server()

        self.logger.debug('Requesting registration')
        SetupTimer.start(
            Timer(System.Ahenk.registration_timeout(),
                  timeout_function=self.registration_timeout,
                  checker_func=self.is_registered,
                  kwargs=None))
        anon_messenger = AnonymousMessenger(
            self.message_manager.registration_msg(self.user_name,
                                                  self.user_password,
                                                  self.directory_server),
            self.host, self.servicename)
        anon_messenger.connect_to_server()

    def ldap_registration_request(self):
        self.logger.info('Requesting LDAP registration')
        self.messenger.send_Direct_message(
            self.message_manager.ldap_registration_msg())

    def registration_success(self, reg_reply):

        try:
            self.local_user_disable = reg_reply['disableLocalUser']
            if self.local_user_disable is True:
                self.conf_manager.set('MACHINE', 'user_disabled', 'true')
            else:
                self.conf_manager.set('MACHINE', 'user_disabled', 'false')

            self.logger.info('LDAP Registration update starting')
            dn = str(reg_reply['agentDn'])
            self.logger.info('Current dn:' + dn)
            self.logger.info('updating host name and service')
            self.update_registration_attrs(dn)

            # lightdm configuration by desktop env is XFCE
            self.desktop_env = self.util.get_desktop_env()
            self.logger.info("Get desktop environment is {0}".format(
                self.desktop_env))
            if self.desktop_env == "xfce":
                # Configure lightdm.service
                # check if 99-pardus-xfce.conf exists if not create
                pardus_xfce_path = "/usr/share/lightdm/lightdm.conf.d/99-pardus-xfce.conf"
                if not self.util.is_exist(pardus_xfce_path):
                    self.logger.info("99-pardus-xfce.conf does not exist.")
                    self.util.create_file(pardus_xfce_path)

                    file_lightdm = open(pardus_xfce_path, 'a')
                    file_lightdm.write("[Seat:*]\n")
                    file_lightdm.write("greeter-hide-users=true")
                    file_lightdm.close()
                    self.logger.info("lightdm has been configured.")
                else:
                    self.logger.info(
                        "99-pardus-xfce.conf exists. Delete file and create new one."
                    )
                    self.util.delete_file(pardus_xfce_path)
                    self.util.create_file(pardus_xfce_path)

                    file_lightdm = open(pardus_xfce_path, 'a')
                    file_lightdm.write("[Seat:*]")
                    file_lightdm.write("greeter-hide-users=true")
                    file_lightdm.close()
                    self.logger.info("lightdm.conf has been configured.")

            if self.desktop_env == "gnome":
                pardus_gnome_path = "/etc/gdm3/greeter.dconf-defaults"
                if not self.util.is_exist(pardus_gnome_path):
                    self.logger.info("Gnome conf doesn't exist")

                else:
                    reading_file = open(pardus_gnome_path, "r")

                    new_file_content = ""
                    for line in reading_file:
                        stripped_line = line.strip()
                        new_line = stripped_line.replace(
                            "# disable-user-list=true",
                            "disable-user-list=true")
                        new_file_content += new_line + "\n"
                    reading_file.close()

                    writing_file = open(pardus_gnome_path, "w")
                    writing_file.write(new_file_content)
                    writing_file.close()
                    self.logger.info("gdm.conf has been configured.")

            # LDAP registration
            if self.directory_server == "LDAP":
                self.install_and_config_ldap(reg_reply)
            # AD registration
            else:
                self.install_and_config_ad(reg_reply)

        except Exception as e:
            self.logger.error('Registration error. Error Message: {0}.'.format(
                str(e)))
            print(e)
            raise

    def update_registration_attrs(self, dn=None):
        self.logger.debug('Registration configuration is updating...')
        self.db_service.update('registration', ['dn', 'registered'], [dn, 1],
                               ' registered = 0')

        if self.conf_manager.has_section('CONNECTION'):
            self.conf_manager.set(
                'CONNECTION', 'uid',
                self.db_service.select_one_result('registration', 'jid',
                                                  ' registered=1'))
            self.conf_manager.set(
                'CONNECTION', 'password',
                self.db_service.select_one_result('registration', 'password',
                                                  ' registered=1'))

            if self.host and self.servicename:
                self.conf_manager.set('CONNECTION', 'host', self.host)
                self.conf_manager.set('CONNECTION', 'servicename',
                                      self.servicename)

            # TODO  get file path?
            with open('/etc/ahenk/ahenk.conf', 'w') as configfile:
                self.conf_manager.write(configfile)
            self.logger.debug('Registration configuration file is updated')

    def install_and_config_ldap(self, reg_reply):
        self.logger.info('ldap install process starting')
        server_address = str(reg_reply['ldapServer'])
        dn = str(reg_reply['ldapBaseDn'])
        version = str(reg_reply['ldapVersion'])
        admin_dn = str(reg_reply['ldapUserDn']
                       )  # get user full dn from server.. password same
        #admin_password = self.user_password # same user get from server
        admin_password = self.db_service.select_one_result(
            'registration', 'password', ' registered=1')
        self.ldap_login.authenticate(server_address, dn, admin_dn,
                                     admin_password)

        if server_address != '' and dn != '' and version != '' and admin_dn != '' and admin_password != '':
            self.logger.info("SSSD configuration process starting....")
            self.logger.info("SSSD configuration process starting....")
        else:
            raise Exception(
                'LDAP Ayarları yapılırken hata oluştu. Lütfen ağ bağlantınızı kontrol ediniz. Deponuzun güncel olduğundan emin olunuz.'
            )

    def install_and_config_ad(self, reg_reply):
        self.logger.info('AD install process starting')
        domain_name = str(reg_reply['adDomainName'])
        host_name = str(reg_reply['adHostName'])
        ip_address = str(reg_reply['adIpAddress'])
        password = str(reg_reply['adAdminPassword'])
        ad_username = str(reg_reply['adAdminUserName'])

        if domain_name is None or host_name is None or ip_address is None or password is None:
            self.logger.error("Registration params is null")
            return

        self.ad_login.authenticate(domain_name, host_name, ip_address,
                                   password, ad_username)

    def registration_error(self, reg_reply):
        self.re_register()

    def is_registered(self):
        try:
            if str(System.Ahenk.uid()):
                return True
            else:
                return False
        except:
            return False

    def is_ldap_registered(self):
        dn = self.db_service.select_one_result('registration', 'dn',
                                               'registered = 1')
        if dn is not None and dn != '':
            return True
        else:
            return False

    def register(self, uuid_depend_mac=False):
        cols = ['jid', 'password', 'registered', 'params', 'timestamp']
        vals = [
            str(System.Os.hostname()),
            str(self.generate_uuid(uuid_depend_mac)), 0,
            str(self.get_registration_params()),
            str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M"))
        ]

        self.db_service.delete('registration', ' 1==1 ')
        self.db_service.update('registration', cols, vals)
        self.logger.debug('Registration parameters were created')

    def get_registration_params(self):
        parts = []
        for part in System.Hardware.Disk.partitions():
            parts.append(part[0])

        params = {
            'ipAddresses':
            str(System.Hardware.Network.ip_addresses()).replace('[',
                                                                '').replace(
                                                                    ']', ''),
            'macAddresses':
            str(System.Hardware.Network.mac_addresses()).replace('[',
                                                                 '').replace(
                                                                     ']', ''),
            'hostname':
            System.Os.hostname(),
            'os.name':
            System.Os.name(),
            'os.version':
            System.Os.version(),
            'os.kernel':
            System.Os.kernel_release(),
            'os.distributionName':
            System.Os.distribution_name(),
            'os.distributionId':
            System.Os.distribution_id(),
            'os.distributionVersion':
            System.Os.distribution_version(),
            'os.architecture':
            System.Os.architecture(),
            'hardware.cpu.architecture':
            System.Hardware.Cpu.architecture(),
            'hardware.cpu.logicalCoreCount':
            System.Hardware.Cpu.logical_core_count(),
            'hardware.cpu.physicalCoreCount':
            System.Hardware.Cpu.physical_core_count(),
            'hardware.disk.total':
            System.Hardware.Disk.total(),
            'hardware.disk.used':
            System.Hardware.Disk.used(),
            'hardware.disk.free':
            System.Hardware.Disk.free(),
            'hardware.disk.partitions':
            str(parts),
            'hardware.monitors':
            str(System.Hardware.monitors()),
            'hardware.screens':
            str(System.Hardware.screens()),
            'hardware.usbDevices':
            str(System.Hardware.usb_devices()),
            'hardware.printers':
            str(System.Hardware.printers()),
            'hardware.systemDefinitions':
            str(System.Hardware.system_definitions()),
            'hardware.model.version':
            str(System.Hardware.machine_model()),
            'hardware.memory.total':
            System.Hardware.Memory.total(),
            'hardware.network.ipAddresses':
            str(System.Hardware.Network.ip_addresses()),
            'sessions.userNames':
            str(System.Sessions.user_name()),
            'bios.releaseDate':
            System.BIOS.release_date()[1].replace('\n', '')
            if System.BIOS.release_date()[0] == 0 else 'n/a',
            'bios.version':
            System.BIOS.version()[1].replace('\n', '')
            if System.BIOS.version()[0] == 0 else 'n/a',
            'bios.vendor':
            System.BIOS.vendor()[1].replace('\n', '')
            if System.BIOS.vendor()[0] == 0 else 'n/a',
            'hardware.baseboard.manufacturer':
            System.Hardware.BaseBoard.manufacturer()[1].replace('\n', '')
            if System.Hardware.BaseBoard.manufacturer()[0] == 0 else 'n/a',
            'hardware.baseboard.version':
            System.Hardware.BaseBoard.version()[1].replace('\n', '')
            if System.Hardware.BaseBoard.version()[0] == 0 else 'n/a',
            'hardware.baseboard.assetTag':
            System.Hardware.BaseBoard.asset_tag()[1].replace('\n', '')
            if System.Hardware.BaseBoard.asset_tag()[0] == 0 else 'n/a',
            'hardware.baseboard.productName':
            System.Hardware.BaseBoard.product_name()[1].replace('\n', '')
            if System.Hardware.BaseBoard.product_name()[0] == 0 else 'n/a',
            'hardware.baseboard.serialNumber':
            System.Hardware.BaseBoard.serial_number()[1].replace('\n', '')
            if System.Hardware.BaseBoard.serial_number()[0] == 0 else 'n/a',
        }

        return json.dumps(params)

    def unregister(self):
        self.logger.debug('Ahenk is unregistering...')
        self.db_service.delete('registration', ' 1==1 ')
        self.logger.debug('Ahenk is unregistered')

    def re_register(self):
        self.logger.debug('Reregistrating...')
        self.unregister()
        self.register(False)

    def generate_uuid(self, depend_mac=True):
        if depend_mac is False:
            self.logger.debug('uuid creating randomly')
            return uuid.uuid4()  # make a random UUID
        else:
            self.logger.debug('uuid creating according to mac address')
            return uuid.uuid3(
                uuid.NAMESPACE_DNS, str(get_mac())
            )  # make a UUID using an MD5 hash of a namespace UUID and a mac address

    def generate_password(self):
        return uuid.uuid4()

    def registration_timeout(self):
        self.logger.error(
            'Could not reach registration response from Lider. Be sure XMPP server is reachable and it supports anonymous message, Lider is running properly '
            'and it is connected to XMPP server! Check your Ahenk configuration file (/etc/ahenk/ahenk.conf)'
        )
        self.logger.error('Ahenk is shutting down...')
        print('Ahenk is shutting down...')
        Util.show_message(
            os.getlogin(), ':0',
            "Lider MYS sistemine ulaşılamadı. Lütfen sunucu adresini kontrol ediniz....",
            "HATA")
        System.Process.kill_by_pid(int(System.Ahenk.get_pid_number()))

    def purge_and_unregister(self):
        try:
            self.logger.info('Ahenk conf cleaned')
            self.logger.info('Ahenk conf cleaning from db')
            self.unregister()

            directory_type = "LDAP"
            if self.util.is_exist("/etc/ahenk/ad_info"):
                directory_type = "AD"

            if directory_type == "LDAP":
                self.ldap_login_cancel.cancel()
            else:
                self.ad_login_cancel.cancel()

            self.logger.info('Cleaning ahenk conf..')
            self.clean()
            self.logger.info('Ahenk conf cleaned from db')

            if self.conf_manager.has_section('MACHINE'):
                user_disabled = self.conf_manager.get("MACHINE",
                                                      "user_disabled")
                self.logger.info('User disabled value=' + str(user_disabled))
                if user_disabled != 'false':
                    self.logger.info('Enable Users')
                    self.enable_local_users()
                else:
                    self.logger.info('Local users already enabled')
            # İf desktop env is XFCE configured lightdm.service
            if self.util.get_desktop_env() == "xfce":
                pardus_xfce_path = "/usr/share/lightdm/lightdm.conf.d/99-pardus-xfce.conf"
                if self.util.is_exist(pardus_xfce_path):
                    self.logger.info(
                        "99-pardus-xfce.conf exists. Deleting file.")
                    self.util.delete_file(pardus_xfce_path)

            if self.util.get_desktop_env() == "gnome":
                pardus_gnome_path = "/etc/gdm3/greeter.dconf-defaults"
                if not self.util.is_exist(pardus_gnome_path):
                    self.logger.info("Gnome conf doesn't exist")

                else:
                    reading_file = open(pardus_gnome_path, "r")

                    new_file_content = ""
                    for line in reading_file:
                        stripped_line = line.strip()
                        new_line = stripped_line.replace(
                            "disable-user-list=true",
                            "# disable-user-list=true")
                        new_file_content += new_line + "\n"
                    reading_file.close()

                    writing_file = open(pardus_gnome_path, "w")
                    writing_file.write(new_file_content)
                    writing_file.close()
                    self.logger.info("gdm.conf has been configured.")

            Util.shutdown()
        except Exception as e:
            self.logger.error(
                "Error while running purge_and_unregister process.. Error Message  "
                + str(e))
        #System.Process.kill_by_pid(int(System.Ahenk.get_pid_number()))
        #sys.exit(2)

    def change_configs_after_purge(self):
        # pattern for clearing file data from spaces, tabs and newlines
        pattern = re.compile(r'\s+')

        ldap_back_up_file_path = "/usr/share/ahenk/pam_scripts_original/ldap"
        ldap_original_file_path = "/usr/share/pam-configs/ldap"

        pam_script_back_up_file_path = "/usr/share/ahenk/pam_scripts_original/pam_script"
        pam_script_original_file_path = "/usr/share/pam-configs/pam_script"

        if self.util.is_exist(ldap_back_up_file_path):
            self.logger.info("Replacing {0} with {1}".format(
                ldap_original_file_path, ldap_back_up_file_path))
            self.util.copy_file(ldap_back_up_file_path,
                                ldap_original_file_path)
            self.logger.info("Deleting {0}".format(ldap_back_up_file_path))
            self.util.delete_file(ldap_back_up_file_path)

        if self.util.is_exist(pam_script_back_up_file_path):
            self.logger.info("Replacing {0} with {1}".format(
                pam_script_original_file_path, pam_script_back_up_file_path))
            self.util.copy_file(pam_script_back_up_file_path,
                                pam_script_original_file_path)
            self.logger.info(
                "Deleting {0}".format(pam_script_back_up_file_path))
            self.util.delete_file(pam_script_back_up_file_path)

        (result_code, p_out, p_err) = self.util.execute(
            "DEBIAN_FRONTEND=noninteractive pam-auth-update --package")
        if result_code == 0:
            self.logger.info(
                "'DEBIAN_FRONTEND=noninteractive pam-auth-update --package' has run successfully"
            )
        else:
            self.logger.error(
                "'DEBIAN_FRONTEND=noninteractive pam-auth-update --package' could not run successfully: "
                + p_err)

        # Configure nsswitch.conf
        file_ns_switch = open("/etc/nsswitch.conf", 'r')
        file_data = file_ns_switch.read()

        # cleared file data from spaces, tabs and newlines
        text = pattern.sub('', file_data)

        did_configuration_change = False
        if "passwd:compatldap[NOTFOUND=return]db" in text:
            file_data = file_data.replace(
                "passwd:         compat ldap [NOTFOUND=return] db",
                "passwd:         compat")
            did_configuration_change = True

        if "group:compatldap[NOTFOUND=return]db" in text:
            file_data = file_data.replace(
                "group:          compat ldap [NOTFOUND=return] db",
                "group:          compat")
            did_configuration_change = True

        if "shadow:compatldap" in text:
            file_data = file_data.replace("shadow:         compat ldap",
                                          "shadow:         compat")
            did_configuration_change = True

        if "#gshadow:files" in text:
            file_data = file_data.replace("#gshadow:        files",
                                          "gshadow:        files")
            did_configuration_change = True

        if did_configuration_change:
            self.logger.info("nsswitch.conf configuration has been configured")
        else:
            self.logger.info("nsswitch.conf has already been configured")

        file_ns_switch.close()
        file_ns_switch = open("/etc/nsswitch.conf", 'w')
        file_ns_switch.write(file_data)
        file_ns_switch.close()

        # Configure ldap-cache
        nss_update_cron_job_file_path = "/etc/cron.daily/nss-updatedb"
        if self.util.is_exist(nss_update_cron_job_file_path):
            self.util.delete_file(nss_update_cron_job_file_path)
            self.logger.info(
                "{0} is deleted.".format(nss_update_cron_job_file_path))

        # Configure lightdm.service
        pardus_xfce_path = "/usr/share/lightdm/lightdm.conf.d/99-pardus-xfce.conf"
        if self.util.is_exist(pardus_xfce_path):
            self.logger.info("99-pardus-xfce.conf exists. Deleting file.")
            self.util.delete_file(pardus_xfce_path)

        self.util.execute("systemctl restart nscd.service")
        self.logger.info("Operation finished")

    def clean(self):
        print('Ahenk cleaning..')
        import configparser
        try:
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            db_path = config.get('BASE', 'dbPath')

            if Util.is_exist(System.Ahenk.fifo_file()):
                Util.delete_file(System.Ahenk.fifo_file())

            if Util.is_exist(db_path):
                Util.delete_file(db_path)

            if Util.is_exist(System.Ahenk.pid_path()):
                Util.delete_file(System.Ahenk.pid_path())

            config.set('CONNECTION', 'uid', '')
            config.set('CONNECTION', 'password', '')
            config.set('MACHINE', 'user_disabled', 'false')

            with open(System.Ahenk.config_path(), 'w') as file:
                config.write(file)
            file.close()
            print('Ahenk cleaned.')
        except Exception as e:
            self.logger.error(
                "Error while running clean command. Error Message  " + str(e))
            print(
                'Error while running clean command. Error Message {0}'.format(
                    str(e)))

    def enable_local_users(self):
        passwd_cmd = 'passwd -u {}'
        change_home = 'usermod -m -d {0} {1}'
        change_username = '******'
        content = self.util.read_file('/etc/passwd')
        for p in pwd.getpwall():
            if not sysx.shell_is_interactive(p.pw_shell):
                continue
            if p.pw_uid == 0:
                continue
            if p.pw_name in content:
                new_home_dir = p.pw_dir.rstrip('-local/') + '/'
                new_username = p.pw_name.rstrip('-local')
                self.util.execute(passwd_cmd.format(p.pw_name))
                self.util.execute(
                    change_username.format(new_username, p.pw_name))
                self.util.execute(
                    change_home.format(new_home_dir, new_username))
                self.logger.debug(
                    "User: '******' will be enabled and changed username and home directory of username"
                    .format(p.pw_name))

    def disable_local_users(self):
        passwd_cmd = 'passwd -l {}'
        change_home = 'usermod -m -d {0} {1}'
        change_username = '******'
        content = Util.read_file('/etc/passwd')
        kill_all_process = 'killall -KILL -u {}'
        change_permisson = "chmod -R 700 {}"

        add_user_conf_file = "/etc/adduser.conf"
        file_dir_mode = open(add_user_conf_file, 'r')
        file_data = file_dir_mode.read()
        file_data = file_data.replace("DIR_MODE=0755", "DIR_MODE=0700")
        file_dir_mode.close()

        file_dir_mode = open(add_user_conf_file, 'w')
        file_dir_mode.write(file_data)
        file_dir_mode.close()

        self.logger.info("add user mode changed to 0700 in file {}".format(
            add_user_conf_file))

        for p in pwd.getpwall():
            self.logger.info(
                "User: '******' will be disabled and changed username and home directory of username"
                .format(p.pw_name))
            if not sysx.shell_is_interactive(p.pw_shell):
                continue
            if p.pw_uid == 0:
                continue
            if p.pw_name in content:
                new_home_dir = p.pw_dir.rstrip('/') + '-local/'
                new_username = p.pw_name + '-local'
                Util.execute(kill_all_process.format(p.pw_name))
                Util.execute(passwd_cmd.format(p.pw_name))
                Util.execute(change_username.format(new_username, p.pw_name))
                Util.execute(change_home.format(new_home_dir, new_username))
                Util.execute(change_permisson.format(new_home_dir))
Exemplo n.º 35
0
 def printers():
     result_code, p_out, p_err = Util.execute('lpstat -a')
     arr = None
     if result_code == 0:
         arr = p_out.splitlines()
     return arr
Exemplo n.º 36
0
class ExecuteSSSDAdAuthentication:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.util = Util()
        self.system = System()

    def authenticate(self, domain_name, host_name, ip_address, password, ad_username, dynamic_dns_update):
        try:

            # Installation of required packages
            (result_code, p_out, p_err) = self.util.execute(
                "sudo apt-get -y install realmd")
            if (result_code == 0):
                self.logger.info("İndirmeler Başarılı")
            else:
                self.logger.error("İndirmeler Başarısız : " + str(p_err))

            # Split datas that Lider send
            self.logger.info(host_name)
            self.logger.info(ip_address)

            ip_address_split = ip_address.split(",")
            host_name_split = host_name.split(",")
            ip_address = ip_address_split[0]
            host_name = host_name_split[0]

            # Execute the commands that require for leave
            (result_code, p_out, p_err) = self.util.execute("realm leave")
            if (result_code == 0):
                self.logger.info("Realm Leave komutu başarılı")
            else:
                self.logger.error("Realm Leave komutu başarısız : " + str(p_err))

            # Create and Configure ad_info file
            (result_code, p_out, p_err) = self.util.execute("touch /etc/ahenk/ad_info")
            if (result_code == 0):
                self.logger.info("AD INFO başarılı bir şekilde oluşturuldu")
                # Configure ad_info for deregisteration info
                default_ad_info_path = "/etc/ahenk/ad_info"
                file_default_ad_info = open(default_ad_info_path, 'r')
                file_data = file_default_ad_info.read()

                file_data = file_data + ("{}".format(ip_address_split)) + "\n" + (
                    "{}".format(host_name_split)) + "\n" + (
                                "{}".format(domain_name)) + "\n" + ("{}".format(ad_username))

                self.logger.info("/etc/ahenk/ad_info bilgiler girildi.")
                file_default_ad_info.close()
                file_default_ad_info = open(default_ad_info_path, 'w')
                file_default_ad_info.write(file_data)
                file_default_ad_info.close()
            else:
                self.logger.error("ad_info oluşturma komutu başarısız : " + str(p_err))

            self.logger.info("Authenticate starting....")
            # Configure /etc/dhcp/dhclient.conf
            dhclient_conf_path = "/etc/dhcp/dhclient.conf"
            dhc_conf = self.util.read_file_by_line(dhclient_conf_path, "r")
            dhc_conf_temp = open(dhclient_conf_path, 'w')

            for lines in dhc_conf:
                if (lines == "#prepend domain-name-servers 127.0.0.1;\n"):
                    lines = lines.replace(lines, ("prepend domain-name-servers {};\n".format(ip_address)))
                dhc_conf_temp.write(lines)
            dhc_conf_temp.close()

            file_default_dhcp = open(dhclient_conf_path, 'r')
            file_data = file_default_dhcp.read()

            if ("prepend domain-name-servers {};\n".format(ip_address)) not in file_data:
                file_data = file_data + "\n" + ("prepend domain-name-servers {};".format(ip_address))

            file_default_dhcp.close()
            file_default_dhcp = open(dhclient_conf_path, 'w')
            file_default_dhcp.write(file_data)
            file_default_dhcp.close()

            # Configure /etc/resolv.conf
            resolve_conf_path = "/etc/resolv.conf"
            resolve_conf = self.util.read_file_by_line(resolve_conf_path, "r")
            resolve_conf_temp = open(resolve_conf_path, 'w')

            for lines in resolve_conf:
                if (lines == ("nameserver {}\n".format(ip_address))):
                    continue
                lines = lines.replace(lines, ("#" + lines))
                resolve_conf_temp.write(lines)
            resolve_conf_temp.close()
            file_default_resolve = open(resolve_conf_path, 'r')
            file_data = file_default_resolve.read()

            if ("nameserver {}\n".format(ip_address)) not in file_data:
                file_data = file_data + "\n" + ("nameserver {}\n".format(ip_address))
                self.logger.info("/etc/resolv.conf is configured")

            file_default_resolve.close()
            file_default_resolve = open(resolve_conf_path, 'w')
            file_default_resolve.write(file_data)
            file_default_resolve.close()

            # Configure /etc/hosts
            host_path = "/etc/hosts"
            file_default_hosts = open(host_path, 'r')
            file_data = file_default_hosts.read()

            for ips, hostnames in zip(ip_address_split, host_name_split):
                file_data = file_data + "\n" + ips + "       " + hostnames + " " + domain_name

            file_default_hosts.close()
            file_default_hosts = open(host_path, 'w')
            file_default_hosts.write(file_data)
            file_default_hosts.close()

            # Execute the script that required for "samba-common" and "krb5"
            (result_code, p_out, p_err) = self.util.execute(
                "/bin/bash /usr/share/ahenk/base/registration/scripts/ad.sh {0} {1}".format(domain_name.upper(),
                                                                                            host_name))

            if (result_code == 0):
                self.logger.info("Script başarılı bir  şekilde çalıştırıldı.")
            else:
                self.logger.error("Script başarısız oldu : " + str(p_err))

            # Installation of required packages
            (result_code, p_out, p_err) = self.util.execute(
                "sudo apt-get -y install sssd sssd-tools adcli packagekit samba-common-bin samba-libs")
            if (result_code == 0):
                self.logger.info("İndirmeler Başarılı")
            else:
                self.logger.error("İndirmeler Başarısız : " + str(p_err))

            # Configure pam.d/common-session
            pamd_common_session_path = "/etc/pam.d/common-session"
            file_default_pam = open(pamd_common_session_path, 'r')
            file_data = file_default_pam.read()

            if "session optional        pam_mkhomedir.so skel=/etc/skel umask=077" not in file_data:
                file_data = file_data + "\n" + "session optional        pam_mkhomedir.so skel=/etc/skel umask=077"
                self.logger.info("/etc/pam.d/common-session is configured")

            file_default_pam.close()
            file_default_pam = open(pamd_common_session_path, 'w')
            file_default_pam.write(file_data)
            file_default_pam.close()

            self.discover_try_counter2 = 0
            try:
                while (True):
                    self.discover_try_counter2 = self.discover_try_counter2 + 1
                    if (self.discover_try_counter2 == 5):
                        break
                    else:
                        (result_code, p_out, p_err) = self.util.execute("realm discover {}".format(domain_name.upper()))
                        if (result_code == 0):
                            self.logger.info("Realm Discover komutu başarılı")
                            break
                        else:
                            self.logger.error("Realm Discover komutu başarısız : ")
                            time.sleep(2)
            except Exception as e:
                self.logger.error(e)
                self.logger.info("Active Directory Discover işlemi esnasında hata oluştu.")

            self.join_try_counter = 0
            try:
                while (True):
                    self.join_try_counter = self.join_try_counter + 1
                    if (self.join_try_counter == 5):
                        break
                    else:
                        (result_code, p_out, p_err) = self.util.execute(
                            "echo \"{0}\" | realm join --user={1} {2}".format(password, ad_username,
                                                                              domain_name.upper()))
                        if (result_code == 0):
                            self.logger.info("Realm Join komutu başarılı")
                            break
                        else:
                            self.logger.error("Realm Join komutu başarısız : ")
                            time.sleep(2)
            except Exception as e:
                self.logger.error(e)
                self.logger.info("Active Directory Join işlemi esnasında hata oluştu.")

            # DynamicDNSUpdate in Active Directory
            if dynamic_dns_update == True:
                self.logger.info("dynamicDNSUpdate is Activated")
                # Installation of required packages
                (result_code, p_out, p_err) = self.util.execute(
                    "sudo apt-get -y install dnsutils")
                if (result_code == 0):
                    self.logger.info("İndirmeler Başarılı")
                else:
                    self.logger.error("İndirmeler Başarısız : " + str(p_err))

                # Configure sssd template
                sssd_config_template_path = "/usr/share/ahenk/base/registration/config-files/sssd_ad_dns.conf"
                sssd_config_folder_path = "/etc/sssd"
                sssd_config_file_path = "/etc/sssd/sssd.conf"

                if not self.util.is_exist(sssd_config_folder_path):
                    self.util.create_directory(sssd_config_folder_path)
                    self.logger.info("{0} folder is created".format(sssd_config_folder_path))

                if self.util.is_exist(sssd_config_file_path):
                    self.util.delete_file(sssd_config_file_path)
                    self.logger.info("delete sssd org conf")

                self.util.copy_file(sssd_config_template_path, sssd_config_folder_path)
                self.logger.info(
                    "{0} config file is copied under {1}".format(sssd_config_template_path, sssd_config_folder_path))
                self.util.rename_file("/etc/sssd/sssd_ad_dns.conf", "/etc/sssd/sssd.conf")

                # Configure sssd.conf
                file_sssd = open(sssd_config_file_path, 'r')
                file_data = file_sssd.read()

                file_data = file_data.replace("###domains###", "domains = {}".format(domain_name))
                file_data = file_data.replace("###[domain/###", "[domain/{}]".format(domain_name))
                file_data = file_data.replace("###ad_domain###", "ad_domain = {}".format(domain_name))
                file_data = file_data.replace("###krb5_realm###", "krb5_realm = {}".format(domain_name.upper()))
                file_data = file_data.replace("###ad_hostname###",
                                              "ad_hostname = {0}.{1}".format(self.system.Os.hostname(),
                                                                             domain_name.lower()))

                file_sssd.close()
                file_sssd = open(sssd_config_file_path, 'w')
                file_sssd.write(file_data)
                file_sssd.close()

                # Arrangement of chmod as 600 for sssd.conf
                (result_code, p_out, p_err) = self.util.execute("chmod 600 {}".format(sssd_config_file_path))
                if (result_code == 0):
                    self.logger.info("Chmod komutu başarılı bir şekilde çalıştırıldı")
                else:
                    self.logger.error("Chmod komutu başarısız : " + str(p_err))

            else:
                self.logger.info("dynamicDNSUpdate is NOT Activated")
                # Configure sssd template
                sssd_config_template_path = "/usr/share/ahenk/base/registration/config-files/sssd_ad.conf"
                sssd_config_folder_path = "/etc/sssd"
                sssd_config_file_path = "/etc/sssd/sssd.conf"

                if not self.util.is_exist(sssd_config_folder_path):
                    self.util.create_directory(sssd_config_folder_path)
                    self.logger.info("{0} folder is created".format(sssd_config_folder_path))

                if self.util.is_exist(sssd_config_file_path):
                    self.util.delete_file(sssd_config_file_path)
                    self.logger.info("delete sssd org conf")

                self.util.copy_file(sssd_config_template_path, sssd_config_folder_path)
                self.logger.info(
                    "{0} config file is copied under {1}".format(sssd_config_template_path, sssd_config_folder_path))
                self.util.rename_file("/etc/sssd/sssd_ad.conf", "/etc/sssd/sssd.conf")

                # Configure sssd.conf
                file_sssd = open(sssd_config_file_path, 'r')
                file_data = file_sssd.read()

                file_data = file_data.replace("###domains###", "domains = {}".format(domain_name))
                file_data = file_data.replace("###[domain/###", "[domain/{}]".format(domain_name))
                file_data = file_data.replace("###ad_domain###", "ad_domain = {}".format(domain_name))
                file_data = file_data.replace("###krb5_realm###", "krb5_realm = {}".format(domain_name.upper()))

                file_sssd.close()
                file_sssd = open(sssd_config_file_path, 'w')
                file_sssd.write(file_data)
                file_sssd.close()

                # Arrangement of chmod as 600 for sssd.conf
                (result_code, p_out, p_err) = self.util.execute("chmod 600 {}".format(sssd_config_file_path))
                if (result_code == 0):
                    self.logger.info("Chmod komutu başarılı bir şekilde çalıştırıldı")
                else:
                    self.logger.error("Chmod komutu başarısız : " + str(p_err))

            # Configure krb5 template
            krb5_config_template_path = "/usr/share/ahenk/base/registration/config-files/krb5_ad.conf"
            krb5_config_folder_path = "/etc"
            krb5_config_file_path = "/etc/krb5.conf"

            if not self.util.is_exist(krb5_config_folder_path):
                self.util.create_directory(krb5_config_folder_path)
                self.logger.info("{0} folder is created".format(krb5_config_folder_path))

            if self.util.is_exist(krb5_config_file_path):
                self.util.delete_file(krb5_config_file_path)
                self.logger.info("delete krb5 org conf")

            self.util.copy_file(krb5_config_template_path, krb5_config_folder_path)
            self.logger.info(
                "{0} config file is copied under {1}".format(krb5_config_template_path, krb5_config_folder_path))
            self.util.rename_file("/etc/krb5_ad.conf", "/etc/krb5.conf")

            # Configure krb5_ad.conf
            file_krb5 = open(krb5_config_file_path, 'r')
            file_data = file_krb5.read()
            file_data = file_data.replace("###default_realm###", "default_realm = {}".format(domain_name.upper()))
            file_krb5.close()
            file_krb5 = open(krb5_config_file_path, 'w')
            file_krb5.write(file_data)
            file_krb5.close()

            # Arrangement of chmod as 644 for krb5_ad.conf
            (result_code, p_out, p_err) = self.util.execute("chmod 644 {}".format(krb5_config_file_path))
            if (result_code == 0):
                self.logger.info("Chmod komutu başarılı bir şekilde çalıştırıldı")
            else:
                self.logger.error("Chmod komutu başarısız : " + str(p_err))

            # Configure sssd for language environment
            default_sssd_path = "/etc/default/sssd"
            file_default_sssd = open(default_sssd_path, 'r')
            file_data = file_default_sssd.read()

            if not self.util.is_exist(default_sssd_path):
                self.util.create_directory(default_sssd_path)
                self.logger.info("{0} folder is created".format(default_sssd_path))

            if self.util.is_exist(default_sssd_path):
                self.util.delete_file(default_sssd_path)
                self.logger.info("delete sssd org conf")

            if "LC_ALL=\"tr_CY.UTF-8\"" not in file_data:
                file_data = file_data + "\n" + "LC_ALL=\"tr_CY.UTF-8\""
                self.logger.info("/etc/default/sssd is configured")

            file_default_sssd.close()
            file_default_sssd = open(default_sssd_path, 'w')
            file_default_sssd.write(file_data)
            file_default_sssd.close()

            self.util.execute("systemctl restart nscd.service")
            self.logger.info("AD Login operation has been completed.")
            self.logger.info("AD Login işlemi başarı ile sağlandı.")
            return True

        except Exception as e:
            self.logger.error(str(e))
            self.logger.info("AD Login işlemi esnasında hata oluştu.")
            return False
Exemplo n.º 37
0
class ExecuteSSSDAuthentication:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.util = Util()

    def authenticate(self, server_address, dn, admin_dn, admin_password):
        try:
            ldap_pwdlockout_dn = "ou=PasswordPolicies" + "," + dn

            # pattern for clearing file data from spaces, tabs and newlines
            pattern = re.compile(r'\s+')

            sssd_config_template_path = "/usr/share/ahenk/base/registration/config-files/sssd.conf"
            sssd_config_folder_path = "/etc/sssd"
            sssd_config_file_path = "/etc/sssd/sssd.conf"
            sssd_language_conf = "/etc/default/sssd"

            common_session_conf_path = "/etc/pam.d/common-session"

            # copy configuration file to /etc/sssd/sssd.conf before package installation
            # create sssd folder in /etc
            if not self.util.is_exist(sssd_config_folder_path):
                self.util.create_directory(sssd_config_folder_path)
                self.logger.info(
                    "{0} folder is created".format(sssd_config_folder_path))

            # Copy sssd.conf template under /etc/sssd
            self.util.copy_file(sssd_config_template_path,
                                sssd_config_folder_path)
            self.logger.info("{0} config file is copied under {1}".format(
                sssd_config_template_path, sssd_config_folder_path))

            # Configure sssd.conf
            file_sssd = open(sssd_config_file_path, 'r')
            file_data = file_sssd.read()

            file_data = file_data.replace(
                "###ldap_pwdlockout_dn###",
                "ldap_pwdlockout_dn = " + ldap_pwdlockout_dn)
            file_data = file_data.replace(
                "###ldap_uri###",
                "ldap_uri = " + "ldap://" + server_address + "/")
            file_data = file_data.replace("###ldap_default_bind_dn###",
                                          "ldap_default_bind_dn = " + admin_dn)
            file_data = file_data.replace(
                "###ldap_default_authtok###",
                "ldap_default_authtok = " + admin_password)
            file_data = file_data.replace("###ldap_search_base###",
                                          "ldap_search_base = " + dn)
            file_data = file_data.replace("###ldap_user_search_base###",
                                          "ldap_user_search_base = " + dn)
            file_data = file_data.replace("###ldap_group_search_base###",
                                          "ldap_group_search_base = " + dn)
            file_data = file_data.replace(
                "###ldap_sudo_search_base###",
                "ldap_sudo_search_base = ou=Role,ou=Groups," + dn)

            file_sssd.close()
            file_sssd = open(sssd_config_file_path, 'w')
            file_sssd.write(file_data)
            file_sssd.close()

            # Install libpam-sss sssd-common for sssd authentication
            (result_code, p_out, p_err) = self.util.execute(
                "sudo apt install libpam-sss sssd-common -y")

            if result_code != 0:
                self.logger.error("SSSD packages couldn't be downloaded.")
                return False

            (result_code, p_out, p_err) = self.util.execute(
                "chmod 600 {}".format(sssd_config_file_path))
            if (result_code == 0):
                self.logger.info(
                    "Chmod komutu başarılı bir şekilde çalıştırıldı")
            else:
                self.logger.error("Chmod komutu başarısız : " + str(p_err))

            # configure common-session for creating home directories for ldap users
            file_common_session = open(common_session_conf_path, 'r')
            file_data = file_common_session.read()

            if "session optional        pam_mkhomedir.so skel=/etc/skel umask=077" not in file_data:
                file_data = file_data + "\n" + "session optional        pam_mkhomedir.so skel=/etc/skel umask=077"
                self.logger.info("common-session is configured")

            file_common_session.close()
            file_common_session = open(common_session_conf_path, 'w')
            file_common_session.write(file_data)
            file_common_session.close()

            # configure sssd for language environment
            file_default_sssd = open(sssd_language_conf, 'r')
            file_data = file_default_sssd.read()

            if "LC_ALL=\"tr_CY.UTF-8\"" not in file_data:
                file_data = file_data + "\n" + "LC_ALL=\"tr_CY.UTF-8\""
                self.logger.info("/etc/default/sssd is configured")

            file_default_sssd.close()
            file_default_sssd = open(sssd_language_conf, 'w')
            file_default_sssd.write(file_data)
            file_default_sssd.close()

            self.logger.info("Restarting sssd service.")
            self.util.execute("systemctl restart sssd.service")

            # Configure nsswitch.conf
            file_ns_switch = open("/etc/nsswitch.conf", 'r')
            file_data = file_ns_switch.read()

            # cleared file data from spaces, tabs and newlines
            text = pattern.sub('', file_data)

            is_configuration_done_before = False
            if "passwd:compatsss" not in text and "passwd:compat" in text:
                file_data = file_data.replace("passwd:         compat",
                                              "passwd:         compat sss")
                is_configuration_done_before = True

            if "passwd:filessystemdsss" not in text and "passwd:filessystemd" in text:
                file_data = file_data.replace(
                    "passwd:         files systemd",
                    "passwd:         files systemd sss")
                is_configuration_done_before = True

            if "group:compatsss" not in text and "group:compat" in text:
                file_data = file_data.replace("group:          compat",
                                              "group:          compat sss")
                is_configuration_done_before = True

            if "group:filessystemdsss" not in text and "group:filessystemd" in text:
                file_data = file_data.replace(
                    "group:          files systemd",
                    "group:          files systemd sss")
                is_configuration_done_before = True

            if "shadow:compatsss" not in text and "shadow:compat" in text:
                file_data = file_data.replace("shadow:         compat",
                                              "shadow:         compat sss")
                is_configuration_done_before = True

            if "shadow:filessss" not in text and "shadow:files" in text:
                file_data = file_data.replace("shadow:         files",
                                              "shadow:         files sss")
                is_configuration_done_before = True

            if "services:dbfilessss" not in text:
                file_data = file_data.replace("services:       db files",
                                              "services:       db files sss")
                is_configuration_done_before = True

            if "netgroup:nissss" not in text:
                file_data = file_data.replace("netgroup:       nis",
                                              "netgroup:       nis sss")
                is_configuration_done_before = True

            if "sudoers:filessss" not in text and "sudoers:files" in text:
                file_data = file_data.replace("sudoers:        files",
                                              "sudoers:        files sss")
                is_configuration_done_before = True
            elif "sudoers:filessss" in text:
                is_configuration_done_before = False
            else:
                file_data = file_data + "sudoers:        files sss"

            if is_configuration_done_before:
                self.logger.info(
                    "nsswitch.conf configuration has been completed")
            else:
                self.logger.info("nsswitch.conf is already configured")

            file_ns_switch.close()
            file_ns_switch = open("/etc/nsswitch.conf", 'w')
            file_ns_switch.write(file_data)
            file_ns_switch.close()

            self.util.execute("systemctl restart nscd.service")
            # self.util.execute("pam-auth-update --force")
            self.logger.info("LDAP Login operation has been completed.")

            self.logger.info("LDAP Login işlemi başarı ile sağlandı.")
            return True
        except Exception as e:
            self.logger.error(str(e))
            self.logger.info("LDAP Login işlemi esnasında hata oluştu.")
            return False
Exemplo n.º 38
0
class ExecuteLDAPLogin:
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.util = Util()

    def login(self, server_address, dn, version, admin_dn, admin_password):
        try:
            self.logger.info("----------------> server_address: " +
                             server_address)
            self.logger.info("----------------> dn: " + dn)
            self.logger.info("----------------> version: " + version)
            self.logger.info("----------------> admin_dn: " + admin_dn)
            self.logger.info("----------------> admin_password: "******"/bin/bash /usr/share/ahenk/base/registration/scripts/test.sh")
            (result_code, p_out, p_err) = self.util.execute(
                "/bin/bash /usr/share/ahenk/base/registration/scripts/ldap-login.sh {0} {1} {2} {3} {4}"
                .format(server_address, "\'" + dn + "\'",
                        "\'" + admin_dn + "\'", "\'" + admin_password + "\'",
                        version))
            if result_code == 0:
                self.logger.info("Script has run successfully")
            else:
                self.logger.error("Script could not run successfully: " +
                                  p_err)

            # pattern for clearing file data from spaces, tabs and newlines
            pattern = re.compile(r'\s+')

            pam_scripts_original_directory_path = "/usr/share/ahenk/pam_scripts_original"

            ldap_back_up_file_path = "/usr/share/ahenk/pam_scripts_original/ldap"
            ldap_original_file_path = "/usr/share/pam-configs/ldap"
            ldap_configured_file_path = "/usr/share/ahenk/plugins/ldap-login/config-files/ldap"

            pam_script_back_up_file_path = "/usr/share/ahenk/pam_scripts_original/pam_script"
            pam_script_original_file_path = "/usr/share/pam-configs/pam_script"
            pam_script_configured_file_path = "/usr/share/ahenk/plugins/ldap-login/config-files/pam_script"

            # create pam_scripts_original directory if not exists
            if not self.util.is_exist(pam_scripts_original_directory_path):
                self.logger.info("Creating {0} directory.".format(
                    pam_scripts_original_directory_path))
                self.util.create_directory(pam_scripts_original_directory_path)

            if self.util.is_exist(ldap_back_up_file_path):
                self.logger.info("Changing {0} with {1}.".format(
                    ldap_original_file_path, ldap_configured_file_path))
                self.util.copy_file(ldap_configured_file_path,
                                    ldap_original_file_path)
            else:
                self.logger.info(
                    "Backing up {0}".format(ldap_original_file_path))
                self.util.copy_file(ldap_original_file_path,
                                    ldap_back_up_file_path)
                self.logger.info("{0} file is replaced with {1}.".format(
                    ldap_original_file_path, ldap_configured_file_path))
                self.util.copy_file(ldap_configured_file_path,
                                    ldap_original_file_path)

            if self.util.is_exist(pam_script_back_up_file_path):
                self.util.copy_file(pam_script_configured_file_path,
                                    pam_script_original_file_path)
                self.logger.info("{0} is replaced with {1}.".format(
                    pam_script_original_file_path,
                    pam_script_configured_file_path))
            else:
                self.logger.info(
                    "Backing up {0}".format(pam_script_original_file_path))
                self.util.copy_file(pam_script_original_file_path,
                                    pam_script_back_up_file_path)
                self.logger.info("{0} file is replaced with {1}".format(
                    pam_script_original_file_path,
                    pam_script_configured_file_path))
                self.util.copy_file(pam_script_configured_file_path,
                                    pam_script_original_file_path)

            (result_code, p_out, p_err) = self.util.execute(
                "DEBIAN_FRONTEND=noninteractive pam-auth-update --package")
            if result_code == 0:
                self.logger.info(
                    "'DEBIAN_FRONTEND=noninteractive pam-auth-update --package' has run successfully"
                )
            else:
                self.logger.error(
                    "'DEBIAN_FRONTEND=noninteractive pam-auth-update --package' could not run successfully: "
                    + p_err)

            # Configure nsswitch.conf
            file_ns_switch = open("/etc/nsswitch.conf", 'r')
            file_data = file_ns_switch.read()

            # cleared file data from spaces, tabs and newlines
            text = pattern.sub('', file_data)

            is_configuration_done_before = False
            if ("passwd:compatldap" not in text):
                file_data = file_data.replace("passwd:         compat",
                                              "passwd:         compat ldap")
                is_configuration_done_before = True

            if ("group:compatldap" not in text):
                file_data = file_data.replace("group:          compat",
                                              "group:          compat ldap")
                is_configuration_done_before = True

            if ("shadow:compatldap" not in text):
                file_data = file_data.replace("shadow:         compat",
                                              "shadow:         compat ldap")
                is_configuration_done_before = True

            if is_configuration_done_before:
                self.logger.info(
                    "nsswitch.conf configuration has been completed")
            else:
                self.logger.info("nsswitch.conf is already configured")

            file_ns_switch.close()
            file_ns_switch = open("/etc/nsswitch.conf", 'w')
            file_ns_switch.write(file_data)
            file_ns_switch.close()

            # configure ldap-cache
            self.logger.info("Starting to ldap-cache configurations.")
            result_code, p_out, p_err = self.util.execute(
                "apt-get install nss-updatedb -y")
            if result_code != 0:
                self.logger.error(
                    "Error occured while downloading nss-updatedb.")
            else:
                self.logger.info(
                    "nss-updatedb downloaded successfully. Configuring /etc/nsswitch.conf."
                )
                file_ns_switch = open("/etc/nsswitch.conf", 'r')
                file_data = file_ns_switch.read()

                # cleared file data from spaces, tabs and newlines
                text = pattern.sub('', file_data)

                did_configuration_change = False
                if "passwd:compatldap[NOTFOUND=return]db" not in text:
                    file_data = file_data.replace(
                        "passwd:         compat ldap",
                        "passwd:         compat ldap [NOTFOUND=return] db")
                    did_configuration_change = True

                if "group:compatldap[NOTFOUND=return]db" not in text:
                    file_data = file_data.replace(
                        "group:          compat ldap",
                        "group:          compat ldap [NOTFOUND=return] db")
                    did_configuration_change = True

                if "gshadow:files" in text and "#gshadow:files" not in text:
                    file_data = file_data.replace("gshadow:        files",
                                                  "#gshadow:        files")
                    did_configuration_change = True

                if did_configuration_change:
                    self.logger.info(
                        "nsswitch.conf configuration has been configured for ldap cache."
                    )
                else:
                    self.logger.info(
                        "nsswitch.conf has already been configured for ldap cache."
                    )

                file_ns_switch.close()
                file_ns_switch = open("/etc/nsswitch.conf", 'w')
                file_ns_switch.write(file_data)
                file_ns_switch.close()
                self.util.execute("nss_updatedb ldap")

            # create cron job for ldap cache
            content = "#!/bin/bash\n" \
                      "nss-updatedb ldap"
            nss_update_cron_job_file_path = "/etc/cron.daily/nss-updatedb"
            if self.util.is_exist(nss_update_cron_job_file_path):
                self.logger.info(
                    "{0} exists. File will be deleted and creating new one.".
                    format(nss_update_cron_job_file_path))
                self.util.delete_file(nss_update_cron_job_file_path)
                self.util.create_file(nss_update_cron_job_file_path)
                self.util.write_file(nss_update_cron_job_file_path, content,
                                     'w+')
                self.util.execute("chmod +x " + nss_update_cron_job_file_path)
            else:
                self.logger.info(
                    "{0} doesnt exist. File will be created and content will be written."
                    .format(nss_update_cron_job_file_path))
                self.util.create_file(nss_update_cron_job_file_path)
                self.util.write_file(nss_update_cron_job_file_path, content,
                                     'w+')
                self.util.execute("chmod +x " + nss_update_cron_job_file_path)

            # configure /etc/libnss-ldap.conf
            libnss_ldap_file_path = "/etc/libnss-ldap.conf"
            content = "bind_policy hard" \
                      "\nnss_reconnect_tries 1" \
                      "\nnss_reconnect_sleeptime 1" \
                      "\nnss_reconnect_maxsleeptime 8" \
                      "\nnss_reconnect_maxconntries 2"
            if self.util.is_exist(libnss_ldap_file_path):
                self.logger.info("{0} exists.".format(libnss_ldap_file_path))
                self.util.execute("sed -i '/bind_policy hard/c\\' " +
                                  libnss_ldap_file_path)
                self.util.execute("sed -i '/nss_reconnect_tries 1/c\\' " +
                                  libnss_ldap_file_path)
                self.util.execute("sed -i '/nss_reconnect_sleeptime 1/c\\' " +
                                  libnss_ldap_file_path)
                self.util.execute(
                    "sed -i '/nss_reconnect_maxsleeptime 8/c\\' " +
                    libnss_ldap_file_path)
                self.util.execute(
                    "sed -i '/nss_reconnect_maxconntries 2/c\\' " +
                    libnss_ldap_file_path)
                self.util.write_file(libnss_ldap_file_path, content, 'a+')
                self.logger.info("Configuration has been made to {0}.".format(
                    libnss_ldap_file_path))

            result_code, p_out, p_err = self.util.execute(
                "apt-get install libnss-db libpam-ccreds -y")
            if result_code != 0:
                self.logger.error(
                    "Error occured while downloading libnss-db libpam-ccreds.")
            else:
                self.logger.error("libnss-db libpam-ccreds are downloaded.")

            # configure sudo-ldap
            sudo_ldap_conf_file_path = "/etc/sudo-ldap.conf"
            content = "sudoers_base ou=Roles," + dn \
                      + "\nBASE " + dn \
                      + "\nURI ldap://" + server_address
            # clean if config is already written
            self.util.execute("sed -i '/BASE /c\\' " +
                              sudo_ldap_conf_file_path)
            self.util.execute("sed -i '/sudoers_base /c\\' " +
                              sudo_ldap_conf_file_path)
            self.util.execute("sed -i '/URI /c\\' " + sudo_ldap_conf_file_path)

            if self.util.is_exist(sudo_ldap_conf_file_path):
                self.logger.info(
                    "{0} exists.".format(sudo_ldap_conf_file_path))
                self.util.write_file(sudo_ldap_conf_file_path, content, 'a+')
                self.logger.info(
                    "Content is written to {0} successfully.".format(
                        sudo_ldap_conf_file_path))

            # Configure lightdm.service
            # check if 99-pardus-xfce.conf exists if not create
            pardus_xfce_path = "/usr/share/lightdm/lightdm.conf.d/99-pardus-xfce.conf"
            if not self.util.is_exist(pardus_xfce_path):
                self.logger.info("99-pardus-xfce.conf does not exist.")
                self.util.create_file(pardus_xfce_path)

                file_lightdm = open(pardus_xfce_path, 'a')
                file_lightdm.write("[Seat:*]\n")
                file_lightdm.write("greeter-hide-users=true")
                file_lightdm.close()
                self.logger.info("lightdm has been configured.")
            else:
                self.logger.info(
                    "99-pardus-xfce.conf exists. Delete file and create new one."
                )
                self.util.delete_file(pardus_xfce_path)
                self.util.create_file(pardus_xfce_path)

                file_lightdm = open(pardus_xfce_path, 'a')
                file_lightdm.write("[Seat:*]")
                file_lightdm.write("greeter-hide-users=true")
                file_lightdm.close()
                self.logger.info("lightdm.conf has been configured.")
            self.util.execute("systemctl restart nscd.service")
            self.util.execute("pam-auth-update --force")
            self.logger.info("LDAP Login operation has been completed.")

            self.logger.info("LDAP Login işlemi başarı ile sağlandı.")
        except Exception as e:
            self.logger.error(str(e))
            self.logger.info("LDAP Login işlemi esnasında hata oluştu.")
            raise Exception(
                'LDAP Ayarları yapılırken hata oluştu. Lütfen ağ bağlantınızı kontrol ediniz. Deponuzun güncel olduğundan emin olunuz.'
            )