Syncing /usr/share/ahenk to src and recreating ahenk.install

This commit is contained in:
Tuncay ÇOLAK 2022-12-27 10:32:14 +03:00
parent 7100a6942f
commit ecce5632e4
43 changed files with 864 additions and 239 deletions

View file

@ -16,12 +16,16 @@ usr/share/ahenk/base/config/config_manager.py
usr/share/ahenk/base/config/__init__.py usr/share/ahenk/base/config/__init__.py
usr/share/ahenk/base/config usr/share/ahenk/base/config
usr/share/ahenk/base/system/system.py usr/share/ahenk/base/system/system.py
usr/share/ahenk/base/system/disk_info.py
usr/share/ahenk/base/system usr/share/ahenk/base/system
usr/share/ahenk/base/timer/setup_timer.py usr/share/ahenk/base/timer/setup_timer.py
usr/share/ahenk/base/timer/timer.py usr/share/ahenk/base/timer/timer.py
usr/share/ahenk/base/timer usr/share/ahenk/base/timer
usr/share/ahenk/base/util/util.py usr/share/ahenk/base/util/util.py
usr/share/ahenk/base/util 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_base.py
usr/share/ahenk/base/event/event_manager.py usr/share/ahenk/base/event/event_manager.py
usr/share/ahenk/base/event 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/message_response_queue.py
usr/share/ahenk/base/messaging usr/share/ahenk/base/messaging
usr/share/ahenk/base/default_policy/config-files/xfce4-notifyd.xml 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/config-files
usr/share/ahenk/base/default_policy/default_policy.py usr/share/ahenk/base/default_policy/default_policy.py
usr/share/ahenk/base/default_policy/__init__.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_webcam.sh
usr/share/ahenk/plugins/usb/scripts/ENABLED_usbhid.sh usr/share/ahenk/plugins/usb/scripts/ENABLED_usbhid.sh
usr/share/ahenk/plugins/usb/scripts 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/init.py
usr/share/ahenk/plugins/usb/manage-usb-rules.py
usr/share/ahenk/plugins/usb/main.py usr/share/ahenk/plugins/usb/main.py
usr/share/ahenk/plugins/usb/logout.py usr/share/ahenk/plugins/usb/logout.py
usr/share/ahenk/plugins/usb/policy.py usr/share/ahenk/plugins/usb/policy.py

View file

@ -30,6 +30,7 @@ from base.scope import Scope
from base.system.system import System from base.system.system import System
from base.task.task_manager import TaskManager from base.task.task_manager import TaskManager
from base.util.util import Util from base.util.util import Util
from base.default_config.default_config import DefaultConfig
from easygui import msgbox from easygui import msgbox
sys.path.append('../..') sys.path.append('../..')
@ -159,7 +160,7 @@ class AhenkDaemon(BaseDaemon):
# self.registration_failed() # self.registration_failed()
while registration.is_registered() is False: while registration.is_registered() is False:
print("Registration attemp") print("Registration attempt")
max_attempt_number -= 1 max_attempt_number -= 1
self.logger.debug('Ahenk is not registered. Attempting for registration') self.logger.debug('Ahenk is not registered. Attempting for registration')
# registration.registration_request(self.register_hostname,self.register_user_name,self.register_user_password,self.register_directory_server) # registration.registration_request(self.register_hostname,self.register_user_name,self.register_user_password,self.register_directory_server)
@ -274,6 +275,10 @@ class AhenkDaemon(BaseDaemon):
else: else:
self.logger.info('local users will not be disabled because local_user_paramater is FALSE') 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): def run(self):
""" docstring""" """ docstring"""
print('Ahenk running...') print('Ahenk running...')
@ -319,6 +324,8 @@ class AhenkDaemon(BaseDaemon):
self.init_execution_manager() self.init_execution_manager()
self.logger.info('Execution Manager was set') self.logger.info('Execution Manager was set')
self.default_settings()
self.check_registration() self.check_registration()
self.is_registered() self.is_registered()
@ -341,7 +348,6 @@ class AhenkDaemon(BaseDaemon):
# if registration.is_ldap_registered() is False: # if registration.is_ldap_registered() is False:
# logger.debug('Attempting to registering ldap') # logger.debug('Attempting to registering ldap')
# registration.ldap_registration_request() #TODO work on message # registration.ldap_registration_request() #TODO work on message
self.logger.info('LDAP registration of Ahenk is completed') self.logger.info('LDAP registration of Ahenk is completed')
self.messenger.send_direct_message('test') self.messenger.send_direct_message('test')

View file

@ -60,6 +60,7 @@ class CommandRunner(object):
json_data = json.loads(event) json_data = json.loads(event)
self.logger.info(event) self.logger.info(event)
except Exception as e: except Exception as e:
self.logger.error( self.logger.error(
'A problem occurred while loading json. Check json format! Error Message: {0}.' '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(): if str(json_data['event']) == 'login' and self.check_last_login():
username = json_data['username'] username = json_data['username']
display = json_data['display'] if username != "Debian-gdm" and username != "gdm":
desktop = json_data['desktop'] display = json_data['display']
desktop = json_data['desktop']
ip = None ip = None
if 'ip' in json_data: if 'ip' in json_data:
ip = json_data['ip'] ip = json_data['ip']
domain = None domain = None
if 'domain' in json_data: if 'domain' in json_data:
domain = json_data['domain'] domain = json_data['domain']
self.logger.info('login event is handled for user: {0}'.format(username)) 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 parameters of login user, username: {0}, display: {1}, desktop: {2}, domain: {3}'.format(username, display, desktop, domain))
Util.execute("systemctl restart sssd.service") Util.execute("systemctl restart sssd.service")
login_message = self.message_manager.login_msg(username,ip) login_message = self.message_manager.login_msg(username,ip)
self.messenger.send_direct_message(login_message) self.messenger.send_direct_message(login_message)
agreement = Agreement() agreement = Agreement()
agreement_choice = None agreement_choice = None
if agreement.check_agreement(username) is not True and System.Ahenk.agreement() == '1': if agreement.check_agreement(username) is not True and System.Ahenk.agreement() == '1':
self.logger.debug('User {0} has not accepted agreement.'.format(username)) self.logger.debug('User {0} has not accepted agreement.'.format(username))
thread_ask = Process(target=agreement.ask, args=(username, display,)) thread_ask = Process(target=agreement.ask, args=(username, display,))
thread_ask.start() thread_ask.start()
agreement_timeout = self.conf_manager.get('SESSION', 'agreement_timeout') agreement_timeout = self.conf_manager.get('SESSION', 'agreement_timeout')
timeout = int(agreement_timeout) # sec timeout = int(agreement_timeout) # sec
timer = time.time() timer = time.time()
while 1: while 1:
if thread_ask.is_alive() is False: if thread_ask.is_alive() is False:
self.logger.warning('{0} was answered the question '.format(username)) self.logger.warning('{0} was answered the question '.format(username))
if Agreement().check_agreement(username) is True: if Agreement().check_agreement(username) is True:
self.logger.warning('Choice of {0} is YES'.format(username)) self.logger.warning('Choice of {0} is YES'.format(username))
agreement_choice = True agreement_choice = True
break break
elif Agreement().check_agreement(username) is False: elif Agreement().check_agreement(username) is False:
self.logger.warning('Choice of {0} is NO'.format(username)) self.logger.warning('Choice of {0} is NO'.format(username))
agreement_choice = False 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) Util.close_session(username)
self.logger.warning(
'Session of {0} was ended because of timeout of contract agreement'.format(
username))
break break
time.sleep(1)
if (time.time() - timer) > timeout: if agreement_choice is not None:
if thread_ask.is_alive(): self.messenger.send_direct_message(
thread_ask.terminate() self.message_manager.agreement_answer_msg(username, agreement_choice))
Util.close_session(username) else:
self.logger.warning( agreement_choice = True
'Session of {0} was ended because of timeout of contract agreement'.format(
username))
break
time.sleep(1)
if agreement_choice is not None: if agreement_choice is True or System.Ahenk.agreement() != '1':
self.messenger.send_direct_message( self.db_service.delete('session', '1=1')
self.message_manager.agreement_answer_msg(username, agreement_choice)) self.logger.info('Display is {0}, desktop env is {1} for {2}'.format(display, desktop, username))
else: session_columns = self.db_service.get_cols('session')
agreement_choice = True # ['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': # Default policy for users --->> START
self.db_service.delete('session', '1=1') self.logger.info("Applying default policies for user {0}".format(Util.get_username()))
self.logger.info('Display is {0}, desktop env is {1} for {2}'.format(display, desktop, username)) self.default_policy.default_firefox_policy(Util.get_username())
session_columns = self.db_service.get_cols('session') self.default_policy.disable_update_package_notify(Util.get_username())
# ['username', 'display', 'desktop', 'timestamp', 'ip', 'domain'] self.default_policy.create_pulseaudio_autostart()
self.db_service.update('session', session_columns, # Default policy for users --->> STOP
[username, display, desktop, str(int(time.time())), ip, domain])
# Default policy for users --->> START get_policy_message = self.message_manager.policy_request_msg(username)
self.logger.info("Applying default policies for user {0}".format(Util.get_username())) self.plugin_manager.process_mode('safe', username)
self.default_policy.default_firefox_policy(Util.get_username()) self.plugin_manager.process_mode('login', 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) kward = dict()
self.plugin_manager.process_mode('safe', username) kward['timeout_args'] = username
self.plugin_manager.process_mode('login', username) kward['checker_args'] = username
kward = dict() SetupTimer.start(Timer(timeout=System.Ahenk.get_policy_timeout(),
kward['timeout_args'] = username timeout_function=self.execute_manager.execute_default_policy,
kward['checker_args'] = username checker_func=self.execute_manager.is_policy_executed, kwargs=kward))
SetupTimer.start(Timer(timeout=System.Ahenk.get_policy_timeout(), self.logger.info('Requesting updated policies from Lider. If Ahenk could not reach updated '
timeout_function=self.execute_manager.execute_default_policy, 'policies in {0} sec, booked policies will be executed'.format(
checker_func=self.execute_manager.is_policy_executed, kwargs=kward)) 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': elif str(json_data['event']) == 'logout':
username = json_data['username'] username = json_data['username']
self.execute_manager.remove_user_executed_policy_dict(username) if username != "Debian-gdm" and username != "gdm":
self.plugin_manager.process_mode('logout', username) self.execute_manager.remove_user_executed_policy_dict(username)
self.plugin_manager.process_mode('safe', username) self.plugin_manager.process_mode('logout', username)
self.db_service.delete('session', '1=1') self.plugin_manager.process_mode('safe', username)
# TODO delete all user records while initializing if username != "Debian-gdm":
self.logger.info('logout event is handled for user: {0}'.format(username)) self.db_service.delete('session', '1=1')
ip = None # TODO delete all user records while initializing
if 'ip' in json_data: self.logger.info('logout event is handled for user: {0}'.format(username))
ip = json_data['ip'] ip = None
if 'ip' in json_data:
ip = json_data['ip']
logout_message = self.message_manager.logout_msg(username,ip) logout_message = self.message_manager.logout_msg(username,ip)
self.messenger.send_direct_message(logout_message) self.messenger.send_direct_message(logout_message)
self.logger.info('Ahenk polkit file deleting..') self.logger.info('Ahenk polkit file deleting..')
self.delete_polkit_user() self.delete_polkit_user()
# self.db_service.delete('session', 'username=\'{0}\''.format(username)) # self.db_service.delete('session', 'username=\'{0}\''.format(username))
elif str(json_data['event']) == 'send': elif str(json_data['event']) == 'send':
self.logger.info('Sending message over ahenkd command. Response Message: {0}'.format( self.logger.info('Sending message over ahenkd command. Response Message: {0}'.format(

View file

@ -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()

View file

@ -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

View file

@ -134,4 +134,18 @@ class DefaultPolicy:
new_element.attrib["value"] = app_name_for_blocking new_element.attrib["value"] = app_name_for_blocking
tree.write(fileName) tree.write(fileName)
else: else:
self.logger.info("'" + app_name_for_blocking + "' is already added to muted_applications tag.") 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")

View file

@ -95,13 +95,23 @@ class AnonymousMessenger(ClientXMPP):
def recv_direct_message(self, msg): def recv_direct_message(self, msg):
if msg['type'] in ['normal']: if msg['type'] in ['normal']:
self.logger.info('---------->Received message: {0}'.format(str(msg['body'])))
self.logger.info('Reading registration reply') self.logger.info('Reading registration reply')
j = json.loads(str(msg['body'])) j = json.loads(str(msg['body']))
message_type = j['type'] message_type = j['type']
status = str(j['status']).lower() status = str(j['status']).lower()
dn = str(j['agentDn']) dn = str(j['agentDn'])
self.logger.debug('Registration status: ' + str(status)) 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): if 'not_authorized' == str(status):
self.logger.debug('[REGISTRATION IS FAILED]. User not authorized') 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)) self.logger.debug('Fired event is: {0}'.format(message_type))
def send_direct_message(self, msg): 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') self.send_message(mto=self.receiver, mbody=msg, mtype='normal')

View file

@ -2,12 +2,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com> # Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
import json import json
import os
from base.scope import Scope from base.scope import Scope
from base.system.system import System from base.system.system import System
from base.util.util import Util from base.util.util import Util
from base.system.disk_info import DiskInfo from base.system.disk_info import DiskInfo
import os
# TODO Message Factory # 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(']', '')) 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.monitors'] = str(System.Hardware.monitors()),
data['hardware.screens'] = str(System.Hardware.screens()), data['hardware.screens'] = str(System.Hardware.screens()),
data['hardware.usbDevices'] = str(System.Hardware.usb_devices()), data['hardware.usbDevices'] = str(System.Hardware.usb_devices()),
@ -91,10 +92,10 @@ class Messaging(object):
data['hardware.systemDefinitions'] = str(System.Hardware.system_definitions()), data['hardware.systemDefinitions'] = str(System.Hardware.system_definitions()),
if len(ssd_list) > 0: if len(ssd_list) > 0:
data['hardware.disk.ssd.info'] = ssd_list data['hardwareDiskSsdInfo'] = str(ssd_list)
if len(hdd_list) > 0: if len(hdd_list) > 0:
data['hardware.disk.hdd.info'] = hdd_list data['hardwareDiskHddInfo'] = str(hdd_list)
json_data = json.dumps(data) json_data = json.dumps(data)
self.logger.debug('Login message was created') 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') data['timestamp'] = self.db_service.select_one_result('registration', 'timestamp', ' 1=1')
json_data = json.dumps(data) json_data = json.dumps(data)
self.logger.debug('Registration message was created') 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 return json_data
def ldap_registration_msg(self): def ldap_registration_msg(self):

View file

@ -92,7 +92,17 @@ class Messenger(ClientXMPP):
def send_direct_message(self, msg): def send_direct_message(self, msg):
try: 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') self.send_message(mto=self.receiver, mbody=msg, mtype='normal')
except Exception as e: except Exception as e:
self.logger.error( self.logger.error(
@ -109,12 +119,31 @@ class Messenger(ClientXMPP):
self.logger.info('---------->Received message: {0}'.format(str(msg['body']))) self.logger.info('---------->Received message: {0}'.format(str(msg['body'])))
if j['type'] == "EXECUTE_TASK": if j['type'] == "EXECUTE_TASK":
i = json.loads(str(j['task'])) message = json.loads(str(msg['body']))
plugin_name = i['plugin']['name'] task = json.loads(str(message['task']))
if plugin_name == "manage-root": #plugin_name = task['plugin']['name']
parameter_map = i['parameterMap'] parameter_map = task['parameterMap']
parameter_map.pop("RootPassword") use_file_transfer = message['fileServerConf']
self.logger.info("---------->Received message: {}".format(str(parameter_map))) 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: else:
self.logger.info('---------->Received message: {0}'.format(str(msg['body']))) self.logger.info('---------->Received message: {0}'.format(str(msg['body'])))
self.event_manger.fireEvent(message_type, str(msg['body'])) self.event_manger.fireEvent(message_type, str(msg['body']))

View file

@ -17,7 +17,6 @@ debug_level = 9
id_provider = ldap id_provider = ldap
auth_provider = ldap auth_provider = ldap
access_provider = ldap access_provider = ldap
#ldap_access_filter = (employeeType=admin)
ldap_access_order = ppolicy ldap_access_order = ppolicy
pam_verbosity=2 pam_verbosity=2
###ldap_pwdlockout_dn### ###ldap_pwdlockout_dn###
@ -34,7 +33,6 @@ ldap_user_gecos = cn
ldap_tls_reqcert = never ldap_tls_reqcert = never
ldap_auth_disable_tls_never_use_in_production = true ldap_auth_disable_tls_never_use_in_production = true
override_shell = /bin/bash override_shell = /bin/bash
enumerate = true
cache_credentials = true cache_credentials = true
sudo_provider = ldap sudo_provider = ldap
###ldap_sudo_search_base### ###ldap_sudo_search_base###

View file

@ -12,7 +12,7 @@ config_file_version = 2
services = nss, pam services = nss, pam
###[domain/### ###[domain/###
###ad_domain### ###ad_server###
###krb5_realm### ###krb5_realm###
realmd_tags = manages-system joined-with-adcli realmd_tags = manages-system joined-with-adcli
cache_credentials = True cache_credentials = True

View file

@ -12,7 +12,7 @@ config_file_version = 2
services = nss, pam services = nss, pam
###[domain/### ###[domain/###
###ad_domain### ###ad_server###
###krb5_realm### ###krb5_realm###
realmd_tags = manages-system joined-with-adcli realmd_tags = manages-system joined-with-adcli
cache_credentials = True cache_credentials = True

View file

@ -16,7 +16,7 @@ class ExecuteCancelLDAPLogin:
def cancel(self): def cancel(self):
self.logger.info('Purge ldap packages') self.logger.info('Purge ldap packages')
self.util.execute("apt-get install sudo -y") 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.util.execute("apt autoremove -y")
self.logger.info('purging successfull') self.logger.info('purging successfull')

View file

@ -14,7 +14,7 @@ class ExecuteCancelSSSDAuthentication:
self.util = Util() self.util = Util()
def cancel(self): 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") self.util.execute("apt autoremove -y")
if self.util.is_exist("/etc/sssd"): if self.util.is_exist("/etc/sssd"):

View file

@ -178,7 +178,7 @@ class ExecuteLDAPLogin:
self.util.write_file(libnss_ldap_file_path, content, 'a+') self.util.write_file(libnss_ldap_file_path, content, 'a+')
self.logger.info("Configuration has been made to {0}.".format(libnss_ldap_file_path)) 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: if result_code != 0:
self.logger.error("Error occured while downloading libnss-db libpam-ccreds.") self.logger.error("Error occured while downloading libnss-db libpam-ccreds.")
else: else:

View file

@ -1,6 +1,7 @@
#!/usr/bin/python3 #!/usr/bin/python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Author: Agah Hulusi ÖZ <enghulusi@gmail.com> # Author: Agah Hulusi ÖZ <enghulusi@gmail.com>
import subprocess
from base.scope import Scope from base.scope import Scope
from base.util.util import Util from base.util.util import Util
@ -134,7 +135,7 @@ class ExecuteSSSDAdAuthentication:
# Installation of required packages # Installation of required packages
(result_code, p_out, p_err) = self.util.execute( (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): if (result_code == 0):
self.logger.info("İndirmeler Başarılı") self.logger.info("İndirmeler Başarılı")
else: else:
@ -155,6 +156,10 @@ class ExecuteSSSDAdAuthentication:
file_default_pam.close() file_default_pam.close()
self.discover_try_counter2 = 0 self.discover_try_counter2 = 0
try: try:
while (True): while (True):
self.discover_try_counter2 = self.discover_try_counter2 + 1 self.discover_try_counter2 = self.discover_try_counter2 + 1
@ -179,7 +184,7 @@ class ExecuteSSSDAdAuthentication:
if (self.join_try_counter == 5): if (self.join_try_counter == 5):
break break
else: 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, "echo \"{0}\" | realm join --user={1} {2}".format(password, ad_username,
domain_name.upper())) domain_name.upper()))
if (result_code == 0): 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("###domains###", "domains = {}".format(domain_name))
file_data = file_data.replace("###[domain/###", "[domain/{}]".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("###krb5_realm###", "krb5_realm = {}".format(domain_name.upper()))
file_data = file_data.replace("###ad_hostname###", file_data = file_data.replace("###ad_hostname###",
"ad_hostname = {0}.{1}".format(self.system.Os.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("###domains###", "domains = {}".format(domain_name))
file_data = file_data.replace("###[domain/###", "[domain/{}]".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("###krb5_realm###", "krb5_realm = {}".format(domain_name.upper()))
file_sssd.close() file_sssd.close()
@ -352,3 +357,19 @@ class ExecuteSSSDAdAuthentication:
self.logger.info("AD Login işlemi esnasında hata oluştu.") self.logger.info("AD Login işlemi esnasında hata oluştu.")
return False 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)), ''

View file

@ -56,7 +56,7 @@ class ExecuteSSSDAuthentication:
file_sssd.close() file_sssd.close()
# Install libpam-sss sssd-common for sssd authentication # 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: if result_code != 0:

View file

@ -152,7 +152,7 @@ class Registration:
self.install_and_config_ad(reg_reply) self.install_and_config_ad(reg_reply)
self.change_permissions_for_local_users() self.change_permissions_for_local_users()
self.create_ahenk_pulseaudio_desktop_file() # self.create_ahenk_pulseaudio_desktop_file()
except Exception as e: except Exception as e:
self.logger.error('Registration error. Error Message: {0}.'.format(str(e))) self.logger.error('Registration error. Error Message: {0}.'.format(str(e)))
@ -297,12 +297,12 @@ class Registration:
'processor': System.Hardware.Cpu.brand(), 'processor': System.Hardware.Cpu.brand(),
'agentVersion': Util.get_agent_version(), 'agentVersion': Util.get_agent_version(),
} }
ssd_list, hdd_list = DiskInfo.get_all_disks() ssd_list, hdd_list = DiskInfo.get_all_disks()
if len(ssd_list) > 0: 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: if len(hdd_list) > 0:
params['hardware.disk.hdd.info'] = hdd_list params['hardware.disk.hdd.info'] = str(hdd_list)
return json.dumps(params) return json.dumps(params)
@ -637,6 +637,12 @@ class Registration:
def delete_ahenk_pulseaudio_desktop_file(self): def delete_ahenk_pulseaudio_desktop_file(self):
ahenkpulseaudio = "/etc/xdg/autostart/ahenk.pulseaudio.desktop" 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): if self.util.is_exist(ahenkpulseaudio):
self.util.delete_file(ahenkpulseaudio) self.util.delete_file(ahenkpulseaudio)
self.logger.info("ahenk.pulseaudio.desktop autostart file deleted") self.logger.info("ahenk.pulseaudio.desktop autostart file deleted")

View file

@ -1,15 +1,50 @@
#!/usr/bin/env python3 # !/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Author: Agah Hulusi ÖZ <enghulusi@gmail.com> # Author: Agah Hulusi ÖZ <enghulusi@gmail.com>
from base.util.util import Util from base.util.util import Util
import psutil
# HDD and SSD disk information # HDD and SSD disk information
class DiskInfo(): 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 @staticmethod
def get_all_disks(): 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") txt = p_out.split("\n")
while '' in txt: while '' in txt:
txt.remove('') txt.remove('')
@ -45,6 +80,8 @@ class DiskInfo():
ssd_list_counter = 0 ssd_list_counter = 0
hdd_list_counter = 0 hdd_list_counter = 0
is_first_disk = True is_first_disk = True
resource_name = 0
resource_disk = 0
for item in detail_txt: for item in detail_txt:
if item[1] == "disk": if item[1] == "disk":
if is_first_disk: if is_first_disk:
@ -64,8 +101,17 @@ class DiskInfo():
total = item[3] total = item[3]
type = item[2] type = item[2]
else: else:
if len(item) > 6 and item[0] != "NAME": if len(item) > 7 and item[0] != "NAME":
used += int(item[6]) 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": if type == "0":
ssd_list[ssd_list_counter]["used"] = used ssd_list[ssd_list_counter]["used"] = used
ssd_list_counter += 1 ssd_list_counter += 1
@ -78,5 +124,4 @@ class DiskInfo():
for item in hdd_list: for item in hdd_list:
item["total"] = int(int(item["total"]) / (1000 * 1000)) item["total"] = int(int(item["total"]) / (1000 * 1000))
item["used"] = int(int(item["used"]) / (1000 * 1000)) item["used"] = int(int(item["used"]) / (1000 * 1000))
return ssd_list, hdd_list
return ssd_list, hdd_list

View file

@ -12,12 +12,14 @@ import socket
import struct import struct
import netifaces import netifaces
from uuid import getnode as get_mac from uuid import getnode as get_mac
import distro
import cpuinfo import cpuinfo
import psutil import psutil
from base.scope import Scope from base.scope import Scope
from base.util.util import Util from base.util.util import Util
from base.system.disk_info import DiskInfo
class System: class System:
@ -337,19 +339,24 @@ class System:
@staticmethod @staticmethod
def distribution_name(): def distribution_name():
return platform.linux_distribution()[0] #return platform.linux_distribution()[0]
return distro.linux_distribution()[0]
@staticmethod @staticmethod
def distribution_version(): def distribution_version():
return platform.linux_distribution()[1] # return platform.linux_distribution()[1]
return distro.linux_distribution()[1]
@staticmethod @staticmethod
def distribution_id(): def distribution_id():
return platform.linux_distribution()[2] # return platform.linux_distribution()[2]
return distro.linux_distribution()[2]
@staticmethod @staticmethod
def version(): def version():
return platform.version() # return platform.version()
version = distro.lsb_release_info()['description'] +"-"+ distro.lsb_release_info()["release"]
return version
@staticmethod @staticmethod
def kernel_release(): def kernel_release():
@ -429,15 +436,18 @@ class System:
@staticmethod @staticmethod
def total(): 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 @staticmethod
def used(): 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 @staticmethod
def free(): 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 @staticmethod
def percent(): def percent():
@ -494,20 +504,28 @@ class System:
@staticmethod @staticmethod
def mac_addresses(): def mac_addresses():
mac = get_mac() mac_addresses = []
':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2)) nics = psutil.net_if_addrs()
arr = [] nics.pop('lo') # remove loopback since it doesnt have a real mac address
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 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 @staticmethod
def screen_info_json_obj(info): def screen_info_json_obj(info):

View file

@ -30,8 +30,9 @@ class ADLogin(AbstractPlugin):
ad_username = self.data['ad_username'] ad_username = self.data['ad_username']
admin_password = self.data['admin_password'] admin_password = self.data['admin_password']
ad_port = self.data['ad_port'] 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: if execution_result is False:
self.context.create_response(code=self.message_code.TASK_ERROR.value, 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.', 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 = configparser.ConfigParser()
config.read(self.ahenk_conf_path) config.read(self.ahenk_conf_path)
config.set('MACHINE', 'user_disabled', 'true') config.set('MACHINE', 'user_disabled', 'true')
with open(self.ahenk_conf_path, 'w') as configfile: with open(self.ahenk_conf_path, 'w') as configfile:
self.logger.info('Opening config file ') self.logger.info('Opening config file ')
config.write(configfile) config.write(configfile)
configfile.close() configfile.close()
self.logger.info('User disabled value Disabled') self.logger.info('User disabled value Disabled')
else: else:
self.logger.info("local users will not be disabled because local_user parameter is FALSE") self.logger.info("local users will not be disabled because local_user parameter is FALSE")
self.shutdown() self.shutdown()
self.context.create_response(code=self.message_code.TASK_PROCESSED.value, 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.', 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) content_type=self.get_content_type().APPLICATION_JSON.value)
except Exception as e: except Exception as e:
self.logger.error(str(e)) self.logger.error(str(e))
self.context.create_response(code=self.message_code.TASK_ERROR.value, self.context.create_response(code=self.message_code.TASK_ERROR.value,

View file

@ -2,6 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Author:Mine DOGAN <mine.dogan@agem.com.tr> # Author:Mine DOGAN <mine.dogan@agem.com.tr>
# Author:Tuncay ÇOLAK <tuncay.colak@tubitak.gov.tr> # Author:Tuncay ÇOLAK <tuncay.colak@tubitak.gov.tr>
import subprocess
from base.plugin.abstract_plugin import AbstractPlugin from base.plugin.abstract_plugin import AbstractPlugin
from pathlib import Path from pathlib import Path
@ -60,10 +61,10 @@ class AddUser(AbstractPlugin):
self.logger.debug('Added user to these groups: {}'.format(self.groups)) self.logger.debug('Added user to these groups: {}'.format(self.groups))
if str(self.password).strip() != "": 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 = p_out.strip()
# shadow_password = crypt.crypt(self.password) # 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.logger.debug('Changed password.')
self.execute(self.change_shell.format(self.username)) 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, 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.') 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): def handle_task(task, context):
add_user = AddUser(task, context) add_user = AddUser(task, context)

View file

@ -2,6 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Author:Mine DOGAN <mine.dogan@agem.com.tr> # Author:Mine DOGAN <mine.dogan@agem.com.tr>
# Author:Tuncay ÇOLAK <tuncay.colak@tubitak.gov.tr> # Author:Tuncay ÇOLAK <tuncay.colak@tubitak.gov.tr>
import subprocess
from base.plugin.abstract_plugin import AbstractPlugin from base.plugin.abstract_plugin import AbstractPlugin
from pathlib import Path from pathlib import Path
@ -64,9 +65,9 @@ class EditUser(AbstractPlugin):
self.username = self.new_username self.username = self.new_username
if str(self.password).strip() != "": 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 = 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.') self.logger.debug('Changed password.')
if self.current_home != self.home: if self.current_home != self.home:
@ -155,6 +156,21 @@ class EditUser(AbstractPlugin):
self.context.create_response(code=self.message_code.TASK_ERROR.value, 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.') 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): def handle_task(task, context):
edit_user = EditUser(task, context) edit_user = EditUser(task, context)
edit_user.handle_task() edit_user.handle_task()

View file

@ -98,21 +98,16 @@ class RootPassword(AbstractPlugin):
try: try:
process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE,
stdout=subprocess.PIPE, shell=shell) stdout=subprocess.PIPE, shell=shell)
self.logger.debug('Executing command for manage-root') self.logger.debug('Executing command for manage-root')
if result is True: if result is True:
result_code = process.wait() result_code = process.wait()
p_out = process.stdout.read().decode("unicode_escape") p_out = process.stdout.read().decode("unicode_escape")
p_err = process.stderr.read().decode("unicode_escape") p_err = process.stderr.read().decode("unicode_escape")
return result_code, p_out, p_err return result_code, p_out, p_err
else: else:
return None, None, None return None, None, None
except Exception as e: 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): def handle_task(task, context):

View file

@ -23,10 +23,10 @@ class AddDNS(AbstractPlugin):
def handle_task(self): def handle_task(self):
try: try:
if self.is_active is True: 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.') self.logger.debug('Created active dns content.')
else: else:
content = '#nameserver {}\n'.format(self.ip) content = '\n#nameserver {}\n'.format(self.ip)
self.logger.debug('Created passive dns content.') self.logger.debug('Created passive dns content.')
self.logger.debug('Writing to file...') self.logger.debug('Writing to file...')

View file

@ -21,7 +21,7 @@ class AddDomain(AbstractPlugin):
def handle_task(self): def handle_task(self):
try: 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.logger.debug('Writing to file...')
self.write_file(self.dns_file, content, 'a') self.write_file(self.dns_file, content, 'a')

View file

@ -24,10 +24,10 @@ class AddHost(AbstractPlugin):
def handle_task(self): def handle_task(self):
try: try:
if self.is_active is True: 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.') self.logger.debug('Created active host content.')
else: 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('Created passive host content.')
self.logger.debug('Writing to file...') self.logger.debug('Writing to file...')

View file

@ -32,12 +32,12 @@ class AddNetwork(AbstractPlugin):
try: try:
if self.type == 'STATIC': if self.type == 'STATIC':
if self.is_active is True: 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.ip,
self.netmask, self.netmask,
self.gateway) self.gateway)
else: 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.ip,
self.netmask, self.netmask,
self.gateway) self.gateway)

View file

@ -21,36 +21,45 @@ class CheckPackage(AbstractPlugin):
package_version = str((self.data)['packageVersion']) package_version = str((self.data)['packageVersion'])
dn = self.Ahenk.dn() dn = self.Ahenk.dn()
res = {} res = {}
result_message = "Paket yüklü"
if dn is None: if dn is None:
dn = " " dn = " "
res["package_name"] = package_name
res["dn"] = dn
result_code, result, p_err = self.execute('dpkg -s {} | grep Version'.format(package_name)) result_code, result, p_err = self.execute('dpkg -s {} | grep Version'.format(package_name))
data = result.split(': ') 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 self.logger.debug("Result is: - {}".format(result_message))
if package_version is None or len(package_version) == 0: self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
result = 'Paket yüklü' message='{0} - {1}'.format(package_name, result_message),
res['version'] = data[1] data=json.dumps(res),
elif data[1] is not None and (package_version + '\n') in data[ content_type=self.get_content_type().APPLICATION_JSON.value)
1]: # Package version is the same with wanted version self.logger.debug("Package Info has sent")
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")
except Exception as e: except Exception as e:
self.logger.debug(str(e)) self.logger.debug(str(e))
self.context.create_response(code=self.message_code.TASK_ERROR.value, self.context.create_response(code=self.message_code.TASK_ERROR.value,

View file

@ -3,6 +3,7 @@
# Author: Tuncay ÇOLAK <tuncay.colak@tubitak.gov.tr> # Author: Tuncay ÇOLAK <tuncay.colak@tubitak.gov.tr>
from base.plugin.abstract_plugin import AbstractPlugin from base.plugin.abstract_plugin import AbstractPlugin
from base.system.disk_info import DiskInfo
import json import json
@ -23,6 +24,8 @@ class AgentInfo(AbstractPlugin):
device += ", " device += ", "
device = device + part.device device = device + part.device
ssd_list, hdd_list = DiskInfo.get_all_disks()
data = {'System': self.Os.name(), 'Release': self.Os.kernel_release(), data = {'System': self.Os.name(), 'Release': self.Os.kernel_release(),
'agentVersion': self.get_agent_version(), 'agentVersion': self.get_agent_version(),
'hostname': self.Os.hostname(), 'hostname': self.Os.hostname(),
@ -41,6 +44,13 @@ class AgentInfo(AbstractPlugin):
'memory': self.Hardware.Memory.total(), 'memory': self.Hardware.Memory.total(),
'Device': device, '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.logger.debug("Agent info gathered.")
self.context.create_response(code=self.message_code.TASK_PROCESSED.value, self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
message='Ahenk bilgileri başarıyla güncellendi.', message='Ahenk bilgileri başarıyla güncellendi.',

View file

@ -3,11 +3,13 @@
# Author: Cemre ALPSOY <cemre.alpsoy@agem.com.tr> # Author: Cemre ALPSOY <cemre.alpsoy@agem.com.tr>
# Author: Emre Akkaya <emre.akkaya@agem.com.tr> # Author: Emre Akkaya <emre.akkaya@agem.com.tr>
import json
from psutil import disk_io_counters from psutil import disk_io_counters
from base.plugin.abstract_plugin import AbstractPlugin from base.plugin.abstract_plugin import AbstractPlugin
import json
from base.system.disk_info import DiskInfo from base.system.disk_info import DiskInfo
class ResourceUsage(AbstractPlugin): class ResourceUsage(AbstractPlugin):
def __init__(self, data, context): def __init__(self, data, context):
super(AbstractPlugin, self).__init__() super(AbstractPlugin, self).__init__()
@ -20,14 +22,11 @@ class ResourceUsage(AbstractPlugin):
try: try:
device = "" device = ""
self.logger.debug("Gathering resource usage for disk, memory and CPU.") self.logger.debug("Gathering resource usage for disk, memory and CPU.")
ssd_list, hdd_list = DiskInfo.get_all_disks() ssd_list, hdd_list = DiskInfo.get_all_disks()
for part in self.Hardware.Disk.partitions(): for part in self.Hardware.Disk.partitions():
if len(device) != 0: if len(device) != 0:
device += ", " device += ", "
device = device + part.device device = device + part.device
data = {'System': self.Os.name(), 'Release': self.Os.kernel_release(), data = {'System': self.Os.name(), 'Release': self.Os.kernel_release(),
'Version': self.Os.distribution_version(), 'Machine': self.Os.architecture(), 'Version': self.Os.distribution_version(), 'Machine': self.Os.architecture(),
'CPU Physical Core Count': self.Hardware.Cpu.physical_core_count(), '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 Actual Hz': self.Hardware.Cpu.hz_actual(),
'CPU Advertised Hz': self.Hardware.Cpu.hz_advertised() 'CPU Advertised Hz': self.Hardware.Cpu.hz_advertised()
} }
if len(ssd_list) > 0: 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: 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.logger.debug("Resource usage info gathered.")
self.context.create_response(code=self.message_code.TASK_PROCESSED.value, self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
message='Anlık kaynak kullanım bilgisi başarıyla toplandı.', message='Anlık kaynak kullanım bilgisi başarıyla toplandı.',

View file

@ -97,17 +97,16 @@ class GetServices(AbstractPlugin):
del service[0] 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, 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 # result, out, err = self.execute(self.service_status.format(service[0])) # check service is enable or not on auto start
auto='INACTIVE' result, out, err = self.execute("systemctl is-enabled {0}".format(service[0]))
if 'disabled' in out: auto = 'disabled'
auto='INACTIVE' if 'enabled' in out:
elif 'enabled' in out: auto = 'enabled'
auto='ACTIVE'
if service[2] == 'active': if service[2] == 'active':
self.add_file(service[0], "ACTIVE", auto) self.add_file(service[0], "active", auto)
else: else:
self.add_file(service[0], 'INACTIVE',auto) self.add_file(service[0], 'inactive', auto)
print(service) print(service)

View file

@ -28,7 +28,7 @@ class ServiceList(AbstractPlugin):
return result_code, message, item return result_code, message, item
def set_startup_service(self, service_name, action): 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: if result_code == 0:
message = 'Service startup action was successful: {}'.format(service_name) message = 'Service startup action was successful: {}'.format(service_name)
else: else:
@ -39,17 +39,22 @@ class ServiceList(AbstractPlugin):
def get_service_status(self, service_item): 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)) result, p_out, err = self.execute('systemctl status {0}'.format(service_name))
if 'not-found' in p_out: if 'not-found' in p_out:
service_item["serviceStatus"] = 'Service Not Found' service_item["serviceStatus"] = 'Service Not Found'
elif 'running' in p_out: elif 'running' in p_out:
service_item["serviceStatus"] = 'Running' service_item["serviceStatus"] = 'active'
elif ('inactive' in p_out) or ('failed' in p_out): 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 return service_item
@ -61,30 +66,29 @@ class ServiceList(AbstractPlugin):
for item in items: for item in items:
try: try:
if item['serviceStatus'] is not None and ( 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") resultcode, message, item = self.start_stop_service(item, "start")
resultMessage += message resultMessage += message
if item['serviceStatus'] is not None and ( 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") resultcode, message, item= self.start_stop_service(item, "stop")
resultMessage += message resultMessage += message
if item['startAuto'] is not None and ( if item['startAuto'] is not None and (
str(item['startAuto']) == 'Başlat' or str(item['startAuto']) == 'Start' or str(item['startAuto']) == 'START'): str(item['startAuto']) == 'enabled' or str(item['startAuto']) == 'Start' or str(item['startAuto']) == 'START'):
resultcode, message = self.set_startup_service(item, "defaults") resultcode, message = self.set_startup_service(item['serviceName'], "enable")
resultMessage += message resultMessage += message
if item['startAuto'] is not None and ( if item['startAuto'] is not None and (
str(item['startAuto']) == 'Durdur' or str(item['startAuto']) == 'Stop' or str(item['startAuto']) == 'STOP' ): str(item['startAuto']) == 'disabled' or str(item['startAuto']) == 'Stop' or str(item['startAuto']) == 'STOP'):
resultcode, message = self.set_startup_service(item, "remove") resultcode, message = self.set_startup_service(item['serviceName'], "disable")
resultMessage += message resultMessage += message
item = self.get_service_status(item)
item=self.get_service_status(item)
except Exception as e: except Exception as e:
resultMessage += '{0} servisinin isteklerini gerçekleştirirken hata ile karşılaşıldı. Hdata : {1}\r\n'.format( resultMessage += '{0} servisinin isteklerini gerçekleştirirken hata ile karşılaşıldı. Hdata : {1}\r\n'.format(
str(item['serviceName']), str(e)) str(item['serviceName']), str(e))
self.logger.debug(resultMessage) 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, self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
message='Servis istekleri gerçekleştirildi', message='Servis istekleri gerçekleştirildi',

View file

@ -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()

View file

@ -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()

View file

@ -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()

View file

@ -3,7 +3,7 @@ var=$(lsmod | awk '{print $1}'| grep usblp)
service cups stop service cups stop
if [ -z "$var" ] if [[ -z "$var" ]]
then then
echo "USB printer devices are already blocked" echo "USB printer devices are already blocked"
else else

View file

@ -2,7 +2,7 @@
var=$(lsmod | grep usbhid) var=$(lsmod | grep usbhid)
if [ -z "$var" ] if [[ -z "$var" ]]
then then
echo "USB HID devices are already blocked" echo "USB HID devices are already blocked"
else else
@ -21,7 +21,7 @@ fi
var=$(lsmod | grep psmouse) var=$(lsmod | grep psmouse)
if [ -z "$var" ] if [[ -z "$var" ]]
then then
echo "psmouse is already blocked" echo "psmouse is already blocked"
else else

View file

@ -2,7 +2,7 @@
var=$(lsmod | awk '{print $1}'| grep usb_storage) var=$(lsmod | awk '{print $1}'| grep usb_storage)
if [ -z "$var" ] if [[ -z "$var" ]]
then then
echo "USB storage devices are already blocked" echo "USB storage devices are already blocked"
else else
@ -26,7 +26,7 @@ sleep 2
var=$(lsmod | grep usb_storage | awk '{print $4}') var=$(lsmod | grep usb_storage | awk '{print $4}')
if [ ! -z "$var" ] if [[ ! -z "$var" ]]
then then
IFS=',' read -ra deps <<< "$var" IFS=',' read -ra deps <<< "$var"
for i in "${deps[@]}"; do for i in "${deps[@]}"; do

View file

@ -2,7 +2,7 @@
var=$(lsof -t /dev/video0) var=$(lsof -t /dev/video0)
if [ -z "$var" ] if [[ -z "$var" ]]
then then
echo "Webcam is not in use" echo "Webcam is not in use"
else else
@ -12,7 +12,7 @@ fi
var=$(lsmod | awk '{print $1}'| grep uvcvideo) var=$(lsmod | awk '{print $1}'| grep uvcvideo)
if [ -z "$var" ] if [[ -z "$var" ]]
then then
echo "Webcam is already blocked" echo "Webcam is already blocked"
else else

View file

@ -14,14 +14,14 @@ function log() {
echo "$(date) $0: $@" >> $LOG echo "$(date) $0: $@" >> $LOG
} }
if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; 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 if ([[ -n $PAM_SERVICE ]] && [[ ( $PAM_SERVICE == *"dm" || $PAM_SERVICE == "gdm"* )]]) || ([[ -n $PAM_TTY ]] && [[ $PAM_TTY == ":"* ]]); then
SERVICE="none" SERVICE="none"
if [ -n $PAM_SERVICE ]; then if [[ -n $PAM_SERVICE ]]; then
SERVICE="$PAM_SERVICE" SERVICE="$PAM_SERVICE"
fi fi
TTY_DISPLAY="none" TTY_DISPLAY="none"
if [ -n $PAM_TTY ]; then if [[ -n $PAM_TTY ]]; then
TTY_DISPLAY="$PAM_TTY" TTY_DISPLAY="$PAM_TTY"
fi fi
if [[ $PAM_USER = *'\'* ]]; then if [[ $PAM_USER = *'\'* ]]; then
@ -32,6 +32,6 @@ if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; then
done done
fi fi
log "logout: $PAM_USER service: $SERVICE tty: $TTY_DISPLAY" 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
fi fi

View file

@ -14,14 +14,14 @@ function log() {
echo "$(date) $0: $@" >> $LOG echo "$(date) $0: $@" >> $LOG
} }
if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; 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 if ([[ -n $PAM_SERVICE ]] && [[ ( $PAM_SERVICE == "gdm"* || $PAM_SERVICE == *"dm" )]]) || ([[ -n $PAM_TTY ]] && [[ $PAM_TTY == ":"* ]]); then
SERVICE="none" SERVICE="none"
if [ -n $PAM_SERVICE ]; then if [[ -n $PAM_SERVICE ]]; then
SERVICE="$PAM_SERVICE" SERVICE="$PAM_SERVICE"
fi fi
TTY_DISPLAY="none" TTY_DISPLAY="none"
if [ -n $PAM_TTY ]; then if [[ -n $PAM_TTY ]]; then
TTY_DISPLAY="$PAM_TTY" TTY_DISPLAY="$PAM_TTY"
fi fi
domain="none" domain="none"
@ -35,10 +35,10 @@ if [ -n $PAM_USER ] && [ $PAM_USER != "root" ]; then
fi fi
if [[ $domain != "none" ]]; then if [[ $domain != "none" ]]; then
log "login: $PAM_USER service: $SERVICE tty: $TTY_DISPLAY domain: $domain" 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 else
log "login: $PAM_USER service: $SERVICE tty: $TTY_DISPLAY domain: none" 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 fi
fi fi