From 38720d2df69d40f3a550863889464e6131ffd6ce Mon Sep 17 00:00:00 2001 From: edip Date: Fri, 2 Nov 2018 14:01:49 +0300 Subject: [PATCH] Ahenk Registration for user authorization.. --- src/ahenkd.py | 47 ++- src/base/agreement/ask.py | 2 +- src/base/command/command_manager.py | 5 +- src/base/command/command_runner.py | 7 + src/base/execution/execution_manager.py | 15 + src/base/messaging/anonymous_messenger.py | 71 ++++- src/base/messaging/messaging.py | 47 ++- src/base/model/enum/message_type.py | 1 + src/base/plugin/plugin.py | 6 +- src/base/registration/registration.py | 353 ++++++++++++++++++++-- src/base/util/util.py | 7 + 11 files changed, 503 insertions(+), 58 deletions(-) diff --git a/src/ahenkd.py b/src/ahenkd.py index 91fbe44..450477d 100644 --- a/src/ahenkd.py +++ b/src/ahenkd.py @@ -29,6 +29,7 @@ from base.scope import Scope from base.system.system import System from base.task.task_manager import TaskManager from base.util.util import Util +from easygui import msgbox sys.path.append('../..') @@ -144,21 +145,47 @@ class AhenkDaemon(BaseDaemon): def check_registration(self): """ docstring""" - max_attempt_number = int(System.Hardware.Network.interface_size()) * 3 + # max_attempt_number = int(System.Hardware.Network.interface_size()) * 3 + max_attempt_number = 1 # self.logger.debug() # logger = Scope.getInstance().getLogger() registration = Scope.get_instance().get_registration() try: - while registration.is_registered() is False: + #if registration.is_registered() is False: + # self.logger.debug('Ahenk is not registered. Attempting for registration') + # if registration.registration_request() == False: + # self.registration_failed() + + if registration.is_registered() is False: + print("Registation attemp") max_attempt_number -= 1 self.logger.debug('Ahenk is not registered. Attempting for registration') - registration.registration_request() - if max_attempt_number < 0: - self.logger.warning('Number of Attempting for registration is over') - self.registration_failed() - break + #registration.registration_request() + + if registration.registration_request() == False: + if max_attempt_number < 0: + self.registration_failed() + else: + registration.registration_request() + + #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))) + + + def is_registered(self): + try: + registration = Scope.get_instance().get_registration() + if registration.is_registered() is False: + self.registration_failed() + + except Exception as e: + self.registration_failed() self.logger.error('Registration failed. Error message: {0}'.format(str(e))) @staticmethod @@ -170,8 +197,7 @@ class AhenkDaemon(BaseDaemon): def registration_failed(self): """ docstring""" - self.logger.error( - 'Registration failed. All registration attempts were failed. Ahenk is stopping...') + self.logger.error('Registration failed. All registration attempts were failed. Ahenk is stopping...') print('Registration failed. Ahenk is stopping..') ahenk_daemon.stop() @@ -265,6 +291,9 @@ class AhenkDaemon(BaseDaemon): self.logger.info('Execution Manager was set') self.check_registration() + + self.is_registered() + self.logger.info('Ahenk was registered') self.messenger = self.init_messenger() diff --git a/src/base/agreement/ask.py b/src/base/agreement/ask.py index 158c4a2..d584d5a 100644 --- a/src/base/agreement/ask.py +++ b/src/base/agreement/ask.py @@ -7,7 +7,7 @@ import easygui def ask(content, title): - choice = easygui.textbox(msg=title, text=content, codebox=0) + choice = easygui.buttonbox(msg=title, title=content, choices=['TAMAM']) if choice: print('Y') else: diff --git a/src/base/command/command_manager.py b/src/base/command/command_manager.py index eef575f..cad7d2e 100644 --- a/src/base/command/command_manager.py +++ b/src/base/command/command_manager.py @@ -73,6 +73,10 @@ class Commander(object): data['event'] = 'remove' data['plugins'] = params[3] + elif len(params) > 1 and params[1] == 'unregister': + data['event'] = params[1] + + elif len(params) > 5 and params[1] == 'send': data['event'] = params[1] response = dict() @@ -138,7 +142,6 @@ class Commander(object): print( 'Wrong or missing parameter.(-e|-s|-w parameters are optional) Usage: send -p -c -m|-f | -e|-s|-w') return None - else: print( 'Wrong or missing parameter. Usage: send -p -c -m|-f | -e|-s|-w') diff --git a/src/base/command/command_runner.py b/src/base/command/command_runner.py index 22694fc..2cfd080 100644 --- a/src/base/command/command_runner.py +++ b/src/base/command/command_runner.py @@ -160,6 +160,13 @@ class CommandRunner(object): 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']) diff --git a/src/base/execution/execution_manager.py b/src/base/execution/execution_manager.py index d341815..261351a 100644 --- a/src/base/execution/execution_manager.py +++ b/src/base/execution/execution_manager.py @@ -17,6 +17,7 @@ from base.scheduler.custom.schedule_job import ScheduleTaskJob from base.scope import Scope from base.system.system import System from base.util.util import Util +from easygui import * class ExecutionManager(object): @@ -43,6 +44,7 @@ class ExecutionManager(object): self.event_manager.register_event(MessageType.INSTALL_PLUGIN.value, self.install_plugin) self.event_manager.register_event(MessageType.RESPONSE_AGREEMENT.value, self.agreement_update) self.event_manager.register_event(MessageType.UPDATE_SCHEDULED_TASK.value, self.update_scheduled_task) + self.event_manager.register_event(MessageType.REGISTRATION_RESPONSE.value, self.unregister) # registration message for unregister event def agreement_update(self, arg): @@ -397,6 +399,19 @@ class ExecutionManager(object): self.task_manager.addTask(task) self.logger.debug('Task added') + def unregister(self, msg): + j = json.loads(msg) + status = str(j['status']).lower() + + if 'not_authorized' == str(status): + self.logger.info('Registration is failed. User not authorized') + msgbox('Ahenk etki alanından çıkarmak için yetkili kullanıcı haklarına sahip olmanız gerekmektedir.', + 'Kullanıcı Yetkilendirme Hatası') + else : + registration= Scope.get_instance().get_registration() + registration.purge_and_unregister() + + def json_to_task_bean(self, json_data, file_server_conf=None): plu = json_data['plugin'] plugin = PluginBean(p_id=plu['id'], active=plu['active'], create_date=plu['createDate'], deleted=plu['deleted'], diff --git a/src/base/messaging/anonymous_messenger.py b/src/base/messaging/anonymous_messenger.py index d007483..104d654 100644 --- a/src/base/messaging/anonymous_messenger.py +++ b/src/base/messaging/anonymous_messenger.py @@ -5,15 +5,20 @@ import json import sys import socket +from base.util.util import Util +import time +from base.system.system import System from sleekxmpp import ClientXMPP from base.scope import Scope +from easygui import msgbox + sys.path.append('../..') class AnonymousMessenger(ClientXMPP): - def __init__(self, message): + def __init__(self, message, host= None, servicename= None): # global scope of ahenk scope = Scope().get_instance() @@ -22,17 +27,20 @@ class AnonymousMessenger(ClientXMPP): self.registration = scope.get_registration() self.event_manager = scope.get_event_manager() - self.host = str(socket.gethostbyname(self.configuration_manager.get('CONNECTION', 'host'))) - self.service = str(self.configuration_manager.get('CONNECTION', 'servicename')) - self.port = str(self.configuration_manager.get('CONNECTION', 'port')) + if host is not None and servicename is not None: + self.host = str(host) + self.service = str(servicename) + self.port = str(self.configuration_manager.get('CONNECTION', 'port')) + + # self.host = str(socket.gethostbyname(self.configuration_manager.get('CONNECTION', 'host'))) + # self.service = str(self.configuration_manager.get('CONNECTION', 'servicename')) + # self.port = str(self.configuration_manager.get('CONNECTION', 'port')) ClientXMPP.__init__(self, self.service, None) self.message = message self.receiver_resource = self.configuration_manager.get('CONNECTION', 'receiverresource') - self.receiver = self.configuration_manager.get('CONNECTION', - 'receiverjid') + '@' + self.configuration_manager.get( - 'CONNECTION', 'servicename') + self.receiver = self.configuration_manager.get('CONNECTION','receiverjid') + '@' + self.configuration_manager.get('CONNECTION', 'servicename') if self.receiver_resource: self.receiver += '/' + self.receiver_resource @@ -85,11 +93,54 @@ class AnonymousMessenger(ClientXMPP): def recv_direct_message(self, msg): if msg['type'] in ['normal']: self.logger.debug('---------->Received message: {0}'.format(str(msg['body']))) - self.logger.debug('Disconnecting...') - self.disconnect() + self.logger.debug('Reading registration reply') j = json.loads(str(msg['body'])) message_type = j['type'] - self.event_manager.fireEvent(message_type, str(msg['body'])) + status = str(j['status']).lower() + dn = str(j['agentDn']) + self.logger.debug('Registration status: ' + str(status)) + + if 'not_authorized' == str(status): + self.logger.info('Registration is failed. User not authorized') + msgbox('Ahenk etki alanına alınamadı !! Sadece yetkili kullanıcılar etki alanına kayıt yapabilir.', 'Kullanıcı Yetkilendirme Hatası') + self.logger.debug('Disconnecting...') + self.disconnect() + + elif 'already_exists' == str(status) or 'registered' == str(status) or 'registered_without_ldap' == str(status): + try: + self.logger.info('Registred from server. Registration process starting.') + self.event_manager.fireEvent('REGISTRATION_SUCCESS', j) + msg = str(self.host) + " Etki Alanına hoş geldiniz." + msgbox(msg, "") + msg = "Değişikliklerin etkili olması için sistem yeniden başlayacaktır. Sistem yeniden başlatılıyor...." + msgbox(msg, "") + time.sleep(5) + self.logger.info('Disconnecting...') + self.disconnect() + + self.logger.info('Rebooting...') + Util.shutdown(); + System.Process.kill_by_pid(int(System.Ahenk.get_pid_number())) + sys.exit(2) + + + except Exception as e: + self.logger.error('Error Message: {0}.'.format(str(e))) + msgbox(str(e)) + self.logger.debug('Disconnecting...') + self.disconnect() + + + elif 'registration_error' == str(status): + self.logger.info('Registration is failed. New registration request will send') + #self.event_manager.fireEvent('REGISTRATION_ERROR', str(j)) + msgbox('Ahenk etki alanına alınamadı !! Kayıt esnasında hata oluştu. Lütfen sistem yöneticinize başvurunuz.', + 'Sistem Hatası') + self.logger.debug('Disconnecting...') + self.disconnect() + else: + self.event_manger.fireEvent(message_type, str(msg['body'])) + self.logger.debug('Fired event is: {0}'.format(message_type)) def send_direct_message(self, msg): self.logger.debug('<<--------Sending message: {0}'.format(msg)) diff --git a/src/base/messaging/messaging.py b/src/base/messaging/messaging.py index 7747330..20e3346 100644 --- a/src/base/messaging/messaging.py +++ b/src/base/messaging/messaging.py @@ -112,7 +112,7 @@ class Messaging(object): self.logger.debug('Get Policies message was created') return json_data - def registration_msg(self): + def registration_msg(self, userName= None, userPassword=None): data = dict() data['type'] = 'REGISTER' data['from'] = self.db_service.select_one_result('registration', 'jid', ' 1=1') @@ -125,6 +125,12 @@ class Messaging(object): data['ipAddresses'] = json_params['ipAddresses'] data['hostname'] = json_params['hostname'] + if userName is not None: + data["userName"] = str(userName) + + if userPassword is not None: + data["userPassword"] = str(userPassword) + data['timestamp'] = self.db_service.select_one_result('registration', 'timestamp', ' 1=1') json_data = json.dumps(data) self.logger.debug('Registration message was created') @@ -144,13 +150,42 @@ class Messaging(object): return json_data def unregister_msg(self): + from easygui import multpasswordbox,msgbox + + field_names = [] + field_names.append("Yetkili Kullanıcı") + field_names.append("Parola") + + field_values = multpasswordbox( + msg='Makineyi etki alanından çıkarmak için zorunlu alanları giriniz. Lütfen devam eden işlemlerini sonlandırdığınıza emin olunuz !', + title='ETKI ALANI ÇIKARMA', fields=(field_names)) + + if field_values is None: + return None; + + is_fieldvalue_empty = False; + + for value in field_values: + if value == '': + is_fieldvalue_empty = True; + + if is_fieldvalue_empty: + msgbox("Lütfen zorunlu alanları giriniz.", ok_button="Tamam") + return False; + data = dict() data['type'] = 'UNREGISTER' - data['from'] = str(self.conf_manager.get('REGISTRATION', 'from')) - data['password'] = str(self.conf_manager.get('REGISTRATION', 'password')) - data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses')) - data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses')) - data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname')) + data['from'] = str(self.conf_manager.get('CONNECTION', 'uid')) + data['password'] = str(self.conf_manager.get('CONNECTION', 'password')) + + user_registration_info = list(field_values) + + data['userName'] = user_registration_info[0]; + data['userPassword'] = user_registration_info[1]; + + #data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses')) + #data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses')) + #data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname')) # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ]) data['timestamp'] = Util.timestamp() json_data = json.dumps(data) diff --git a/src/base/model/enum/message_type.py b/src/base/model/enum/message_type.py index 46085b4..a677665 100644 --- a/src/base/model/enum/message_type.py +++ b/src/base/model/enum/message_type.py @@ -23,3 +23,4 @@ class MessageType(Enum): TASK_STATUS = 'TASK_STATUS' RESPONSE_AGREEMENT = 'RESPONSE_AGREEMENT' UPDATE_SCHEDULED_TASK = 'UPDATE_SCHEDULED_TASK' + REGISTRATION_RESPONSE ='REGISTRATION_RESPONSE' diff --git a/src/base/plugin/plugin.py b/src/base/plugin/plugin.py index 4bc59bc..fc0f01e 100644 --- a/src/base/plugin/plugin.py +++ b/src/base/plugin/plugin.py @@ -92,6 +92,9 @@ class Plugin(threading.Thread): self.messaging = scope.get_message_manager() self.db_service = scope.get_db_service() + self.configurationManager = scope.get_configuration_manager() + self.is_user_notify_active = self.configurationManager.get('MACHINE', 'agreement') + self.keep_run = True self.context = Context() @@ -126,12 +129,13 @@ class Plugin(threading.Thread): self.logger.debug('[Plugin] Sending notify to user about task process') - if System.Sessions.user_name() is not None and len(System.Sessions.user_name()) > 0: + if System.Sessions.user_name() is not None and len(System.Sessions.user_name()) > 0 and self.is_user_notify_active == 1: for user in System.Sessions.user_name(): Util.send_notify("Lider Ahenk", "{0} eklentisi şu anda bir görev çalıştırıyor.".format(self.getName()), System.Sessions.display(user), user) + self.context.put('taskData', task_data) self.context.put('taskId', item_obj.get_id()) diff --git a/src/base/registration/registration.py b/src/base/registration/registration.py index 3e181fd..52cda3f 100644 --- a/src/base/registration/registration.py +++ b/src/base/registration/registration.py @@ -6,17 +6,17 @@ import datetime import json import uuid from uuid import getnode as get_mac - from base.scope import Scope from base.messaging.anonymous_messenger import AnonymousMessenger from base.system.system import System -from base.timer.setup_timer import SetupTimer -from base.timer.timer import Timer from base.util.util import Util from helper import system as sysx import pwd -import os, signal - +from base.timer.setup_timer import SetupTimer +from base.timer.timer import Timer +from easygui import multpasswordbox, msgbox +import re +import sys class Registration: def __init__(self): @@ -28,8 +28,11 @@ class Registration: self.conf_manager = scope.get_configuration_manager() self.db_service = scope.get_db_service() self.util = Util() + self.service_name='im.liderahenk.org' - self.event_manager.register_event('REGISTRATION_RESPONSE', self.registration_process) + #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) if self.is_registered(): self.logger.debug('Ahenk already registered') @@ -37,33 +40,199 @@ class Registration: self.register(True) def registration_request(self): + 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()) + # SetupTimer.start(Timer(System.Ahenk.registration_timeout(), timeout_function=self.registration_timeout,checker_func=self.is_registered, kwargs=None)) + + self.host = self.conf_manager.get("CONNECTION", "host") + self.servicename = self.conf_manager.get("CONNECTION", "servicename") + + self.user_name ='' + self.user_password='' + + field_names = [] + if self.host == '': + field_names.append("Sunucu Adresi") + + + field_names.append("Yetkili Kullanıcı") + field_names.append("Parola") + + field_values = multpasswordbox(msg='Makineyi etki alanına almak için bilgileri ilgili alanlara giriniz. LÜTFEN DEVAM EDEN İŞLEMLERİ SONLANDIRDIĞINZA EMİN OLUNUZ !', + title='ETKI ALANINA KAYIT', fields=(field_names)) + + if field_values is None: + return False; + + is_fieldvalue_empty= False; + + for value in field_values : + if value == '' : + is_fieldvalue_empty = True; + + if is_fieldvalue_empty: + msgbox("Lütfen zorunlu alanları giriniz.", ok_button="Tamam") + return False; + + 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]; + else: + self.user_name = user_registration_info[0]; + self.user_password = user_registration_info[1]; + + #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.host,self.servicename) anon_messenger.connect_to_server() def ldap_registration_request(self): - self.logger.debug('Requesting LDAP registration') + self.logger.info('Requesting LDAP registration') self.messenger.send_Direct_message(self.message_manager.ldap_registration_msg()) - def registration_process(self, reg_reply): - self.logger.debug('Reading registration reply') - j = json.loads(reg_reply) - self.logger.debug('[Registration]' + j['message']) - status = str(j['status']).lower() - dn = str(j['agentDn']) - - self.logger.debug('Registration status: ' + str(status)) - - if 'already_exists' == str(status) or 'registered' == str(status) or 'registered_without_ldap' == str(status): - self.logger.debug('Current dn:' + dn) + def registration_success(self, reg_reply): + self.logger.info('Registration update starting') + try: + dn = str(reg_reply['agentDn']) + self.logger.info('Current dn:' + dn) + self.logger.info('updating host name and service') + self.install_and_config_ldap(reg_reply) + #self.disable_local_users() self.update_registration_attrs(dn) - elif 'registration_error' == str(status): - self.logger.info('Registration is failed. New registration request will send') - self.re_register() + + except Exception as e: + self.logger.error('Registartion error. Error Message: {0}.'.format(str(e))) + print(e) + raise + + 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 + + (result_code, p_out, p_err) = self.util.execute("/bin/bash /usr/share/ahenk/plugins/ldap-login/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") + self.change_pam_ldap_configs() else: - self.logger.error('Bad message type of registration response ') + self.logger.error("Script could not run successfully: " + p_err) + print("ERROR ---> " + str(p_err)) + 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 registration_error(self, reg_reply): + self.re_register() + + + def change_pam_ldap_configs(self): + # 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 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.logger.info("Operation finished") + def update_registration_attrs(self, dn=None): self.logger.debug('Registration configuration is updating...') @@ -74,14 +243,19 @@ class Registration: 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') - # self.disable_local_users() + + def is_registered(self): - try: if str(System.Ahenk.uid()): return True @@ -98,9 +272,8 @@ class Registration: return False def register(self, uuid_depend_mac=False): - cols = ['jid', 'password', 'registered', 'params', 'timestamp'] - vals = [str(System.Os.hostname()), str(self.generate_password()), 0, + 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 ') @@ -108,7 +281,6 @@ class Registration: self.logger.debug('Registration parameters were created') def get_registration_params(self): - parts = [] for part in System.Hardware.Disk.partitions(): parts.append(part[0]) @@ -186,6 +358,7 @@ class Registration: '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...') + msgbox('Etki alanı sunucusuna ulaşılamadı. Lütfen sunucu adresini kontrol ediniz....','HATA') System.Process.kill_by_pid(int(System.Ahenk.get_pid_number())) def disable_local_users(self): @@ -211,3 +384,123 @@ class Registration: self.util.execute(change_home.format(new_home_dir, new_username)) self.logger.debug("User: '{0}' will be disabled and changed username and home directory of username".format(p.pw_name)) + def purge_and_unregister(self): + from easygui import msgbox,boolbox + 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") + 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') + + msgbox("Ahenk etki alanından çıkarılmıştır.") + + if boolbox("Değişikliklerin etkili olması için sistem yeniden başlatmanız gerekmektedir.","",["Yeniden Başlat", "Vazgeç"]): + Util.shutdown() + + 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" in text: + file_data = file_data.replace("passwd: compat ldap", "passwd: compat") + did_configuration_change = True + + if "group:compatldap" in text: + file_data = file_data.replace("group: compat ldap", "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 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 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', '') + + with open(System.Ahenk.config_path(), 'w') as file: + config.write(file) + file.close() + print('Ahenk cleaned.') + except Exception as e: + print('Error while running clean command. Error Message {0}'.format(str(e))) + diff --git a/src/base/util/util.py b/src/base/util/util.py index 3a4a5b2..c772093 100644 --- a/src/base/util/util.py +++ b/src/base/util/util.py @@ -24,6 +24,11 @@ class Util: def close_session(username): Util.execute('pkill -9 -u {0}'.format(username)) + @staticmethod + def shutdown(): + print("shutting down") + Util.execute('reboot') + @staticmethod def create_file(full_path): try: @@ -147,6 +152,8 @@ class Util: process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=shell) + Scope.get_instance().get_logger().debug('Executing command: ' + str(command)) + if result is True: result_code = process.wait() p_out = process.stdout.read().decode("unicode_escape")