From ecce5632e4c9c8666a7689dc23567ba382d51144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tuncay=20=C3=87OLAK?= Date: Tue, 27 Dec 2022 10:32:14 +0300 Subject: [PATCH] Syncing /usr/share/ahenk to src and recreating ahenk.install --- debian/ahenk.install | 8 + usr/share/ahenk/ahenkd.py | 10 +- .../ahenk/base/command/command_runner.py | 177 +++++++------- .../ahenk/base/default_config/__init__.py | 0 .../base/default_config/default_config.py | 53 +++++ .../ahenk.pulseaudio.start.desktop | 10 + .../base/default_policy/default_policy.py | 16 +- .../base/messaging/anonymous_messenger.py | 24 +- usr/share/ahenk/base/messaging/messaging.py | 19 +- usr/share/ahenk/base/messaging/messenger.py | 43 +++- .../base/registration/config-files/sssd.conf | 2 - .../registration/config-files/sssd_ad.conf | 2 +- .../config-files/sssd_ad_dns.conf | 2 +- .../registration/execute_cancel_ldap_login.py | 2 +- .../execute_cancel_sssd_authentication.py | 2 +- .../base/registration/execute_ldap_login.py | 2 +- .../execute_sssd_ad_authentication.py | 29 ++- .../execute_sssd_authentication.py | 2 +- .../ahenk/base/registration/registration.py | 14 +- usr/share/ahenk/base/system/disk_info.py | 57 ++++- usr/share/ahenk/base/system/system.py | 60 +++-- .../plugins/ldap-login/execute_ad_login.py | 7 +- .../ahenk/plugins/local-user/add_user.py | 20 +- .../ahenk/plugins/local-user/edit_user.py | 20 +- .../plugins/manage-root/set_root_password.py | 7 +- .../ahenk/plugins/network-manager/add_dns.py | 4 +- .../plugins/network-manager/add_domain.py | 2 +- .../ahenk/plugins/network-manager/add_host.py | 4 +- .../plugins/network-manager/add_network.py | 4 +- .../plugins/package-manager/check_package.py | 59 +++-- .../plugins/resource-usage/agent_info.py | 10 + .../resource-usage/resource_info_fetcher.py | 14 +- .../ahenk/plugins/service/get_services.py | 15 +- .../ahenk/plugins/service/service_list.py | 30 +-- .../ahenk/plugins/usb/delete-usb-rules.py | 47 ++++ usr/share/ahenk/plugins/usb/get-usb-rules.py | 73 ++++++ .../ahenk/plugins/usb/manage-usb-rules.py | 217 ++++++++++++++++++ .../plugins/usb/scripts/DISABLED_printer.sh | 2 +- .../plugins/usb/scripts/DISABLED_usbhid.sh | 4 +- .../usb/scripts/DISABLED_usbstorage.sh | 4 +- .../plugins/usb/scripts/DISABLED_webcam.sh | 4 +- usr/share/libpam-script/pam_script_ses_close | 10 +- usr/share/libpam-script/pam_script_ses_open | 12 +- 43 files changed, 864 insertions(+), 239 deletions(-) create mode 100644 usr/share/ahenk/base/default_config/__init__.py create mode 100644 usr/share/ahenk/base/default_config/default_config.py create mode 100644 usr/share/ahenk/base/default_policy/config-files/ahenk.pulseaudio.start.desktop create mode 100644 usr/share/ahenk/plugins/usb/delete-usb-rules.py create mode 100644 usr/share/ahenk/plugins/usb/get-usb-rules.py create mode 100644 usr/share/ahenk/plugins/usb/manage-usb-rules.py diff --git a/debian/ahenk.install b/debian/ahenk.install index 25b3bd2..c4555ce 100644 --- a/debian/ahenk.install +++ b/debian/ahenk.install @@ -16,12 +16,16 @@ usr/share/ahenk/base/config/config_manager.py usr/share/ahenk/base/config/__init__.py usr/share/ahenk/base/config usr/share/ahenk/base/system/system.py +usr/share/ahenk/base/system/disk_info.py usr/share/ahenk/base/system usr/share/ahenk/base/timer/setup_timer.py usr/share/ahenk/base/timer/timer.py usr/share/ahenk/base/timer usr/share/ahenk/base/util/util.py usr/share/ahenk/base/util +usr/share/ahenk/base/default_config/__init__.py +usr/share/ahenk/base/default_config/default_config.py +usr/share/ahenk/base/default_config usr/share/ahenk/base/event/event_base.py usr/share/ahenk/base/event/event_manager.py usr/share/ahenk/base/event @@ -48,6 +52,7 @@ usr/share/ahenk/base/messaging/__init__.py usr/share/ahenk/base/messaging/message_response_queue.py usr/share/ahenk/base/messaging usr/share/ahenk/base/default_policy/config-files/xfce4-notifyd.xml +usr/share/ahenk/base/default_policy/config-files/ahenk.pulseaudio.start.desktop usr/share/ahenk/base/default_policy/config-files usr/share/ahenk/base/default_policy/default_policy.py usr/share/ahenk/base/default_policy/__init__.py @@ -263,7 +268,10 @@ usr/share/ahenk/plugins/usb/scripts/DISABLED_webcam.sh usr/share/ahenk/plugins/usb/scripts/ENABLED_webcam.sh usr/share/ahenk/plugins/usb/scripts/ENABLED_usbhid.sh usr/share/ahenk/plugins/usb/scripts +usr/share/ahenk/plugins/usb/get-usb-rules.py +usr/share/ahenk/plugins/usb/delete-usb-rules.py usr/share/ahenk/plugins/usb/init.py +usr/share/ahenk/plugins/usb/manage-usb-rules.py usr/share/ahenk/plugins/usb/main.py usr/share/ahenk/plugins/usb/logout.py usr/share/ahenk/plugins/usb/policy.py diff --git a/usr/share/ahenk/ahenkd.py b/usr/share/ahenk/ahenkd.py index ebcef46..7c9e4eb 100644 --- a/usr/share/ahenk/ahenkd.py +++ b/usr/share/ahenk/ahenkd.py @@ -30,6 +30,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 base.default_config.default_config import DefaultConfig from easygui import msgbox sys.path.append('../..') @@ -159,7 +160,7 @@ class AhenkDaemon(BaseDaemon): # self.registration_failed() while registration.is_registered() is False: - print("Registration attemp") + 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) @@ -274,6 +275,10 @@ class AhenkDaemon(BaseDaemon): else: self.logger.info('local users will not be disabled because local_user_paramater is FALSE') + def default_settings(self): + default_config = DefaultConfig() + default_config.check_sssd_settings() + def run(self): """ docstring""" print('Ahenk running...') @@ -319,6 +324,8 @@ class AhenkDaemon(BaseDaemon): self.init_execution_manager() self.logger.info('Execution Manager was set') + self.default_settings() + self.check_registration() self.is_registered() @@ -341,7 +348,6 @@ class AhenkDaemon(BaseDaemon): # if registration.is_ldap_registered() is False: # logger.debug('Attempting to registering ldap') # registration.ldap_registration_request() #TODO work on message - self.logger.info('LDAP registration of Ahenk is completed') self.messenger.send_direct_message('test') diff --git a/usr/share/ahenk/base/command/command_runner.py b/usr/share/ahenk/base/command/command_runner.py index 8165cc4..84c2f23 100644 --- a/usr/share/ahenk/base/command/command_runner.py +++ b/usr/share/ahenk/base/command/command_runner.py @@ -60,6 +60,7 @@ class CommandRunner(object): 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}.' @@ -72,110 +73,114 @@ class CommandRunner(object): if str(json_data['event']) == 'login' and self.check_last_login(): username = json_data['username'] - display = json_data['display'] - desktop = json_data['desktop'] + 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'] + ip = None + if 'ip' in json_data: + ip = json_data['ip'] - domain = None - if 'domain' in json_data: - domain = json_data['domain'] + 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)) + 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 + 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 + 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 (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 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]) - 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 - # 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()) - # 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) - 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 - 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)) - 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) + 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'] - self.execute_manager.remove_user_executed_policy_dict(username) - self.plugin_manager.process_mode('logout', username) - self.plugin_manager.process_mode('safe', username) - 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'] + 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)) + 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( diff --git a/usr/share/ahenk/base/default_config/__init__.py b/usr/share/ahenk/base/default_config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/usr/share/ahenk/base/default_config/default_config.py b/usr/share/ahenk/base/default_config/default_config.py new file mode 100644 index 0000000..8e55ab0 --- /dev/null +++ b/usr/share/ahenk/base/default_config/default_config.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# checked config when restarted agent service. Example, sssd language settings.. + +from base.scope import Scope +from base.util.util import Util + + +class DefaultConfig: + + def __init__(self): + scope = Scope().get_instance() + self.logger = scope.get_logger() + + 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() + + diff --git a/usr/share/ahenk/base/default_policy/config-files/ahenk.pulseaudio.start.desktop b/usr/share/ahenk/base/default_policy/config-files/ahenk.pulseaudio.start.desktop new file mode 100644 index 0000000..317ee1a --- /dev/null +++ b/usr/share/ahenk/base/default_policy/config-files/ahenk.pulseaudio.start.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Name=sesbaslat +Comment=Start the PulseAudio Sound System +Exec=sh -c 'killall pulseaudio; sleep 3; pulseaudio --start' +Terminal=false +Type=Application +Categories= +GenericName= +X-GNOME-Autostart-Phase=Initialization +X-KDE-autostart-phase=1 \ No newline at end of file diff --git a/usr/share/ahenk/base/default_policy/default_policy.py b/usr/share/ahenk/base/default_policy/default_policy.py index e1c82fa..d8c0d60 100644 --- a/usr/share/ahenk/base/default_policy/default_policy.py +++ b/usr/share/ahenk/base/default_policy/default_policy.py @@ -134,4 +134,18 @@ class DefaultPolicy: 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.") \ No newline at end of file + self.logger.info("'" + app_name_for_blocking + "' is already added to muted_applications tag.") + + # create pulseaudio autostart file while user opening session + def create_pulseaudio_autostart(self): + pulseaudio_des_path = "/etc/xdg/autostart/ahenk.pulseaudio.start.desktop" + pulseaudio_src_path = "/usr/share/ahenk/base/default_policy/config-files/ahenk.pulseaudio.start.desktop" + pulseaudio_old_file = "/etc/xdg/autostart/ahenk.pulseaudio.desktop" + if Util.is_exist(pulseaudio_old_file): + Util.delete_file(pulseaudio_old_file) + + if not Util.is_exist(pulseaudio_des_path): + Util.copy_file(pulseaudio_src_path, pulseaudio_des_path) + self.logger.info("Copy pulseaudio autostart file") + else: + self.logger.info("Pulseaudio autostart file already exist") diff --git a/usr/share/ahenk/base/messaging/anonymous_messenger.py b/usr/share/ahenk/base/messaging/anonymous_messenger.py index 729f24e..b2fc7e5 100644 --- a/usr/share/ahenk/base/messaging/anonymous_messenger.py +++ b/usr/share/ahenk/base/messaging/anonymous_messenger.py @@ -95,13 +95,23 @@ class AnonymousMessenger(ClientXMPP): def recv_direct_message(self, msg): if msg['type'] in ['normal']: - self.logger.info('---------->Received message: {0}'.format(str(msg['body']))) + self.logger.info('Reading registration reply') j = json.loads(str(msg['body'])) message_type = j['type'] status = str(j['status']).lower() dn = str(j['agentDn']) self.logger.debug('Registration status: ' + str(status)) + is_password = False + body_without_password = json.loads(str(msg['body'])) + for key, value in body_without_password.items(): + if "password" in key.lower(): + body_without_password[key] = "********" + is_password = True + if is_password: + self.logger.info('---------->Received message: {0}'.format(str(body_without_password))) + else: + self.logger.info('---------->Received message: {0}'.format(str(msg['body']))) if 'not_authorized' == str(status): self.logger.debug('[REGISTRATION IS FAILED]. User not authorized') @@ -154,5 +164,15 @@ class AnonymousMessenger(ClientXMPP): self.logger.debug('Fired event is: {0}'.format(message_type)) def send_direct_message(self, msg): - self.logger.debug('<<--------Sending message: {0}'.format(msg)) + body = json.loads(str(msg)) + if body['type'] == "REGISTER" or body['type'] == "UNREGISTER": + is_password = False + for key, value in body.items(): + if "password" in key.lower(): + body[key] = "********" + is_password = True + if is_password: + self.logger.info('<<--------Sending message: {0}'.format(body)) + else: + self.logger.info('<<--------Sending message: {0}'.format(msg)) self.send_message(mto=self.receiver, mbody=msg, mtype='normal') diff --git a/usr/share/ahenk/base/messaging/messaging.py b/usr/share/ahenk/base/messaging/messaging.py index a1f5c37..7ecb32d 100644 --- a/usr/share/ahenk/base/messaging/messaging.py +++ b/usr/share/ahenk/base/messaging/messaging.py @@ -2,12 +2,12 @@ # -*- coding: utf-8 -*- # Author: Volkan Şahin import json +import os from base.scope import Scope from base.system.system import System from base.util.util import Util from base.system.disk_info import DiskInfo -import os # TODO Message Factory @@ -84,6 +84,7 @@ class Messaging(object): self.logger.debug('USER IP : '+ str(ip)+ ' IPADDRESSES : '+ str(System.Hardware.Network.ip_addresses()).replace('[', '').replace(']', '')) + data['hardware.monitors'] = str(System.Hardware.monitors()), data['hardware.screens'] = str(System.Hardware.screens()), data['hardware.usbDevices'] = str(System.Hardware.usb_devices()), @@ -91,10 +92,10 @@ class Messaging(object): data['hardware.systemDefinitions'] = str(System.Hardware.system_definitions()), if len(ssd_list) > 0: - data['hardware.disk.ssd.info'] = ssd_list + data['hardwareDiskSsdInfo'] = str(ssd_list) if len(hdd_list) > 0: - data['hardware.disk.hdd.info'] = hdd_list + data['hardwareDiskHddInfo'] = str(hdd_list) json_data = json.dumps(data) self.logger.debug('Login message was created') @@ -161,7 +162,17 @@ class Messaging(object): data['timestamp'] = self.db_service.select_one_result('registration', 'timestamp', ' 1=1') json_data = json.dumps(data) self.logger.debug('Registration message was created') - self.logger.info('Registration message was created. Data content: '+ json_data) + + body = json.loads(str(json_data)) + is_password = False + for key, value in body.items(): + if "password" in key.lower(): + body[key] = "********" + is_password = True + if is_password: + self.logger.info('Registration message was created. Data content: {0}'.format(body)) + + #self.logger.info('Registration message was created. Data content: ' + json_data) return json_data def ldap_registration_msg(self): diff --git a/usr/share/ahenk/base/messaging/messenger.py b/usr/share/ahenk/base/messaging/messenger.py index be49d52..8709c84 100644 --- a/usr/share/ahenk/base/messaging/messenger.py +++ b/usr/share/ahenk/base/messaging/messenger.py @@ -92,7 +92,17 @@ class Messenger(ClientXMPP): def send_direct_message(self, msg): try: - self.logger.info('<<--------Sending message: {0}'.format(msg)) + body = json.loads(str(msg)) + if body['type'] == "REGISTER" or body['type'] == "UNREGISTER": + is_password = False + for key, value in body.items(): + if "password" in key.lower(): + body[key] = "********" + is_password = True + if is_password: + self.logger.info('<<--------Sending message: {0}'.format(body)) + else: + self.logger.info('<<--------Sending message: {0}'.format(msg)) self.send_message(mto=self.receiver, mbody=msg, mtype='normal') except Exception as e: self.logger.error( @@ -109,12 +119,31 @@ class Messenger(ClientXMPP): self.logger.info('---------->Received message: {0}'.format(str(msg['body']))) if j['type'] == "EXECUTE_TASK": - i = json.loads(str(j['task'])) - plugin_name = i['plugin']['name'] - if plugin_name == "manage-root": - parameter_map = i['parameterMap'] - parameter_map.pop("RootPassword") - self.logger.info("---------->Received message: {}".format(str(parameter_map))) + message = json.loads(str(msg['body'])) + task = json.loads(str(message['task'])) + #plugin_name = task['plugin']['name'] + parameter_map = task['parameterMap'] + use_file_transfer = message['fileServerConf'] + is_password = False + for key, value in parameter_map.items(): + if "password" in key.lower(): + parameter_map[key] = "********" + task['parameterMap'] = parameter_map + message['task'] = task + is_password = True + if use_file_transfer != None: + #message['fileServerConf'] = "*******" + file_server_conf = message['fileServerConf'] + file_server_param = file_server_conf['parameterMap'] + for key, value in file_server_param.items(): + if "password" in key.lower(): + file_server_param[key] = "********" + file_server_conf['parameterMap'] = file_server_param + #message['fileServerConf']['parameterMap'] = file_server_param + message['fileServerConf'] = file_server_conf + is_password = True + if is_password: + self.logger.info('---------->Received message: {0}'.format(str(message))) else: self.logger.info('---------->Received message: {0}'.format(str(msg['body']))) self.event_manger.fireEvent(message_type, str(msg['body'])) diff --git a/usr/share/ahenk/base/registration/config-files/sssd.conf b/usr/share/ahenk/base/registration/config-files/sssd.conf index 38e467a..a95df1f 100644 --- a/usr/share/ahenk/base/registration/config-files/sssd.conf +++ b/usr/share/ahenk/base/registration/config-files/sssd.conf @@ -17,7 +17,6 @@ debug_level = 9 id_provider = ldap auth_provider = ldap access_provider = ldap -#ldap_access_filter = (employeeType=admin) ldap_access_order = ppolicy pam_verbosity=2 ###ldap_pwdlockout_dn### @@ -34,7 +33,6 @@ ldap_user_gecos = cn ldap_tls_reqcert = never ldap_auth_disable_tls_never_use_in_production = true override_shell = /bin/bash -enumerate = true cache_credentials = true sudo_provider = ldap ###ldap_sudo_search_base### diff --git a/usr/share/ahenk/base/registration/config-files/sssd_ad.conf b/usr/share/ahenk/base/registration/config-files/sssd_ad.conf index ddb1adc..2b83821 100644 --- a/usr/share/ahenk/base/registration/config-files/sssd_ad.conf +++ b/usr/share/ahenk/base/registration/config-files/sssd_ad.conf @@ -12,7 +12,7 @@ config_file_version = 2 services = nss, pam ###[domain/### -###ad_domain### +###ad_server### ###krb5_realm### realmd_tags = manages-system joined-with-adcli cache_credentials = True diff --git a/usr/share/ahenk/base/registration/config-files/sssd_ad_dns.conf b/usr/share/ahenk/base/registration/config-files/sssd_ad_dns.conf index 9397ddd..3aebf74 100644 --- a/usr/share/ahenk/base/registration/config-files/sssd_ad_dns.conf +++ b/usr/share/ahenk/base/registration/config-files/sssd_ad_dns.conf @@ -12,7 +12,7 @@ config_file_version = 2 services = nss, pam ###[domain/### -###ad_domain### +###ad_server### ###krb5_realm### realmd_tags = manages-system joined-with-adcli cache_credentials = True diff --git a/usr/share/ahenk/base/registration/execute_cancel_ldap_login.py b/usr/share/ahenk/base/registration/execute_cancel_ldap_login.py index 5b91b7e..889e1e5 100644 --- a/usr/share/ahenk/base/registration/execute_cancel_ldap_login.py +++ b/usr/share/ahenk/base/registration/execute_cancel_ldap_login.py @@ -16,7 +16,7 @@ class ExecuteCancelLDAPLogin: 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 purge libpam-ldap libnss-ldap ldap-utils sudo-ldap nss-updatedb libnss-db libpam-ccreds libsss-sudo -y") self.util.execute("apt autoremove -y") self.logger.info('purging successfull') diff --git a/usr/share/ahenk/base/registration/execute_cancel_sssd_authentication.py b/usr/share/ahenk/base/registration/execute_cancel_sssd_authentication.py index 791b216..92b009d 100644 --- a/usr/share/ahenk/base/registration/execute_cancel_sssd_authentication.py +++ b/usr/share/ahenk/base/registration/execute_cancel_sssd_authentication.py @@ -14,7 +14,7 @@ class ExecuteCancelSSSDAuthentication: self.util = Util() def cancel(self): - self.util.execute("apt purge libpam-sss sssd-common -y") + self.util.execute("apt purge libpam-sss sssd-common libsss-sudo -y") self.util.execute("apt autoremove -y") if self.util.is_exist("/etc/sssd"): diff --git a/usr/share/ahenk/base/registration/execute_ldap_login.py b/usr/share/ahenk/base/registration/execute_ldap_login.py index 2e189fe..b752249 100644 --- a/usr/share/ahenk/base/registration/execute_ldap_login.py +++ b/usr/share/ahenk/base/registration/execute_ldap_login.py @@ -178,7 +178,7 @@ class ExecuteLDAPLogin: 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") + result_code, p_out, p_err = self.util.execute("apt-get install libnss-db libpam-ccreds libsss-sudo -y") if result_code != 0: self.logger.error("Error occured while downloading libnss-db libpam-ccreds.") else: diff --git a/usr/share/ahenk/base/registration/execute_sssd_ad_authentication.py b/usr/share/ahenk/base/registration/execute_sssd_ad_authentication.py index af8ffb2..1440292 100644 --- a/usr/share/ahenk/base/registration/execute_sssd_ad_authentication.py +++ b/usr/share/ahenk/base/registration/execute_sssd_ad_authentication.py @@ -1,6 +1,7 @@ #!/usr/bin/python3 # -*- coding: utf-8 -*- # Author: Agah Hulusi ÖZ +import subprocess from base.scope import Scope from base.util.util import Util @@ -134,7 +135,7 @@ class ExecuteSSSDAdAuthentication: # 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") + "sudo apt-get -y install sssd sssd-tools adcli packagekit samba-common-bin samba-libs libsss-sudo") if (result_code == 0): self.logger.info("İndirmeler Başarılı") else: @@ -155,6 +156,10 @@ class ExecuteSSSDAdAuthentication: file_default_pam.close() self.discover_try_counter2 = 0 + + + + try: while (True): self.discover_try_counter2 = self.discover_try_counter2 + 1 @@ -179,7 +184,7 @@ class ExecuteSSSDAdAuthentication: if (self.join_try_counter == 5): break else: - (result_code, p_out, p_err) = self.util.execute( + (result_code, p_out, p_err) = self.execute_command( "echo \"{0}\" | realm join --user={1} {2}".format(password, ad_username, domain_name.upper())) if (result_code == 0): @@ -227,7 +232,7 @@ class ExecuteSSSDAdAuthentication: 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("###ad_server###", "ad_server = {}".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(), @@ -271,7 +276,7 @@ class ExecuteSSSDAdAuthentication: 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("###ad_server###", "ad_server = {}".format(domain_name)) file_data = file_data.replace("###krb5_realm###", "krb5_realm = {}".format(domain_name.upper())) file_sssd.close() @@ -352,3 +357,19 @@ class ExecuteSSSDAdAuthentication: self.logger.info("AD Login işlemi esnasında hata oluştu.") return False + def execute_command(self, command, stdin=None, env=None, cwd=None, shell=True, result=True): + + try: + process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, + stdout=subprocess.PIPE, shell=shell) + self.logger.debug('Executing command for ad registration') + if result is True: + result_code = process.wait() + p_out = process.stdout.read().decode("unicode_escape") + p_err = process.stderr.read().decode("unicode_escape") + return result_code, p_out, p_err + else: + return None, None, None + except Exception as e: + return 1, 'Error Message: {0}'.format(str(e)), '' + diff --git a/usr/share/ahenk/base/registration/execute_sssd_authentication.py b/usr/share/ahenk/base/registration/execute_sssd_authentication.py index a23f613..3375853 100644 --- a/usr/share/ahenk/base/registration/execute_sssd_authentication.py +++ b/usr/share/ahenk/base/registration/execute_sssd_authentication.py @@ -56,7 +56,7 @@ class ExecuteSSSDAuthentication: 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") + (result_code, p_out, p_err) = self.util.execute("sudo apt install libpam-sss sssd-common libsss-sudo -y") if result_code != 0: diff --git a/usr/share/ahenk/base/registration/registration.py b/usr/share/ahenk/base/registration/registration.py index 2b60617..d682f9d 100644 --- a/usr/share/ahenk/base/registration/registration.py +++ b/usr/share/ahenk/base/registration/registration.py @@ -152,7 +152,7 @@ class Registration: self.install_and_config_ad(reg_reply) self.change_permissions_for_local_users() - self.create_ahenk_pulseaudio_desktop_file() + # self.create_ahenk_pulseaudio_desktop_file() except Exception as e: self.logger.error('Registration error. Error Message: {0}.'.format(str(e))) @@ -297,12 +297,12 @@ class Registration: 'processor': System.Hardware.Cpu.brand(), 'agentVersion': Util.get_agent_version(), } - + ssd_list, hdd_list = DiskInfo.get_all_disks() if len(ssd_list) > 0: - params['hardware.disk.ssd.info'] = ssd_list + params['hardware.disk.ssd.info'] = str(ssd_list) if len(hdd_list) > 0: - params['hardware.disk.hdd.info'] = hdd_list + params['hardware.disk.hdd.info'] = str(hdd_list) return json.dumps(params) @@ -637,6 +637,12 @@ class Registration: def delete_ahenk_pulseaudio_desktop_file(self): ahenkpulseaudio = "/etc/xdg/autostart/ahenk.pulseaudio.desktop" + pulseaudio_start_file = "/etc/xdg/autostart/ahenk.pulseaudio.start.desktop" + if self.util.is_exist(pulseaudio_start_file): + self.util.delete_file(pulseaudio_start_file) + self.logger.info("ahenk.pulseaudio.start.desktop autostart file deleted") + else: + self.logger.info("ahenk.pulseaudio.start.desktop autostart file doesn't exist") if self.util.is_exist(ahenkpulseaudio): self.util.delete_file(ahenkpulseaudio) self.logger.info("ahenk.pulseaudio.desktop autostart file deleted") diff --git a/usr/share/ahenk/base/system/disk_info.py b/usr/share/ahenk/base/system/disk_info.py index af785b9..2b149ba 100644 --- a/usr/share/ahenk/base/system/disk_info.py +++ b/usr/share/ahenk/base/system/disk_info.py @@ -1,15 +1,50 @@ -#!/usr/bin/env python3 +# !/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: Agah Hulusi ÖZ from base.util.util import Util +import psutil # HDD and SSD disk information class DiskInfo(): + @staticmethod + def total_disk_used(): + ssd_list, hdd_list = DiskInfo.get_all_disks() + total_disk_usage = 0 + if len(ssd_list) > 0: + for disk in ssd_list: + total_disk_usage += int(disk['used']) + if len(hdd_list) > 0: + for disk in hdd_list: + total_disk_usage += int(disk['used']) + return total_disk_usage + + @staticmethod + def total_disk(): + ssd_list, hdd_list = DiskInfo.get_all_disks() + total_size = 0 + for disk in ssd_list: + total_size += int(disk['total']) + for disk in hdd_list: + total_size += int(disk['total']) + return total_size + + @staticmethod + def total_disk_free(): + ssd_list, hdd_list = DiskInfo.get_all_disks() + total_disk_free = 0 + if len(ssd_list) > 0: + for disk in ssd_list: + total_disk_free += int(disk['total']) - int(disk['used']) + if len(hdd_list) > 0: + for disk in hdd_list: + total_disk_free += int(disk['total']) - int(disk['used']) + return total_disk_free + @staticmethod def get_all_disks(): - result_code, p_out, p_err = Util.execute("lsblk -b -o NAME,TYPE,ROTA,SIZE,RM,HOTPLUG,FSUSED | grep -v loop | awk '$5 == \"0\" { print $0 }'") + result_code, p_out, p_err = Util.execute("lsblk -b -o NAME,TYPE,ROTA,SIZE,RM,HOTPLUG,MOUNTPOINT,FSUSED | grep -v loop | awk '$5 == \"0\" { print $0 }'") txt = p_out.split("\n") while '' in txt: txt.remove('') @@ -45,6 +80,8 @@ class DiskInfo(): ssd_list_counter = 0 hdd_list_counter = 0 is_first_disk = True + resource_name = 0 + resource_disk = 0 for item in detail_txt: if item[1] == "disk": if is_first_disk: @@ -64,8 +101,17 @@ class DiskInfo(): total = item[3] type = item[2] else: - if len(item) > 6 and item[0] != "NAME": - used += int(item[6]) + if len(item) > 7 and item[0] != "NAME": + if item[6] == "/": + resource_disk = psutil.disk_usage(item[6])[0] + resource_name = name + used += int(item[7]) + for i in ssd_list: + if i["name"] == resource_name: + i["total"] = resource_disk + for i in hdd_list: + if i["name"] == resource_name: + i["total"] = resource_disk if type == "0": ssd_list[ssd_list_counter]["used"] = used ssd_list_counter += 1 @@ -78,5 +124,4 @@ class DiskInfo(): for item in hdd_list: item["total"] = int(int(item["total"]) / (1000 * 1000)) item["used"] = int(int(item["used"]) / (1000 * 1000)) - - return ssd_list, hdd_list \ No newline at end of file + return ssd_list, hdd_list diff --git a/usr/share/ahenk/base/system/system.py b/usr/share/ahenk/base/system/system.py index 2655fa3..f6e8445 100644 --- a/usr/share/ahenk/base/system/system.py +++ b/usr/share/ahenk/base/system/system.py @@ -12,12 +12,14 @@ import socket import struct import netifaces from uuid import getnode as get_mac - +import distro import cpuinfo import psutil from base.scope import Scope from base.util.util import Util +from base.system.disk_info import DiskInfo + class System: @@ -337,19 +339,24 @@ class System: @staticmethod def distribution_name(): - return platform.linux_distribution()[0] + #return platform.linux_distribution()[0] + return distro.linux_distribution()[0] @staticmethod def distribution_version(): - return platform.linux_distribution()[1] + # return platform.linux_distribution()[1] + return distro.linux_distribution()[1] @staticmethod def distribution_id(): - return platform.linux_distribution()[2] + # return platform.linux_distribution()[2] + return distro.linux_distribution()[2] @staticmethod def version(): - return platform.version() + # return platform.version() + version = distro.lsb_release_info()['description'] +"-"+ distro.lsb_release_info()["release"] + return version @staticmethod def kernel_release(): @@ -429,15 +436,18 @@ class System: @staticmethod def total(): - return int(int(psutil.disk_usage('/')[0]) / (1000 * 1000)) + return int(DiskInfo.total_disk()) +# return int(int(psutil.disk_usage('/')[0]) / (1000 * 1000)) @staticmethod def used(): - return int(int(psutil.disk_usage('/')[1]) / (1000 * 1000)) + return int(DiskInfo.total_disk_used()) +# return int(int(psutil.disk_usage('/')[1]) / (1000 * 1000)) @staticmethod def free(): - return int(int(psutil.disk_usage('/')[2]) / (1000 * 1000)) + return int(DiskInfo.total_disk_free()) +# return int(int(psutil.disk_usage('/')[2]) / (1000 * 1000)) @staticmethod def percent(): @@ -494,20 +504,28 @@ class System: @staticmethod def mac_addresses(): - mac = get_mac() - ':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2)) - arr = [] - for iface in psutil.net_io_counters(pernic=True): - try: - addr_list = psutil.net_if_addrs() - mac = addr_list[str(iface)][2][1] - if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str( - mac) != '00:00:00:00:00:00': - arr.append(mac.lower()) - except Exception as e: - pass + mac_addresses = [] + nics = psutil.net_if_addrs() + nics.pop('lo') # remove loopback since it doesnt have a real mac address - return arr + for i in nics: + for j in nics[i]: + if j.family == 17: # AF_LINK + mac_addresses.append(j.address) + return mac_addresses + # mac = get_mac() + # ':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2)) + # arr = [] + # for iface in psutil.net_io_counters(pernic=True): + # try: + # addr_list = psutil.net_if_addrs() + # mac = addr_list[str(iface)][2][1] + # if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str( + # mac) != '00:00:00:00:00:00': + # arr.append(mac.lower()) + # except Exception as e: + # pass + # return arr @staticmethod def screen_info_json_obj(info): diff --git a/usr/share/ahenk/plugins/ldap-login/execute_ad_login.py b/usr/share/ahenk/plugins/ldap-login/execute_ad_login.py index 842ac88..3a42d3d 100644 --- a/usr/share/ahenk/plugins/ldap-login/execute_ad_login.py +++ b/usr/share/ahenk/plugins/ldap-login/execute_ad_login.py @@ -30,8 +30,9 @@ class ADLogin(AbstractPlugin): ad_username = self.data['ad_username'] admin_password = self.data['admin_password'] ad_port = self.data['ad_port'] + dynamic_dns_update = self.data['dynamic_dns_update'] - execution_result = self.ad_authentication.authenticate(domain_name, hostname, ip_address, admin_password, ad_username) + execution_result = self.ad_authentication.authenticate(domain_name, hostname, ip_address, admin_password, ad_username, dynamic_dns_update) if execution_result is False: self.context.create_response(code=self.message_code.TASK_ERROR.value, message='Active Directory kullanıcısı ile oturum açma ayarlanırken hata oluştu.: Gerekli Paketleri indirilemedi.', @@ -46,21 +47,17 @@ class ADLogin(AbstractPlugin): config = configparser.ConfigParser() config.read(self.ahenk_conf_path) config.set('MACHINE', 'user_disabled', 'true') - with open(self.ahenk_conf_path, 'w') as configfile: self.logger.info('Opening config file ') config.write(configfile) configfile.close() self.logger.info('User disabled value Disabled') - else: self.logger.info("local users will not be disabled because local_user parameter is FALSE") self.shutdown() - self.context.create_response(code=self.message_code.TASK_PROCESSED.value, message='Active Directory kullanıcısı ile oturum açma başarı ile sağlandı ve istemci yeniden başlatılıyor.', content_type=self.get_content_type().APPLICATION_JSON.value) - except Exception as e: self.logger.error(str(e)) self.context.create_response(code=self.message_code.TASK_ERROR.value, diff --git a/usr/share/ahenk/plugins/local-user/add_user.py b/usr/share/ahenk/plugins/local-user/add_user.py index db0fd75..6eea1f3 100644 --- a/usr/share/ahenk/plugins/local-user/add_user.py +++ b/usr/share/ahenk/plugins/local-user/add_user.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- # Author:Mine DOGAN # Author:Tuncay ÇOLAK +import subprocess from base.plugin.abstract_plugin import AbstractPlugin from pathlib import Path @@ -60,10 +61,10 @@ class AddUser(AbstractPlugin): self.logger.debug('Added user to these groups: {}'.format(self.groups)) if str(self.password).strip() != "": - result_code, p_out, p_err = self.execute(self.create_shadow_password.format(self.password)) + result_code, p_out, p_err = self.execute_command(self.create_shadow_password.format(self.password)) shadow_password = p_out.strip() # shadow_password = crypt.crypt(self.password) - self.execute(self.change_password.format('\'{}\''.format(shadow_password), self.username)) + self.execute_command(self.change_password.format('\'{}\''.format(shadow_password), self.username)) self.logger.debug('Changed password.') self.execute(self.change_shell.format(self.username)) @@ -143,6 +144,21 @@ class AddUser(AbstractPlugin): self.context.create_response(code=self.message_code.TASK_ERROR.value, message='Local-User görevi çalıştırılırken bir hata oluştu.') + ## this methode is only for local-user password plugin + def execute_command(self, command, stdin=None, env=None, cwd=None, shell=True, result=True): + try: + process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, + stdout=subprocess.PIPE, shell=shell) + if result is True: + result_code = process.wait() + p_out = process.stdout.read().decode("unicode_escape") + p_err = process.stderr.read().decode("unicode_escape") + return result_code, p_out, p_err + else: + return None, None, None + except Exception as e: + return 1, 'Could not execute command. Error Message: {0}'.format(str(e)), '' + def handle_task(task, context): add_user = AddUser(task, context) diff --git a/usr/share/ahenk/plugins/local-user/edit_user.py b/usr/share/ahenk/plugins/local-user/edit_user.py index a5aef24..53a96c8 100644 --- a/usr/share/ahenk/plugins/local-user/edit_user.py +++ b/usr/share/ahenk/plugins/local-user/edit_user.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- # Author:Mine DOGAN # Author:Tuncay ÇOLAK +import subprocess from base.plugin.abstract_plugin import AbstractPlugin from pathlib import Path @@ -64,9 +65,9 @@ class EditUser(AbstractPlugin): self.username = self.new_username if str(self.password).strip() != "": - result_code, p_out, p_err = self.execute(self.create_shadow_password.format(self.password)) + result_code, p_out, p_err = self.execute_command(self.create_shadow_password.format(self.password)) shadow_password = p_out.strip() - self.execute(self.change_password.format('\'{}\''.format(shadow_password), self.username)) + self.execute_command(self.change_password.format('\'{}\''.format(shadow_password), self.username)) self.logger.debug('Changed password.') if self.current_home != self.home: @@ -155,6 +156,21 @@ class EditUser(AbstractPlugin): self.context.create_response(code=self.message_code.TASK_ERROR.value, message='Local-User görevi çalıştırılırken bir hata oluştu.') + ## this methode is only for local-user password plugin + def execute_command(self, command, stdin=None, env=None, cwd=None, shell=True, result=True): + try: + process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, + stdout=subprocess.PIPE, shell=shell) + if result is True: + result_code = process.wait() + p_out = process.stdout.read().decode("unicode_escape") + p_err = process.stderr.read().decode("unicode_escape") + return result_code, p_out, p_err + else: + return None, None, None + except Exception as e: + return 1, 'Could not execute command. Error Message: {0}'.format(str(e)), '' + def handle_task(task, context): edit_user = EditUser(task, context) edit_user.handle_task() diff --git a/usr/share/ahenk/plugins/manage-root/set_root_password.py b/usr/share/ahenk/plugins/manage-root/set_root_password.py index 3d5c9e1..757ee07 100644 --- a/usr/share/ahenk/plugins/manage-root/set_root_password.py +++ b/usr/share/ahenk/plugins/manage-root/set_root_password.py @@ -98,21 +98,16 @@ class RootPassword(AbstractPlugin): try: process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=shell) - self.logger.debug('Executing command for manage-root') - if result is True: result_code = process.wait() p_out = process.stdout.read().decode("unicode_escape") p_err = process.stderr.read().decode("unicode_escape") - return result_code, p_out, p_err else: return None, None, None except Exception as e: - return 1, 'Could not execute command: {0}. Error Message: {1}'.format(command, str(e)), '' - - + return 1, 'Could not execute command' def handle_task(task, context): diff --git a/usr/share/ahenk/plugins/network-manager/add_dns.py b/usr/share/ahenk/plugins/network-manager/add_dns.py index f925346..ad9a0a0 100644 --- a/usr/share/ahenk/plugins/network-manager/add_dns.py +++ b/usr/share/ahenk/plugins/network-manager/add_dns.py @@ -23,10 +23,10 @@ class AddDNS(AbstractPlugin): def handle_task(self): try: if self.is_active is True: - content = 'nameserver {}\n'.format(self.ip) + content = '\nnameserver {}\n'.format(self.ip) self.logger.debug('Created active dns content.') else: - content = '#nameserver {}\n'.format(self.ip) + content = '\n#nameserver {}\n'.format(self.ip) self.logger.debug('Created passive dns content.') self.logger.debug('Writing to file...') diff --git a/usr/share/ahenk/plugins/network-manager/add_domain.py b/usr/share/ahenk/plugins/network-manager/add_domain.py index 2da5deb..47f64fd 100644 --- a/usr/share/ahenk/plugins/network-manager/add_domain.py +++ b/usr/share/ahenk/plugins/network-manager/add_domain.py @@ -21,7 +21,7 @@ class AddDomain(AbstractPlugin): def handle_task(self): try: - content = 'domain {0}\nsearch {0}\n'.format(self.domain) + content = '\ndomain {0}\nsearch {0}\n'.format(self.domain) self.logger.debug('Writing to file...') self.write_file(self.dns_file, content, 'a') diff --git a/usr/share/ahenk/plugins/network-manager/add_host.py b/usr/share/ahenk/plugins/network-manager/add_host.py index 37f1687..243a864 100644 --- a/usr/share/ahenk/plugins/network-manager/add_host.py +++ b/usr/share/ahenk/plugins/network-manager/add_host.py @@ -24,10 +24,10 @@ class AddHost(AbstractPlugin): def handle_task(self): try: if self.is_active is True: - content = '{0} {1}\n'.format(self.ip, self.hostname) + content = '\n{0} {1}\n'.format(self.ip, self.hostname) self.logger.debug('Created active host content.') else: - content = '#{0} {1}\n'.format(self.ip, self.hostname) + content = '\n#{0} {1}\n'.format(self.ip, self.hostname) self.logger.debug('Created passive host content.') self.logger.debug('Writing to file...') diff --git a/usr/share/ahenk/plugins/network-manager/add_network.py b/usr/share/ahenk/plugins/network-manager/add_network.py index c7ceb0a..de01ede 100644 --- a/usr/share/ahenk/plugins/network-manager/add_network.py +++ b/usr/share/ahenk/plugins/network-manager/add_network.py @@ -32,12 +32,12 @@ class AddNetwork(AbstractPlugin): try: if self.type == 'STATIC': if self.is_active is True: - self.content = 'auto {0}\niface {0} inet static\naddress {1}\nnetmask {2}\ngateway {3}\n'.format(self.name, + self.content = '\nauto {0}\niface {0} inet static\naddress {1}\nnetmask {2}\ngateway {3}\n'.format(self.name, self.ip, self.netmask, self.gateway) else: - self.content = 'auto {0}\niface {0} inet static\n#address {1}\n#netmask {2}\n#gateway {3}\n'.format(self.name, + self.content = '\nauto {0}\niface {0} inet static\n#address {1}\n#netmask {2}\n#gateway {3}\n'.format(self.name, self.ip, self.netmask, self.gateway) diff --git a/usr/share/ahenk/plugins/package-manager/check_package.py b/usr/share/ahenk/plugins/package-manager/check_package.py index 490ceef..31c4a0a 100644 --- a/usr/share/ahenk/plugins/package-manager/check_package.py +++ b/usr/share/ahenk/plugins/package-manager/check_package.py @@ -21,36 +21,45 @@ class CheckPackage(AbstractPlugin): package_version = str((self.data)['packageVersion']) dn = self.Ahenk.dn() res = {} + + result_message = "Paket yüklü" if dn is None: dn = " " + res["package_name"] = package_name + res["dn"] = dn result_code, result, p_err = self.execute('dpkg -s {} | grep Version'.format(package_name)) data = result.split(': ') - self.logger.debug(data) + if data: + if data[0] == 'Version' : # Package is installed + if package_version is None or len(package_version) == 0: + self.logger.debug(package_version) + result = 1 + result_message = "Paket yüklü" + res['version'] = data[1] + res["res"] = result + elif package_version is not None and str((package_version + '\n')) == str(data[1]): # Package version is the same with wanted version + result = 1 + result_message = "Paket yüklü" + res['version'] = data[1] + res["res"] = result + else: + self.logger.debug(package_version) + result = 2 + result_message = "Paket farklı veriyonla yüklü" + res['version'] = data[1] + res["res"] = result + else: # Package is not installed + result = 0 + result_message = "Paket yüklü değil" + res['version'] = '' + res["res"] = result - if data[0] == 'Version': # Package is installed - if package_version is None or len(package_version) == 0: - result = 'Paket yüklü' - res['version'] = data[1] - elif data[1] is not None and (package_version + '\n') in data[ - 1]: # Package version is the same with wanted version - result = 'Paket yüklü' - res['version'] = data[1] - else: - result = 'Paket yüklü; fakat başka bir versiyonla' - res['version'] = data[1] - else: # Package is not installed - result = 'Paket yüklü değil' - res['version'] = '' - - res["dn"] = dn - res["res"] = result - - self.logger.debug("Result is: - {}".format(result)) - self.context.create_response(code=self.message_code.TASK_PROCESSED.value, - message='{0} - {1}'.format(package_name, result), - data=json.dumps(res), - content_type=self.get_content_type().APPLICATION_JSON.value) - self.logger.debug("Package Info has sent") + self.logger.debug("Result is: - {}".format(result_message)) + self.context.create_response(code=self.message_code.TASK_PROCESSED.value, + message='{0} - {1}'.format(package_name, result_message), + data=json.dumps(res), + content_type=self.get_content_type().APPLICATION_JSON.value) + self.logger.debug("Package Info has sent") except Exception as e: self.logger.debug(str(e)) self.context.create_response(code=self.message_code.TASK_ERROR.value, diff --git a/usr/share/ahenk/plugins/resource-usage/agent_info.py b/usr/share/ahenk/plugins/resource-usage/agent_info.py index 421d9f7..c9a54d0 100644 --- a/usr/share/ahenk/plugins/resource-usage/agent_info.py +++ b/usr/share/ahenk/plugins/resource-usage/agent_info.py @@ -3,6 +3,7 @@ # Author: Tuncay ÇOLAK from base.plugin.abstract_plugin import AbstractPlugin +from base.system.disk_info import DiskInfo import json @@ -23,6 +24,8 @@ class AgentInfo(AbstractPlugin): device += ", " device = device + part.device + ssd_list, hdd_list = DiskInfo.get_all_disks() + data = {'System': self.Os.name(), 'Release': self.Os.kernel_release(), 'agentVersion': self.get_agent_version(), 'hostname': self.Os.hostname(), @@ -41,6 +44,13 @@ class AgentInfo(AbstractPlugin): 'memory': self.Hardware.Memory.total(), 'Device': device, } + + if len(ssd_list) > 0: + data['hardwareDiskSsdInfo'] = str(ssd_list) + + if len(hdd_list) > 0: + data['hardwareDiskHddInfo'] = str(hdd_list) + self.logger.debug("Agent info gathered.") self.context.create_response(code=self.message_code.TASK_PROCESSED.value, message='Ahenk bilgileri başarıyla güncellendi.', diff --git a/usr/share/ahenk/plugins/resource-usage/resource_info_fetcher.py b/usr/share/ahenk/plugins/resource-usage/resource_info_fetcher.py index a1ceef5..5e933bc 100644 --- a/usr/share/ahenk/plugins/resource-usage/resource_info_fetcher.py +++ b/usr/share/ahenk/plugins/resource-usage/resource_info_fetcher.py @@ -3,11 +3,13 @@ # Author: Cemre ALPSOY # Author: Emre Akkaya +import json + from psutil import disk_io_counters from base.plugin.abstract_plugin import AbstractPlugin -import json from base.system.disk_info import DiskInfo + class ResourceUsage(AbstractPlugin): def __init__(self, data, context): super(AbstractPlugin, self).__init__() @@ -20,14 +22,11 @@ class ResourceUsage(AbstractPlugin): try: device = "" self.logger.debug("Gathering resource usage for disk, memory and CPU.") - ssd_list, hdd_list = DiskInfo.get_all_disks() - for part in self.Hardware.Disk.partitions(): if len(device) != 0: device += ", " device = device + part.device - data = {'System': self.Os.name(), 'Release': self.Os.kernel_release(), 'Version': self.Os.distribution_version(), 'Machine': self.Os.architecture(), 'CPU Physical Core Count': self.Hardware.Cpu.physical_core_count(), @@ -41,13 +40,12 @@ class ResourceUsage(AbstractPlugin): 'CPU Actual Hz': self.Hardware.Cpu.hz_actual(), 'CPU Advertised Hz': self.Hardware.Cpu.hz_advertised() } - if len(ssd_list) > 0: - data['hardware.disk.ssd.info'] = ssd_list + data['hardware.disk.ssd.info'] = str(ssd_list) if len(hdd_list) > 0: - data['hardware.disk.hdd.info'] = hdd_list - + data['hardware.disk.hdd.info'] = str(hdd_list) + self.logger.debug("Resource usage info gathered.") self.context.create_response(code=self.message_code.TASK_PROCESSED.value, message='Anlık kaynak kullanım bilgisi başarıyla toplandı.', diff --git a/usr/share/ahenk/plugins/service/get_services.py b/usr/share/ahenk/plugins/service/get_services.py index 3b15730..0b58495 100644 --- a/usr/share/ahenk/plugins/service/get_services.py +++ b/usr/share/ahenk/plugins/service/get_services.py @@ -97,17 +97,16 @@ class GetServices(AbstractPlugin): del service[0] if len(service)>0 and '.service' in service[0]: # service[0] = service name, service[1] is loaded, service[2] active or not, - result, out, err = self.execute(self.service_status.format(service[0])) # check service is enable or not on auto start - auto='INACTIVE' - if 'disabled' in out: - auto='INACTIVE' - elif 'enabled' in out: - auto='ACTIVE' + # result, out, err = self.execute(self.service_status.format(service[0])) # check service is enable or not on auto start + result, out, err = self.execute("systemctl is-enabled {0}".format(service[0])) + auto = 'disabled' + if 'enabled' in out: + auto = 'enabled' if service[2] == 'active': - self.add_file(service[0], "ACTIVE", auto) + self.add_file(service[0], "active", auto) else: - self.add_file(service[0], 'INACTIVE',auto) + self.add_file(service[0], 'inactive', auto) print(service) diff --git a/usr/share/ahenk/plugins/service/service_list.py b/usr/share/ahenk/plugins/service/service_list.py index b93bda9..2a1ef78 100644 --- a/usr/share/ahenk/plugins/service/service_list.py +++ b/usr/share/ahenk/plugins/service/service_list.py @@ -28,7 +28,7 @@ class ServiceList(AbstractPlugin): return result_code, message, item def set_startup_service(self, service_name, action): - (result_code, p_out, p_err) = self.execute('update-rc.d {0} {1}'.format(service_name, action)) + (result_code, p_out, p_err) = self.execute('systemctl {0} {1}'.format(action, service_name)) if result_code == 0: message = 'Service startup action was successful: {}'.format(service_name) else: @@ -39,17 +39,22 @@ class ServiceList(AbstractPlugin): def get_service_status(self, service_item): - service_name=str(service_item['serviceName']) + service_name = str(service_item['serviceName']) result, p_out, err = self.execute('systemctl status {0}'.format(service_name)) if 'not-found' in p_out: service_item["serviceStatus"] = 'Service Not Found' elif 'running' in p_out: - service_item["serviceStatus"] = 'Running' + service_item["serviceStatus"] = 'active' elif ('inactive' in p_out) or ('failed' in p_out): - service_item["serviceStatus"] = 'Stopped' + service_item["serviceStatus"] = 'inactive' + result, out, err = self.execute("systemctl is-enabled {0}".format(service_name)) + auto = 'disabled' + if 'enabled' in out: + auto = 'enabled' + service_item["startAuto"] = auto return service_item @@ -61,30 +66,29 @@ class ServiceList(AbstractPlugin): for item in items: try: if item['serviceStatus'] is not None and ( - str(item['serviceStatus']) == 'Başlat' or str(item['serviceStatus']) == 'Start' or str(item['serviceStatus']) == 'START' ): + str(item['serviceStatus']) == 'start' or str(item['serviceStatus']) == 'active' or str(item['serviceStatus']) == 'START'): resultcode, message, item = self.start_stop_service(item, "start") resultMessage += message if item['serviceStatus'] is not None and ( - str(item['serviceStatus']) == 'Durdur' or str(item['serviceStatus']) == 'Stop' or str(item['serviceStatus']) == 'STOP' ): + str(item['serviceStatus']) == 'stop' or str(item['serviceStatus']) == 'inactive' or str(item['serviceStatus']) == 'STOP'): resultcode, message, item= self.start_stop_service(item, "stop") resultMessage += message if item['startAuto'] is not None and ( - str(item['startAuto']) == 'Başlat' or str(item['startAuto']) == 'Start' or str(item['startAuto']) == 'START'): - resultcode, message = self.set_startup_service(item, "defaults") + str(item['startAuto']) == 'enabled' or str(item['startAuto']) == 'Start' or str(item['startAuto']) == 'START'): + resultcode, message = self.set_startup_service(item['serviceName'], "enable") resultMessage += message if item['startAuto'] is not None and ( - str(item['startAuto']) == 'Durdur' or str(item['startAuto']) == 'Stop' or str(item['startAuto']) == 'STOP' ): - resultcode, message = self.set_startup_service(item, "remove") + str(item['startAuto']) == 'disabled' or str(item['startAuto']) == 'Stop' or str(item['startAuto']) == 'STOP'): + resultcode, message = self.set_startup_service(item['serviceName'], "disable") resultMessage += message - - item=self.get_service_status(item) + item = self.get_service_status(item) except Exception as e: resultMessage += '{0} servisinin isteklerini gerçekleştirirken hata ile karşılaşıldı. Hdata : {1}\r\n'.format( str(item['serviceName']), str(e)) self.logger.debug(resultMessage) - data = {'ResultMessage': resultMessage, 'service_list': items } + data = {'ResultMessage': resultMessage, 'service_list': items} self.context.create_response(code=self.message_code.TASK_PROCESSED.value, message='Servis istekleri gerçekleştirildi', diff --git a/usr/share/ahenk/plugins/usb/delete-usb-rules.py b/usr/share/ahenk/plugins/usb/delete-usb-rules.py new file mode 100644 index 0000000..df75e57 --- /dev/null +++ b/usr/share/ahenk/plugins/usb/delete-usb-rules.py @@ -0,0 +1,47 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +from base.plugin.abstract_plugin import AbstractPlugin + + +class DeleteUsbRule(AbstractPlugin): + def __init__(self, task, context): + super(DeleteUsbRule, self).__init__() + self.task = task + self.context = context + self.logger = self.get_logger() + self.message_code = self.get_message_code() + self.whitelist_path = "/etc/udev/rules.d/99-ahenk-task-whitelist.rules" + self.blacklist_path = "/etc/udev/rules.d/99-ahenk-task-blacklist.rules" + + def handle_task(self): + try: + ruleIsExist = False + message = "İstemciye ait USB kuralları başarıyla silindi." + if self.is_exist(self.whitelist_path): + self.delete_file(self.whitelist_path) + ruleIsExist = True + + if self.is_exist(self.blacklist_path): + self.delete_file(self.blacklist_path) + ruleIsExist = True + + if ruleIsExist: + message = "İstemciye ait USB kuralları başarıyla silindi." + self.execute('udevadm control --reload-rules') + self.logger.debug('Blacklist/Whitelist was reloaded.') + else: + message = "İstemciye ait tanımlı USB kuralı bulunmamaktadır." + + self.logger.info('USB rule task is handled successfully.') + self.context.create_response(code=self.message_code.TASK_PROCESSED.value, + message=message) + except Exception as e: + self.logger.error('A problem occurred while deleting USB rules. Error Message: {0}'.format(str(e))) + self.context.create_response(code=self.message_code.TASK_ERROR.value, + message='USB kuralları silinirken hata oluştu: {0}'.format(str(e))) + + +def handle_task(task, context): + manage = DeleteUsbRule(task, context) + manage.handle_task() diff --git a/usr/share/ahenk/plugins/usb/get-usb-rules.py b/usr/share/ahenk/plugins/usb/get-usb-rules.py new file mode 100644 index 0000000..255513e --- /dev/null +++ b/usr/share/ahenk/plugins/usb/get-usb-rules.py @@ -0,0 +1,73 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +from base.plugin.abstract_plugin import AbstractPlugin +import json + + +class GetUsbRules(AbstractPlugin): + def __init__(self, task, context): + super(GetUsbRules, self).__init__() + self.task = task + self.context = context + self.logger = self.get_logger() + self.message_code = self.get_message_code() + self.whitelist_path = "/etc/udev/rules.d/99-ahenk-task-whitelist.rules" + self.blacklist_path = "/etc/udev/rules.d/99-ahenk-task-blacklist.rules" + self.usb_rule_list = [] + + def handle_task(self): + try: + rule_type = "whitelist" + if self.is_exist(self.whitelist_path): + lines = self.read_file_by_line(self.whitelist_path) + for line in lines: + self.get_usb_item(line, rule_type) + + if self.is_exist(self.blacklist_path): + rule_type = "blacklist" + lines = self.read_file_by_line(self.blacklist_path) + for line in lines: + self.get_usb_item(line, rule_type) + message = "İstemciye ait USB kuralları başarıyla alındı." + if len(self.usb_rule_list) == 0: + message = "İstemciye ait tanımlı USB kuralı bulunmamaktadır." + + self.logger.info('Get USB rule task is handled successfully.') + self.context.create_response(code=self.message_code.TASK_PROCESSED.value, + message=message, + data=json.dumps({'usb_list': self.usb_rule_list, 'type': rule_type}), + content_type=self.get_content_type().APPLICATION_JSON.value) + except Exception as e: + self.logger.error('A problem occurred while getting USB rules. Error Message: {0}'.format(str(e))) + self.context.create_response(code=self.message_code.TASK_ERROR.value, + message='USB kuralları getirilirken hata oluştu: {0}'.format(str(e))) + + def get_usb_item(self, line, type): + line_parser_list = line.rstrip().split(', ') + item_obj = {} + authorized_str = 'ATTR{authorized}="1"' + if type == "blacklist": + authorized_str = 'ATTR{authorized}="0"' + if authorized_str in line_parser_list: + for item in line_parser_list: + if "ATTR{manufacturer}" in item: + manufacturer = item.split("==")[1] + manufacturer = manufacturer.replace('"', '') + item_obj["vendor"] = manufacturer + if "ATTR{product}" in item: + model = item.split("==")[1] + model = model.replace('"', '') + item_obj["model"] = model + if "ATTR{serial}" in item: + serial_mumber = item.split("==")[1] + serial_mumber = serial_mumber.replace('"', '') + item_obj["serialNumber"] = serial_mumber + if len(item_obj): + self.usb_rule_list.append(item_obj) + + + +def handle_task(task, context): + manage = GetUsbRules(task, context) + manage.handle_task() diff --git a/usr/share/ahenk/plugins/usb/manage-usb-rules.py b/usr/share/ahenk/plugins/usb/manage-usb-rules.py new file mode 100644 index 0000000..4db4c9b --- /dev/null +++ b/usr/share/ahenk/plugins/usb/manage-usb-rules.py @@ -0,0 +1,217 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +import json + +from base.plugin.abstract_plugin import AbstractPlugin + + +class UsbRule(AbstractPlugin): + def __init__(self, task, context): + super(UsbRule, self).__init__() + self.task = task + self.context = context + self.logger = self.get_logger() + self.message_code = self.get_message_code() + self.logger.info("---->>> "+ str(self.task)) + self.script = '/bin/bash ' + self.Ahenk.plugins_path() + 'usb/scripts/{0}' + self.script_path = self.Ahenk.plugins_path() + 'usb/scripts/{0}' + self.items = [] + self.command_vendor = "grep -lw '{0}' /sys/bus/usb/devices/*/manufacturer | grep -o -P '.{{0,}}/.{{0,0}}'" + self.command_model = "grep -lw '{0}' {1}product" + self.command_serial = "grep -lw '{0}' {1}serial" + self.command_authorized = "echo '{0}' > {1}authorized" + self.command_serial_is_exist = 'if test -e {0}serial; then echo "exist"; else echo "not found"; fi' + self.logger.debug('Parameters were initialized.') + self.whitelist_path = "/etc/udev/rules.d/99-ahenk-task-whitelist.rules" + self.blacklist_path = "/etc/udev/rules.d/99-ahenk-task-blacklist.rules" + + def handle_task(self): + try: + if self.has_attr_json(self.task, 'items') is True: + self.items = self.task['items'] + self.logger.debug('Blacklist/Whitelist will be created task.') + if self.has_attr_json(self.task, 'type') is True: + self.logger.debug('BlackList Whitelist will be created....') + self.create_blacklist_whitelist() + + self.logger.info('USB rule task is handled successfully.') + self.context.create_response(code=self.message_code.TASK_PROCESSED.value, + message='İstemciye ait USB kuralları başarıyla güncellendi.') + + except Exception as e: + self.logger.error('A problem occurred while handling USB rule task. Error Message: {0}'.format(str(e))) + self.context.create_response(code=self.message_code.TASK_ERROR.value, + message='İstemciye ait USB kuralların uygulanırken bir hata oluştu: {0}'.format(str(e))) + + def organize_rule_files(self, is_whitelist): + if is_whitelist == 0: + if self.is_exist(self.whitelist_path): + self.delete_file(self.whitelist_path) + self.execute('> {0}'.format(self.blacklist_path)) + else: + if self.is_exist(self.blacklist_path): + self.delete_file(self.blacklist_path) + self.execute('> {0}'.format(self.whitelist_path)) + + def write_whitelist_line(self, vendor, model, serial_number, is_first_line): + command_blackandwhitelist = 'echo ' + "'" + symbol = '=' + authorized = '1' + if is_first_line is True: + command_blackandwhitelist = 'ex -sc ' + "'1i|" + symbol = '!' + authorized = '0' + command_blackandwhitelist += 'ACTION==\"add|change\", SUBSYSTEM==\"usb\", ' + if vendor is not None and len(vendor) > 0: + command_blackandwhitelist += 'ATTR{manufacturer}' + symbol + '=\"' + vendor + '\", ' + if model is not None and len(model) > 0: + command_blackandwhitelist += 'ATTR{product}' + symbol + '=\"' + model + '\", ' + if serial_number is not None and len(serial_number) > 0: + command_blackandwhitelist += 'ATTR{serial}' + symbol + '=\"' + serial_number + '\", ' + command_blackandwhitelist += 'ATTR{authorized}=\"' + authorized + '\"' + "'" + if is_first_line is False: + command_blackandwhitelist += ' >> ' + else: + command_blackandwhitelist += ' -cx ' + command_blackandwhitelist += self.whitelist_path + self.logger.debug(command_blackandwhitelist) + self.write_rule_line(command_blackandwhitelist) + + def write_rule_line(self, command): + p_result_code, p_out, p_err = self.execute(command) + if p_result_code == 0: + self.logger.debug('Rule line is added successfully') + elif p_result_code != 0: + self.logger.debug('Error while adding rule line to /etc/udev/rules.d/ , Error message : {0}'.format(p_err)) + + def create_rule_line(self, vendor, model, serial_number, is_whitelist): + if is_whitelist == 0: + command_blackandwhitelist = 'echo ' + "'" + 'ACTION ==\"add|change\", SUBSYSTEM==\"usb\", ' + if vendor is not None and len(vendor) > 0: + command_blackandwhitelist += 'ATTR{manufacturer}==\"' + vendor + '\", ' + if model is not None and len(model) > 0: + command_blackandwhitelist += 'ATTR{product}==\"' + model + '\", ' + if serial_number is not None and len(serial_number) > 0: + command_blackandwhitelist += 'ATTR{serial}==\"' + serial_number + '\", ' + command_blackandwhitelist += 'ATTR{authorized}=\"0\"' + "'" + '>> {0}'.format(self.blacklist_path) + self.write_rule_line(command_blackandwhitelist) + else: + self.write_whitelist_line(vendor, model, serial_number, True) + self.write_whitelist_line(vendor, model, serial_number, False) + + def create_blacklist_whitelist(self): + self.logger.debug('usb storage will be enabled') + self.execute(self.script.format('ENABLED_usbstorage.sh'), result=True) + self.logger.debug('usb storage enabled') + if self.task['type'] == 'blacklist': + is_whitelist = 0 + else: + is_whitelist = 1 + self.logger.debug('Rule files are organizing....') + self.organize_rule_files(is_whitelist) + self.logger.debug('Rule files are organized') + + for item in self.items: + item_parameters = json.loads(str(json.dumps(item))) + vendor = item_parameters['vendor'] + model = item_parameters['model'] + serial_number = item_parameters['serialNumber'] + + self.create_rule_line(vendor, model, serial_number, is_whitelist) + + self.logger.debug('vendor, model and serial number is set....') + self.logger.debug(self.command_vendor.format(vendor)) + result_code, p_out, p_err = self.execute(self.command_vendor.format(vendor), result=True) + folder_list = str(p_out).split('\n') + folder_list.pop() + + if p_out == '' and vendor != '': + self.logger.debug('Device has not been found because of vendor. Vendor: {0}'.format(vendor)) + + if vendor == '': + folder_list = [] + folder_list.append('/sys/bus/usb/devices/*/') + + for folder in folder_list: + + result_code, p_out, p_err = self.execute(self.command_model.format(model, folder), result=True) + + if p_out == '' and model != '': + self.logger.debug( + 'Device model has not been found in this directory. Directory: {0}, Vendor: {1}, Model: {2}'.format( + folder, vendor, model)) + + else: + model_folder_list = str(p_out).split('\n') + model_folder_list.pop() + + if p_out == '': + model_folder_list.append(folder) + + if vendor == '' and model == '': + model_folder_list = [] + model_folder_list.append('/sys/bus/usb/devices/*/') + + for model_folder in model_folder_list: + if 'product' in model_folder: + model_folder = model_folder.strip('product') + + if model_folder != '/sys/bus/usb/devices/*/': + result_code, p_out, p_err = self.execute(self.command_serial_is_exist.format(model_folder), + result=True) + + if 'exist' in p_out or model_folder == '/sys/bus/usb/devices/*/': + result_code, p_out, p_err = self.execute( + self.command_serial.format(serial_number, model_folder), + result=True) + if p_out == '' and serial_number != '': + self.logger.debug( + 'Device serial number has not been found in this directory. Directory: {0}, Vendor: {1}, Model: {2}, Serial Number: {3}'.format( + model_folder, vendor, + model, serial_number)) + else: + serial_folder_list = str(p_out).split('\n') + serial_folder_list.pop() + + if p_out == '': + serial_folder_list.append(model_folder) + + for serial_folder in serial_folder_list: + serial_folder = serial_folder.strip('serial') + if self.task['type'] == 'whitelist': + self.execute(self.command_authorized.format('1', serial_folder), result=True) + self.logger.debug( + 'Enabled the device. Directory: {0}, Vendor: {1}, Model: {2}, Serial Number: {3}'.format( + serial_folder, vendor, model, serial_number)) + elif self.task['type'] == 'blacklist': + self.execute(self.command_authorized.format('0', serial_folder), result=True) + self.logger.debug( + 'Disabled the device. Directory: {0}, Vendor: {1}, Model: {2}, Serial Number: {3}'.format( + serial_folder, vendor, model, serial_number)) + + elif 'not found' in p_out: + dir = '' + if model != '': + dir = model_folder + elif vendor != '': + dir = folder + + if self.task['type'] == 'whitelist': + self.execute(self.command_authorized.format('1', dir), result=True) + self.logger.debug( + 'Enabled the device. Directory: {0}, Vendor: {1}, Model: {2}, Serial Number: {3}'.format( + dir, vendor, model, serial_number)) + elif self.task['type'] == 'blacklist': + self.execute(self.command_authorized.format('0', dir), result=True) + self.logger.debug( + 'Disabled the device. Directory: {0}, Vendor: {1}, Model: {2}, Serial Number: {3}'.format( + dir, vendor, model, serial_number)) + + self.execute('udevadm control --reload-rules') + self.logger.debug('Blacklist/Whitelist was created.') + + +def handle_task(task, context): + manage = UsbRule(task, context) + manage.handle_task() diff --git a/usr/share/ahenk/plugins/usb/scripts/DISABLED_printer.sh b/usr/share/ahenk/plugins/usb/scripts/DISABLED_printer.sh index 62a8a08..b087cc6 100755 --- a/usr/share/ahenk/plugins/usb/scripts/DISABLED_printer.sh +++ b/usr/share/ahenk/plugins/usb/scripts/DISABLED_printer.sh @@ -3,7 +3,7 @@ var=$(lsmod | awk '{print $1}'| grep usblp) service cups stop -if [ -z "$var" ] +if [[ -z "$var" ]] then echo "USB printer devices are already blocked" else diff --git a/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbhid.sh b/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbhid.sh index 0105c05..4906813 100755 --- a/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbhid.sh +++ b/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbhid.sh @@ -2,7 +2,7 @@ var=$(lsmod | grep usbhid) -if [ -z "$var" ] +if [[ -z "$var" ]] then echo "USB HID devices are already blocked" else @@ -21,7 +21,7 @@ fi var=$(lsmod | grep psmouse) -if [ -z "$var" ] +if [[ -z "$var" ]] then echo "psmouse is already blocked" else diff --git a/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbstorage.sh b/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbstorage.sh index d875243..85a4161 100755 --- a/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbstorage.sh +++ b/usr/share/ahenk/plugins/usb/scripts/DISABLED_usbstorage.sh @@ -2,7 +2,7 @@ var=$(lsmod | awk '{print $1}'| grep usb_storage) -if [ -z "$var" ] +if [[ -z "$var" ]] then echo "USB storage devices are already blocked" else @@ -26,7 +26,7 @@ sleep 2 var=$(lsmod | grep usb_storage | awk '{print $4}') -if [ ! -z "$var" ] +if [[ ! -z "$var" ]] then IFS=',' read -ra deps <<< "$var" for i in "${deps[@]}"; do diff --git a/usr/share/ahenk/plugins/usb/scripts/DISABLED_webcam.sh b/usr/share/ahenk/plugins/usb/scripts/DISABLED_webcam.sh index 4f24bd4..a12a550 100755 --- a/usr/share/ahenk/plugins/usb/scripts/DISABLED_webcam.sh +++ b/usr/share/ahenk/plugins/usb/scripts/DISABLED_webcam.sh @@ -2,7 +2,7 @@ var=$(lsof -t /dev/video0) -if [ -z "$var" ] +if [[ -z "$var" ]] then echo "Webcam is not in use" else @@ -12,7 +12,7 @@ fi var=$(lsmod | awk '{print $1}'| grep uvcvideo) -if [ -z "$var" ] +if [[ -z "$var" ]] then echo "Webcam is already blocked" else diff --git a/usr/share/libpam-script/pam_script_ses_close b/usr/share/libpam-script/pam_script_ses_close index 58fc3e8..b779c41 100755 --- a/usr/share/libpam-script/pam_script_ses_close +++ b/usr/share/libpam-script/pam_script_ses_close @@ -14,14 +14,14 @@ function log() { echo "$(date) $0: $@" >> $LOG } -if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; then - if ([ -n $PAM_SERVICE ] && [[ ( $PAM_SERVICE == *"dm" || $PAM_SERVICE == "gdm"* )]]) || ([ -n $PAM_TTY ] && [[ $PAM_TTY == ":"* ]]); then +if [[ -n $PAM_USER ]] && [[ $PAM_USER != "root" ]]; then + if ([[ -n $PAM_SERVICE ]] && [[ ( $PAM_SERVICE == *"dm" || $PAM_SERVICE == "gdm"* )]]) || ([[ -n $PAM_TTY ]] && [[ $PAM_TTY == ":"* ]]); then SERVICE="none" - if [ -n $PAM_SERVICE ]; then + if [[ -n $PAM_SERVICE ]]; then SERVICE="$PAM_SERVICE" fi TTY_DISPLAY="none" - if [ -n $PAM_TTY ]; then + if [[ -n $PAM_TTY ]]; then TTY_DISPLAY="$PAM_TTY" fi if [[ $PAM_USER = *'\'* ]]; then @@ -32,6 +32,6 @@ if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; then done fi log "logout: $PAM_USER service: $SERVICE tty: $TTY_DISPLAY" - sudo python3 /usr/share/ahenk/ahenkd.py logout $PAM_USER + python3 /usr/share/ahenk/ahenkd.py logout $PAM_USER fi fi diff --git a/usr/share/libpam-script/pam_script_ses_open b/usr/share/libpam-script/pam_script_ses_open index e90430b..300b52e 100755 --- a/usr/share/libpam-script/pam_script_ses_open +++ b/usr/share/libpam-script/pam_script_ses_open @@ -14,14 +14,14 @@ function log() { echo "$(date) $0: $@" >> $LOG } -if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; then - if ([ -n $PAM_SERVICE ] && [[ ( $PAM_SERVICE == "gdm"* || $PAM_SERVICE == *"dm" )]]) || ([ -n $PAM_TTY ] && [[ $PAM_TTY == ":"* ]]); then +if [[ -n $PAM_USER ]] && [[ $PAM_USER != "root" ]]; then + if ([[ -n $PAM_SERVICE ]] && [[ ( $PAM_SERVICE == "gdm"* || $PAM_SERVICE == *"dm" )]]) || ([[ -n $PAM_TTY ]] && [[ $PAM_TTY == ":"* ]]); then SERVICE="none" - if [ -n $PAM_SERVICE ]; then + if [[ -n $PAM_SERVICE ]]; then SERVICE="$PAM_SERVICE" fi TTY_DISPLAY="none" - if [ -n $PAM_TTY ]; then + if [[ -n $PAM_TTY ]]; then TTY_DISPLAY="$PAM_TTY" fi domain="none" @@ -35,10 +35,10 @@ if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; then fi if [[ $domain != "none" ]]; then log "login: $PAM_USER service: $SERVICE tty: $TTY_DISPLAY domain: $domain" - sudo python3 /usr/share/ahenk/ahenkd.py login $PAM_USER $SERVICE $TTY_DISPLAY $domain + python3 /usr/share/ahenk/ahenkd.py login $PAM_USER $SERVICE $TTY_DISPLAY $domain else log "login: $PAM_USER service: $SERVICE tty: $TTY_DISPLAY domain: none" - sudo python3 /usr/share/ahenk/ahenkd.py login $PAM_USER $SERVICE $TTY_DISPLAY + python3 /usr/share/ahenk/ahenkd.py login $PAM_USER $SERVICE $TTY_DISPLAY fi fi fi