synced to development branch

This commit is contained in:
Tuncay ÇOLAK 2020-06-24 12:31:50 +03:00
parent 4237ad9810
commit 74e00e8312
24 changed files with 427 additions and 256 deletions

View file

@ -289,6 +289,7 @@ usr/share/ahenk/plugins/login-manager/scripts/check.py
usr/share/ahenk/plugins/login-manager/scripts usr/share/ahenk/plugins/login-manager/scripts
usr/share/ahenk/plugins/login-manager/manage.py usr/share/ahenk/plugins/login-manager/manage.py
usr/share/ahenk/plugins/login-manager/shutdown.py usr/share/ahenk/plugins/login-manager/shutdown.py
usr/share/ahenk/plugins/login-manager/machine_restart.py
usr/share/ahenk/plugins/login-manager usr/share/ahenk/plugins/login-manager
usr/share/ahenk/plugins usr/share/ahenk/plugins
usr/share/ahenk/api/service/ps_util.py usr/share/ahenk/api/service/ps_util.py

View file

@ -147,7 +147,7 @@ class AhenkDaemon(BaseDaemon):
def check_registration(self): def check_registration(self):
""" docstring""" """ docstring"""
# max_attempt_number = int(System.Hardware.Network.interface_size()) * 3 # max_attempt_number = int(System.Hardware.Network.interface_size()) * 3
max_attempt_number = 1 max_attempt_number = 4
# self.logger.debug() # self.logger.debug()
# logger = Scope.getInstance().getLogger() # logger = Scope.getInstance().getLogger()
registration = Scope.get_instance().get_registration() registration = Scope.get_instance().get_registration()
@ -158,12 +158,15 @@ class AhenkDaemon(BaseDaemon):
# if registration.registration_request() == False: # if registration.registration_request() == False:
# self.registration_failed() # self.registration_failed()
if registration.is_registered() is False: while registration.is_registered() is False:
print("Registration attemp") print("Registration attemp")
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) registration.registration_request(self.register_hostname,self.register_user_name,self.register_user_password,self.register_directory_server)
if max_attempt_number < 0:
self.logger.warning('Number of Attempting for registration is over')
Util.execute("/etc/init.d/ahenk stop")
break
#if max_attempt_number < 0: #if max_attempt_number < 0:
# self.logger.warning('Number of Attempting for registration is over') # self.logger.warning('Number of Attempting for registration is over')
# self.registration_failed() # self.registration_failed()
@ -240,10 +243,11 @@ class AhenkDaemon(BaseDaemon):
Util.create_file(System.Ahenk.fifo_file()) Util.create_file(System.Ahenk.fifo_file())
Util.set_permission(System.Ahenk.fifo_file(), '600') Util.set_permission(System.Ahenk.fifo_file(), '600')
def set_register_user(self, hostName, username, password): def set_register_user(self, hostName, username, password,directoryServer):
self.register_hostname=hostName self.register_hostname=hostName
self.register_user_name=username self.register_user_name=username
self.register_user_password=password self.register_user_password=password
self.register_directory_server = directoryServer
# if user_disabled is when ahenk service restarted TRUE disabled local users # if user_disabled is when ahenk service restarted TRUE disabled local users
def disable_local_users(self): def disable_local_users(self):
@ -349,7 +353,7 @@ if __name__ == '__main__':
ahenk_daemon = AhenkDaemon(System.Ahenk.pid_path()) ahenk_daemon = AhenkDaemon(System.Ahenk.pid_path())
try: try:
if len(sys.argv) == 2 and (sys.argv[1] in ('start', 'stop', 'restart', 'status')): if len(sys.argv) == 2 and (sys.argv[1] in ('start', 'stop', 'restart', 'status')):
ahenk_daemon.set_register_user(None, None, None) ahenk_daemon.set_register_user(None, None, None, None)
if sys.argv[1] == 'start': if sys.argv[1] == 'start':
if System.Ahenk.is_running() is True: if System.Ahenk.is_running() is True:
print('There is already running Ahenk service. It will be killed.[{0}]'.format( print('There is already running Ahenk service. It will be killed.[{0}]'.format(
@ -375,12 +379,13 @@ if __name__ == '__main__':
else: else:
print('Unknown command. Usage : %s start|stop|restart|status|clean' % sys.argv[0]) print('Unknown command. Usage : %s start|stop|restart|status|clean' % sys.argv[0])
sys.exit(2) sys.exit(2)
elif len(sys.argv) > 2 and (sys.argv[1] in ('register')): elif len(sys.argv) > 2 and (sys.argv[1] in ('start')):
params = sys.argv[1] params = sys.argv[1]
hostName = sys.argv[2] hostName = sys.argv[2]
userName = sys.argv[3] userName = sys.argv[3]
password = sys.argv[4] password = sys.argv[4]
ahenk_daemon.set_register_user(hostName,userName,password) directoryServer = sys.argv[5]
ahenk_daemon.set_register_user(hostName,userName,password,directoryServer)
ahenk_daemon.run() ahenk_daemon.run()
else: else:

View file

@ -73,9 +73,13 @@ class Commander(object):
data['event'] = 'remove' data['event'] = 'remove'
data['plugins'] = params[3] data['plugins'] = params[3]
elif len(params) > 1 and params[1] == 'unregister': elif len(params) == 2 and params[1] == 'unregister':
data['event'] = params[1] data['event'] = params[1]
elif len(params) == 4 and params[1] == 'unregister':
data['event'] = params[1]
data['userName'] = params[2]
data['password'] = params[3]
elif len(params) > 5 and params[1] == 'send': elif len(params) > 5 and params[1] == 'send':
data['event'] = params[1] data['event'] = params[1]

View file

@ -181,12 +181,24 @@ class CommandRunner(object):
message = json.dumps(json_data['message']) message = json.dumps(json_data['message'])
self.messenger.send_direct_message(message) self.messenger.send_direct_message(message)
elif str(json_data['event']) == 'unregister': elif str(json_data['event']) == 'unregister' and len(json_data)==1:
self.logger.info('Unregistering..') self.logger.info('Unregistering..')
self.execute_manager.set_unregister_credential_params(None, None)
unregister_message = self.message_manager.unregister_msg() unregister_message = self.message_manager.unregister_msg()
if unregister_message is not None: if unregister_message is not None:
self.messenger.send_direct_message(unregister_message) self.messenger.send_direct_message(unregister_message)
elif str(json_data['event']) == 'unregister' and len(json_data)==3:
self.logger.info('Unregistering..')
usernameForCheck = json_data['userName']
passwordForCheck = json_data['password']
## send user credential info to execution manager for hide user notify when remote unregister
self.execute_manager.set_unregister_credential_params(usernameForCheck,usernameForCheck)
self.logger.info('Unregistering by username+'+str(usernameForCheck))
unregister_message = self.message_manager.unregister_msg(usernameForCheck,passwordForCheck)
if unregister_message is not None:
self.messenger.send_direct_message(unregister_message)
elif str(json_data['event']) == 'load': elif str(json_data['event']) == 'load':
plugin_name = str(json_data['plugins']) plugin_name = str(json_data['plugins'])

View file

@ -32,11 +32,12 @@ class AhenkDbService(object):
'parameter_map BLOB', 'deleted INTEGER', 'plugin TEXT', 'cron_expr TEXT', 'parameter_map BLOB', 'deleted INTEGER', 'plugin TEXT', 'cron_expr TEXT',
'file_server TEXT']) 'file_server TEXT'])
self.check_and_create_table('policy', self.check_and_create_table('policy',
['id INTEGER PRIMARY KEY AUTOINCREMENT', 'type TEXT', 'version TEXT', 'name TEXT', ['id INTEGER PRIMARY KEY AUTOINCREMENT', 'policy_id INTEGER',
'execution_id TEXT','expiration_date TEXT']) 'type TEXT', 'version TEXT', 'name TEXT',
'execution_id TEXT', 'expiration_date TEXT', 'assign_date TEXT'])
self.check_and_create_table('profile', ['id INTEGER', 'create_date TEXT', 'label TEXT', 'description TEXT', self.check_and_create_table('profile', ['id INTEGER', 'create_date TEXT', 'label TEXT', 'description TEXT',
'overridable INTEGER', 'active TEXT', 'deleted TEXT', 'overridable INTEGER', 'active TEXT', 'deleted TEXT',
'profile_data TEXT', 'modify_date TEXT', 'plugin TEXT']) 'profile_data TEXT', 'modify_date TEXT', 'plugin TEXT', 'policy_id INTEGER'])
self.check_and_create_table('plugin', self.check_and_create_table('plugin',
['id INTEGER PRIMARY KEY AUTOINCREMENT', 'active TEXT', 'create_date TEXT', ['id INTEGER PRIMARY KEY AUTOINCREMENT', 'active TEXT', 'create_date TEXT',
'deleted TEXT', 'description TEXT', 'machine_oriented TEXT', 'modify_date TEXT', 'deleted TEXT', 'description TEXT', 'machine_oriented TEXT', 'modify_date TEXT',

View file

@ -1,9 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- 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 os
import json import json
import time import time
import datetime
from base.file.file_transfer_manager import FileTransferManager from base.file.file_transfer_manager import FileTransferManager
from base.model.enum.content_type import ContentType from base.model.enum.content_type import ContentType
from base.model.enum.message_code import MessageCode from base.model.enum.message_code import MessageCode
@ -17,6 +18,7 @@ from base.scheduler.custom.schedule_job import ScheduleTaskJob
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 easygui import * from easygui import *
@ -173,7 +175,10 @@ class ExecutionManager(object):
def execute_default_policy(self, username): def execute_default_policy(self, username):
self.logger.debug('Executing active policies for {0} user...'.format(username)) self.logger.debug('Executing active policies for {0} user...'.format(username))
self.task_manager.addPolicy(self.get_active_policies(username)) policy_list = self.get_active_policies(username)
for i in range(len(policy_list)):
self.task_manager.addPolicy(policy_list[i])
def update_scheduled_task(self, arg): def update_scheduled_task(self, arg):
self.logger.debug('Working on scheduled task ...') self.logger.debug('Working on scheduled task ...')
@ -215,106 +220,121 @@ class ExecutionManager(object):
def execute_policy(self, arg): def execute_policy(self, arg):
try: try:
self.logger.debug('Updating policies...') j = json.loads(str(arg))
policy = self.json_to_PolicyBean(json.loads(arg)) for i in range(len(j['executePolicyList'])):
self.policy_executed[policy.get_username()] = True policy = self.json_to_PolicyBean(json.loads(json.dumps(j['executePolicyList'][i])))
machine_uid = self.db_service.select_one_result('registration', 'jid', 'registered=1') self.logger.debug('Updating policies...')
ahenk_policy_ver = self.db_service.select_one_result('policy', 'version', 'type = \'A\'') # policy is deleted or unassigned on server
user_policy_version = self.db_service.select_one_result('policy', 'version', # delete on ahenk db
'type = \'U\' and name = \'' + policy.get_username() + '\'')
profile_columns = ['id', 'create_date', 'modify_date', 'label', 'description', 'overridable', 'active', if policy.get_is_deleted():
'deleted', 'profile_data', 'plugin'] existing_policy_id = self.db_service.select('policy', ['id'],
plugin_columns = ['active', 'create_date', 'deleted', 'description', 'machine_oriented', 'modify_date', 'type = \'U\' and name = \'' + policy.get_username() + '\'' +
'name', 'and policy_id = ' + str(policy.get_policy_id()))
'policy_plugin', 'user_oriented', 'version', 'task_plugin', 'x_based'] existing_profile_list = self.db_service.select('profile',
['id', 'plugin', 'policy_id'],
if policy.get_ahenk_policy_version() != ahenk_policy_ver: ' id=' + str(existing_policy_id[0][0]))
ahenk_policy_id = self.db_service.select_one_result('policy', 'id', 'type = \'A\'') for profile in existing_profile_list:
if ahenk_policy_id is not None: self.db_service.delete('plugin', 'id=' + str(profile[1]))
self.db_service.delete('profile', 'id=' + str(ahenk_policy_id)) self.db_service.delete('profile', 'id=' + str(existing_policy_id[0][0]))
self.db_service.delete('plugin', 'id=' + str(ahenk_policy_id)) self.db_service.delete('policy', 'type = \'U\' and name = \'' + policy.get_username() + '\'' +
self.db_service.update('policy', ['version', 'execution_id', 'expiration_date'], 'and policy_id = ' + str(policy.get_policy_id()))
[str(policy.get_ahenk_policy_version()), policy.agent_execution_id,
str(policy.agent_expiration_date)], 'type=\'A\'')
else: else:
self.db_service.update('policy', ['type', 'version', 'name', 'execution_id', 'expiration_date'], self.policy_executed[policy.get_username()] = True
['A', str(policy.get_ahenk_policy_version()), machine_uid, machine_uid = self.db_service.select_one_result('registration', 'jid', 'registered=1')
policy.get_agent_execution_id(), policy.agent_expiration_date]) user_policy_version = self.db_service.select_one_result('policy', 'version',
ahenk_policy_id = self.db_service.select_one_result('policy', 'id', 'type = \'A\'') 'type = \'U\' and name = \'' + policy.get_username() + '\'' +
'and policy_id = ' + str(policy.get_policy_id()))
for profile in policy.get_ahenk_profiles(): profile_columns = ['id', 'create_date', 'modify_date', 'label', 'description', 'overridable', 'active',
plugin = profile.get_plugin() 'deleted', 'profile_data', 'policy_id', 'plugin']
plugin_columns = ['active', 'create_date', 'deleted', 'description', 'machine_oriented', 'modify_date',
'name',
'policy_plugin', 'user_oriented', 'version', 'task_plugin', 'x_based']
plugin_args = [str(plugin.get_active()), str(plugin.get_create_date()), str(plugin.get_deleted()), # if user_policy_version is null that means this policy is not added to db
str(plugin.get_description()), str(plugin.get_machine_oriented()), # add this policy to db
str(plugin.get_modify_date()), str(plugin.get_name()), if user_policy_version is None:
str(plugin.get_policy_plugin()), self.db_service.update('policy', ['policy_id', 'type', 'version', 'name', 'execution_id', 'expiration_date', 'assign_date'],
str(plugin.get_user_oriented()), str(plugin.get_version()), [policy.get_policy_id(), 'U', str(policy.get_user_policy_version()),
str(plugin.get_task_plugin()), str(plugin.get_x_based())] policy.get_username(), policy.user_execution_id,
plugin_id = self.db_service.update('plugin', plugin_columns, plugin_args) str(policy.user_expiration_date), str(policy.get_assign_date())])
user_policy_id = self.db_service.select_one_result('policy', 'id',
'type = \'U\' and name=\'' + policy.get_username() + '\''
+ 'and policy_id = ' + str(policy.get_policy_id()))
for profile in policy.get_user_profiles():
plugin = profile.get_plugin()
profile_args = [str(ahenk_policy_id), str(profile.get_create_date()), plugin_args = [str(plugin.get_active()), str(plugin.get_create_date()), str(plugin.get_deleted()),
str(profile.get_modify_date()), str(plugin.get_description()), str(plugin.get_machine_oriented()),
str(profile.get_label()), str(profile.get_description()), str(plugin.get_modify_date()), str(plugin.get_name()),
str(profile.get_overridable()), str(profile.get_active()), str(plugin.get_policy_plugin()),
str(profile.get_deleted()), str(plugin.get_user_oriented()), str(plugin.get_version()),
str(profile.get_profile_data()), plugin_id] str(plugin.get_task_plugin()), str(plugin.get_x_based())]
self.db_service.update('profile', profile_columns, profile_args) plugin_id = self.db_service.update('plugin', plugin_columns, plugin_args)
elif ahenk_policy_ver: profile_args = [str(user_policy_id), str(profile.get_create_date()), str(profile.get_modify_date()),
self.logger.debug('Already there is ahenk policy. Command Execution Id is updating') str(profile.get_label()), str(profile.get_description()),
self.db_service.update('policy', ['execution_id'], [policy.get_agent_execution_id()], 'type = \'A\'') str(profile.get_overridable()), str(profile.get_active()),
else: str(profile.get_deleted()),
self.logger.debug('There is no any Ahenk policy.') str(profile.get_profile_data()), policy.get_policy_id(), plugin_id]
self.db_service.update('profile', profile_columns, profile_args)
if policy.get_user_policy_version() != user_policy_version: elif policy.get_user_policy_version() != user_policy_version:
user_policy_id = self.db_service.select_one_result('policy', 'id', # policy is in db but policy version is updated
'type = \'U\' and name=\'' + policy.get_username() + '\'') # delete profiles and plugins of that policcy and then insert new profiles and plugins
if user_policy_id is not None: existing_profile_list = self.db_service.select('profile',
# TODO remove profiles' plugins ['id', 'plugin', 'policy_id'],
self.db_service.delete('profile', 'id=' + str(user_policy_id)) ' policy_id=\'' + str(policy.get_policy_id()) + '\'')
self.db_service.delete('plugin', 'id=' + str(user_policy_id)) self.db_service.update('policy', ['version', 'execution_id', 'expiration_date', 'assign_date'],
self.db_service.update('policy', ['version', 'execution_id', 'expiration_date'], [str(policy.get_user_policy_version()), policy.user_execution_id,
[str(policy.get_user_policy_version()), policy.user_execution_id, str(policy.user_expiration_date), str(policy.assign_date)],
str(policy.user_expiration_date)], 'type=\'U\' and name=\'' + policy.get_username() + '\'' +
'type=\'U\' and name=\'' + policy.get_username() + '\'') ' and policy_id=\'' + str(policy.get_policy_id()) + '\'')
else: user_policy_id = self.db_service.select_one_result('policy', 'id',
self.db_service.update('policy', ['type', 'version', 'name', 'execution_id', 'expiration_date'], 'type = \'U\' and name=\'' + policy.get_username() + '\'' +
['U', str(policy.get_user_policy_version()), policy.get_username(), ' and policy_id=\'' + str(policy.get_policy_id()) + '\'')
policy.get_user_execution_id(), policy.user_expiration_date])
user_policy_id = self.db_service.select_one_result('policy', 'id',
'type = \'U\' and name=\'' + policy.get_username() + '\'')
for profile in policy.get_user_profiles(): # update all profiles
plugin = profile.get_plugin() for profile in existing_profile_list:
self.db_service.delete('profile', 'id=' + str(profile[0]))
self.db_service.delete('plugin', 'id=' + str(profile[1]))
plugin_args = [str(plugin.get_active()), str(plugin.get_create_date()), str(plugin.get_deleted()), # add new profile and policies
str(plugin.get_description()), str(plugin.get_machine_oriented()), for profile in policy.get_user_profiles():
str(plugin.get_modify_date()), str(plugin.get_name()), plugin = profile.get_plugin()
str(plugin.get_policy_plugin()),
str(plugin.get_user_oriented()), str(plugin.get_version()),
str(plugin.get_task_plugin()), str(plugin.get_x_based())]
plugin_id = self.db_service.update('plugin', plugin_columns, plugin_args)
profile_args = [str(user_policy_id), str(profile.get_create_date()), str(profile.get_modify_date()), plugin_args = [str(plugin.get_active()), str(plugin.get_create_date()), str(plugin.get_deleted()),
str(profile.get_label()), str(profile.get_description()), str(plugin.get_description()), str(plugin.get_machine_oriented()),
str(profile.get_overridable()), str(profile.get_active()), str(plugin.get_modify_date()), str(plugin.get_name()),
str(profile.get_deleted()), str(plugin.get_policy_plugin()),
str(profile.get_profile_data()), plugin_id] str(plugin.get_user_oriented()), str(plugin.get_version()),
self.db_service.update('profile', profile_columns, profile_args) str(plugin.get_task_plugin()), str(plugin.get_x_based())]
plugin_id = self.db_service.update('plugin', plugin_columns, plugin_args)
elif user_policy_version: profile_args = [str(user_policy_id), str(profile.get_create_date()), str(profile.get_modify_date()),
self.logger.debug('Already there is user policy. . Command Execution Id is updating') str(profile.get_label()), str(profile.get_description()),
self.db_service.update('policy', ['execution_id'], [policy.get_user_execution_id()], 'type = \'U\'') str(profile.get_overridable()), str(profile.get_active()),
else: str(profile.get_deleted()),
self.logger.debug('There is no any user policy') str(profile.get_profile_data()), policy.get_policy_id(), plugin_id]
self.db_service.update('profile', profile_columns, profile_args)
else:
existing_policy = self.db_service.select('policy', ['id', 'assign_date'],
'type = \'U\' and name = \'' + policy.get_username() + '\'' +
'and policy_id = ' + str(policy.get_policy_id()))
policy = self.get_active_policies(policy.get_username()) self.db_service.update('policy', ['assign_date'], [str(policy.get_assign_date())]
, 'type = \'U\' and name = \'' + policy.get_username() + '\'' +
'and policy_id = ' + str(policy.get_policy_id()))
policy_list = self.get_active_policies(j['username'])
# TODO check is null # TODO check is null
self.task_manager.addPolicy(policy) for i in range(len(policy_list)):
self.task_manager.addPolicy(policy_list[i])
except Exception as e: except Exception as e:
self.logger.error('A problem occurred while executing policy. Erroe Message: {0}:'.format(str(e))) self.logger.error('A problem occurred while executing policy. Error Message: {0}:'.format(str(e)))
def check_expiration(self, expiration): def check_expiration(self, expiration):
current_timestamp = int(time.time()) * 1000 current_timestamp = int(time.time()) * 1000
@ -329,8 +349,8 @@ class ExecutionManager(object):
try: try:
# TODO vt den gecerli son tarihi olani cek # TODO vt den gecerli son tarihi olani cek
user_policy = self.db_service.select('policy', ['id', 'version', 'name', 'expiration_date'], user_policy_list = self.db_service.select('policy', ['id', 'version', 'name', 'policy_id', 'expiration_date'],
' type=\'U\' and name=\'' + username + '\'') ' type=\'U\' and name=\'' + username + '\' order by assign_date asc')
ahenk_policy = self.db_service.select('policy', ['id', 'version', 'expiration_date'], ' type=\'A\' ') ahenk_policy = self.db_service.select('policy', ['id', 'version', 'expiration_date'], ' type=\'A\' ')
plugin_columns = ['id', 'active', 'create_date', 'deleted', 'description', 'machine_oriented', plugin_columns = ['id', 'active', 'create_date', 'deleted', 'description', 'machine_oriented',
@ -339,52 +359,34 @@ class ExecutionManager(object):
profile_columns = ['id', 'create_date', 'label', 'description', 'overridable', 'active', 'deleted', profile_columns = ['id', 'create_date', 'label', 'description', 'overridable', 'active', 'deleted',
'profile_data', 'modify_date', 'plugin'] 'profile_data', 'modify_date', 'plugin']
policy = PolicyBean(username=username)
if len(user_policy) > 0 and self.check_expiration(user_policy[0][3]): policy_list = []
user_policy_version = user_policy[0][0] if len(user_policy_list) > 0:
policy.set_user_policy_version(user_policy_version) for i in range(len(user_policy_list)):
policy = PolicyBean(username=username)
user_policy_version = user_policy_list[i][0]
policy_id = user_policy_list[i][3]
policy.set_user_policy_version(user_policy_version)
user_profiles = self.db_service.select('profile', profile_columns, user_profiles = self.db_service.select('profile', profile_columns,
' id=' + str(user_policy_version) + ' ') ' id=' + str(user_policy_version) + ' ')
arr_profiles = [] arr_profiles = []
if len(user_profiles) > 0: if len(user_profiles) > 0:
for profile in user_profiles: for profile in user_profiles:
plu = self.db_service.select('plugin', plugin_columns, ' id=\'' + profile[9] + '\'')[0] plu = self.db_service.select('plugin', plugin_columns, ' id=\'' + profile[9] + '\'')[0]
plugin = PluginBean(p_id=plu[0], active=plu[1], create_date=plu[2], deleted=plu[3], plugin = PluginBean(p_id=plu[0], active=plu[1], create_date=plu[2], deleted=plu[3],
description=plu[4], machine_oriented=plu[5], modify_date=plu[6], description=plu[4], machine_oriented=plu[5], modify_date=plu[6],
name=plu[7], name=plu[7],
policy_plugin=plu[8], user_oriented=plu[9], version=plu[10], policy_plugin=plu[8], user_oriented=plu[9], version=plu[10],
task_plugin=plu[11], x_based=plu[12]) task_plugin=plu[11], x_based=plu[12])
arr_profiles.append( arr_profiles.append(
ProfileBean(profile[0], profile[1], profile[2], profile[3], profile[4], profile[5], ProfileBean(profile[0], profile[1], profile[2], profile[3], profile[4], profile[5],
profile[6], profile[6],
profile[7], profile[8], plugin, policy.get_username())) profile[7], profile[8], user_policy_list[i][3], plugin, policy.get_username()))
policy.set_user_profiles(arr_profiles) policy.set_user_profiles(arr_profiles)
policy_list.append(policy)
if len(ahenk_policy) > 0 and self.check_expiration(ahenk_policy[0][2]): return policy_list
ahenk_policy_version = ahenk_policy[0][0]
policy.set_ahenk_policy_version(ahenk_policy_version)
ahenk_profiles = self.db_service.select('profile', profile_columns,
' id=' + str(ahenk_policy_version) + ' ')
arr_profiles = []
if len(ahenk_profiles) > 0:
for profile in ahenk_profiles:
plu = self.db_service.select('plugin', plugin_columns, ' id=\'' + profile[9] + '\'')[0]
plugin = PluginBean(p_id=plu[0], active=plu[1], create_date=plu[2], deleted=plu[3],
description=plu[4], machine_oriented=plu[5], modify_date=plu[6],
name=plu[7],
policy_plugin=plu[8], user_oriented=plu[9], version=plu[10],
task_plugin=plu[11], x_based=plu[12])
arr_profiles.append(
ProfileBean(profile[0], profile[1], profile[2], profile[3], profile[4], profile[5],
profile[6],
profile[7], profile[8], plugin, policy.get_username()))
policy.set_ahenk_profiles(arr_profiles)
return policy
except Exception as e: except Exception as e:
self.logger.error('A problem occurred while getting active policies. Error Message : {0}'.format(str(e))) self.logger.error('A problem occurred while getting active policies. Error Message : {0}'.format(str(e)))
@ -403,18 +405,28 @@ class ExecutionManager(object):
def unregister(self, msg): def unregister(self, msg):
j = json.loads(msg) j = json.loads(msg)
status = str(j['status']).lower() status = str(j['status']).lower()
# user_name = self.db_service.select_one_result('session', 'username', " 1=1 order by id desc ")
user_name = self.db_service.select_one_result('session', 'username', " 1=1 order by id desc ") # display = self.db_service.select_one_result('session', 'display', " 1=1 order by id desc ")
display = self.db_service.select_one_result('session', 'display', " 1=1 order by id desc ")
if 'not_authorized' == str(status): if 'not_authorized' == str(status):
self.logger.info('Registration is failed. User not authorized') self.logger.info('UnRegistration is failed. User not authorized')
Util.show_message(user_name,display,'Ahenk Lider MYS sisteminden çıkarmak için yetkili kullanıcı haklarına sahip olmanız gerekmektedir.', if self.unregister_user_name is None:
'Kullanıcı Yetkilendirme Hatası') user_name = os.getlogin()
display = Util.get_username_display()
Util.show_message(user_name, display,
'Ahenk Lider MYS sisteminden çıkarmak için yetkili kullanıcı haklarına sahip olmanız gerekmektedir.',
'Kullanıcı Yetkilendirme Hatası')
else: else:
Util.show_message(user_name, display, "Ahenk Lider MYS sisteminden çıkarılmıştır.", "") if self.unregister_user_name is None:
if Util.show_message(user_name, display, "Değişikliklerin etkili olması için sistem yeniden başlatılacaktır. Lütfen bekleyiniz...", "") : user_name = os.getlogin()
registration= Scope.get_instance().get_registration() display = Util.get_username_display()
Util.show_message(user_name, display, "Ahenk Lider MYS sisteminden çıkarılmıştır.", "")
if Util.show_message(user_name, display,
"Değişikliklerin etkili olması için sistem yeniden başlatılacaktır. Lütfen bekleyiniz...",
""):
registration = Scope.get_instance().get_registration()
registration.purge_and_unregister()
else:
registration = Scope.get_instance().get_registration()
registration.purge_and_unregister() registration.purge_and_unregister()
@ -494,6 +506,7 @@ class ExecutionManager(object):
username = json_data['username'] username = json_data['username']
ahenk_prof_json_arr = json_data['agentPolicyProfiles'] ahenk_prof_json_arr = json_data['agentPolicyProfiles']
user_prof_json_arr = json_data['userPolicyProfiles'] user_prof_json_arr = json_data['userPolicyProfiles']
policy_id = json_data['policyID']
ahenk_prof_arr = [] ahenk_prof_arr = []
user_prof_arr = [] user_prof_arr = []
@ -508,7 +521,7 @@ class ExecutionManager(object):
task_plugin=plu['taskPlugin'], x_based=plu['xBased']) task_plugin=plu['taskPlugin'], x_based=plu['xBased'])
ahenk_prof_arr.append( ahenk_prof_arr.append(
ProfileBean(prof['id'], prof['createDate'], prof['label'], prof['description'], prof['overridable'], ProfileBean(prof['id'], prof['createDate'], prof['label'], prof['description'], prof['overridable'],
prof['active'], prof['deleted'], json.dumps(prof['profileData']), prof['modifyDate'], prof['active'], prof['deleted'], json.dumps(prof['profileData']), prof['modifyDate'], policy_id,
plugin, username)) plugin, username))
if user_prof_json_arr is not None: if user_prof_json_arr is not None:
@ -522,16 +535,19 @@ class ExecutionManager(object):
task_plugin=plu['taskPlugin'], x_based=plu['xBased']) task_plugin=plu['taskPlugin'], x_based=plu['xBased'])
user_prof_arr.append( user_prof_arr.append(
ProfileBean(prof['id'], prof['createDate'], prof['label'], prof['description'], prof['overridable'], ProfileBean(prof['id'], prof['createDate'], prof['label'], prof['description'], prof['overridable'],
prof['active'], prof['deleted'], json.dumps(prof['profileData']), prof['modifyDate'], prof['active'], prof['deleted'], json.dumps(prof['profileData']), prof['modifyDate'], policy_id,
plugin, username)) plugin, username))
return PolicyBean(ahenk_policy_version=json_data['agentPolicyVersion'], return PolicyBean(policy_id=json_data['policyID'],
ahenk_policy_version=json_data['agentPolicyVersion'],
user_policy_version=json_data['userPolicyVersion'], ahenk_profiles=ahenk_prof_arr, user_policy_version=json_data['userPolicyVersion'], ahenk_profiles=ahenk_prof_arr,
user_profiles=user_prof_arr, timestamp=json_data['timestamp'], username=json_data['username'], user_profiles=user_prof_arr, timestamp=json_data['timestamp'], username=json_data['username'],
agent_execution_id=json_data['agentCommandExecutionId'], agent_execution_id=json_data['agentCommandExecutionId'],
user_execution_id=json_data['userCommandExecutionId'], user_execution_id=json_data['userCommandExecutionId'],
agent_expiration_date=json_data['agentPolicyExpirationDate'], agent_expiration_date=json_data['agentPolicyExpirationDate'],
user_expiration_date=json_data['userPolicyExpirationDate']) user_expiration_date=json_data['userPolicyExpirationDate'],
is_deleted=json_data['isDeleted'],
assign_date=json_data['assignDate'])
def login_response(self, msg): def login_response(self, msg):
jData = json.loads(msg) jData = json.loads(msg)
@ -552,3 +568,7 @@ class ExecutionManager(object):
Util.delete_file(ahenk_policy_file) Util.delete_file(ahenk_policy_file)
Util.create_file(ahenk_policy_file) Util.create_file(ahenk_policy_file)
Util.write_file(ahenk_policy_file, content) Util.write_file(ahenk_policy_file, content)
def set_unregister_credential_params(self, user_name=None, passwd=None):
self.unregister_user_name=user_name
self.unregister_passwd=passwd

View file

@ -105,18 +105,19 @@ class AnonymousMessenger(ClientXMPP):
if 'not_authorized' == str(status): if 'not_authorized' == str(status):
self.logger.info('Registration is failed. User not authorized') self.logger.info('Registration is failed. User not authorized')
Util.show_message(os.getlogin(), ':0','Ahenk Lider MYS sistemine alınamadı !! Sadece yetkili kullanıcılar kayıt yapabilir.', 'Kullanıcı Yetkilendirme Hatası') if self.registration.showUserNotify == True:
Util.show_message(os.getlogin(), ':0','Ahenk Lider MYS sistemine alınamadı !! Sadece yetkili kullanıcılar kayıt yapabilir.', 'Kullanıcı Yetkilendirme Hatası')
self.logger.debug('Disconnecting...') self.logger.debug('Disconnecting...')
self.disconnect() self.disconnect()
elif 'already_exists' == str(status) or 'registered' == str(status) or 'registered_without_ldap' == str(status): elif 'already_exists' == str(status) or 'registered' == str(status) or 'registered_without_ldap' == str(status):
try: try:
self.logger.info('Registred from server. Registration process starting.') self.logger.info('Registred from server. Registration process starting.')
self.event_manager.fireEvent('REGISTRATION_SUCCESS', j) self.event_manager.fireEvent('REGISTRATION_SUCCESS', j)
msg = str(self.host) + " Etki Alanına hoş geldiniz." if self.registration.showUserNotify == True:
Util.show_message(os.getlogin(), ':0' ,msg, "UYARI") msg = str(self.host) + " Etki Alanına hoş geldiniz."
msg = "Değişikliklerin etkili olması için sistem yeniden başlayacaktır. Sistem yeniden başlatılıyor...." Util.show_message(os.getlogin(), ':0' ,msg, "UYARI")
Util.show_message(os.getlogin(), ':0',msg, "UYARI") msg = "Değişikliklerin etkili olması için sistem yeniden başlayacaktır. Sistem yeniden başlatılıyor...."
Util.show_message(os.getlogin(), ':0',msg, "UYARI")
time.sleep(3) time.sleep(3)
self.logger.info('Disconnecting...') self.logger.info('Disconnecting...')
self.disconnect() self.disconnect()
@ -124,18 +125,17 @@ class AnonymousMessenger(ClientXMPP):
#System.Process.kill_by_pid(int(System.Ahenk.get_pid_number())) #System.Process.kill_by_pid(int(System.Ahenk.get_pid_number()))
#sys.exit(2) #sys.exit(2)
Util.shutdown(); Util.shutdown();
except Exception as e: except Exception as e:
self.logger.error('Error Message: {0}.'.format(str(e))) self.logger.error('Error Message: {0}.'.format(str(e)))
Util.show_message(os.getlogin(), ':0',str(e)) if self.registration.showUserNotify == True:
Util.show_message(os.getlogin(), ':0',str(e))
self.logger.debug('Disconnecting...') self.logger.debug('Disconnecting...')
self.disconnect() self.disconnect()
elif 'registration_error' == str(status): elif 'registration_error' == str(status):
self.logger.info('Registration is failed. New registration request will send') self.logger.info('Registration is failed. New registration request will send')
#self.event_manager.fireEvent('REGISTRATION_ERROR', str(j)) #self.event_manager.fireEvent('REGISTRATION_ERROR', str(j))
Util.show_message(os.getlogin(), ':0','Ahenk Lider MYS sistemine alınamadı !! Kayıt esnasında hata oluştu. Lütfen sistem yöneticinize başvurunuz.', if self.registration.showUserNotify == True:
Util.show_message(os.getlogin(), ':0','Ahenk Lider MYS sistemine alınamadı !! Kayıt esnasında hata oluştu. Lütfen sistem yöneticinize başvurunuz.',
'Sistem Hatası') 'Sistem Hatası')
self.logger.debug('Disconnecting...') self.logger.debug('Disconnecting...')
self.disconnect() self.disconnect()

View file

@ -105,6 +105,15 @@ class Messaging(object):
'type = \'U\' and name = \'' + username + '\'') 'type = \'U\' and name = \'' + username + '\'')
machine_policy_number = self.db_service.select_one_result('policy', 'version', 'type = \'A\'') machine_policy_number = self.db_service.select_one_result('policy', 'version', 'type = \'A\'')
user_policy_list = self.db_service.select('policy', ['id', 'version', 'name', 'policy_id', 'assign_date'],
' type=\'U\' and name=\'' + username + '\'')
# to add policy_id and policy_version
user_policy_hash_list = dict()
if len(user_policy_list) > 0:
for i in range(len(user_policy_list)):
user_policy_hash_list[str(user_policy_list[i][3])] = [user_policy_list[i][1], user_policy_list[i][4]]
data['policyList'] = user_policy_hash_list
data['userPolicyVersion'] = user_policy_number data['userPolicyVersion'] = user_policy_number
data['agentPolicyVersion'] = machine_policy_number data['agentPolicyVersion'] = machine_policy_number
@ -155,30 +164,29 @@ class Messaging(object):
self.logger.debug('LDAP Registration message was created') self.logger.debug('LDAP Registration message was created')
return json_data return json_data
def unregister_msg(self): def unregister_msg(self,usernameForCheck,passwordForCheck):
user_name = self.db_service.select_one_result('session', 'username')
display = self.db_service.select_one_result('session', 'display')
self.logger.debug('User : ' + str(user_name))
pout = Util.show_unregistration_message(user_name,display,
'Makineyi etki alanından çıkarmak için zorunlu alanları giriniz. Lütfen DEVAM EDEN İŞLEMLERİNİZİ sonlandırdığınıza emin olunuz !',
'ETKI ALANINDAN ÇIKARMA')
self.logger.debug('pout : ' + str(pout))
field_values = pout.split(' ')
user_registration_info = list(field_values)
data = dict() data = dict()
data['type'] = 'UNREGISTER' data['type'] = 'UNREGISTER'
data['from'] = str(self.conf_manager.get('CONNECTION', 'uid')) data['from'] = str(self.conf_manager.get('CONNECTION', 'uid'))
data['password'] = str(self.conf_manager.get('CONNECTION', 'password')) data['password'] = str(self.conf_manager.get('CONNECTION', 'password'))
# unregistration from commandline..
data['userName'] = user_registration_info[0]; if(usernameForCheck==None and passwordForCheck==None):
data['userPassword'] = user_registration_info[1]; #user_name = self.db_service.select_one_result('session', 'username')
#display = self.db_service.select_one_result('session', 'display')
user_name = os.getlogin()
display = Util.get_username_display()
self.logger.debug('User : ' + str(user_name))
pout = Util.show_unregistration_message(user_name,display,
'Makineyi etki alanından çıkarmak için zorunlu alanları giriniz. Lütfen DEVAM EDEN İŞLEMLERİNİZİ sonlandırdığınıza emin olunuz !',
'ETKI ALANINDAN ÇIKARMA')
self.logger.debug('pout : ' + str(pout))
field_values = pout.split(' ')
user_registration_info = list(field_values)
data['userName'] = user_registration_info[0];
data['userPassword'] = user_registration_info[1];
else:
data['userName'] = usernameForCheck;
data['userPassword'] = passwordForCheck;
#data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses')) #data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
#data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses')) #data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))

View file

@ -116,7 +116,6 @@ class Messenger(ClientXMPP):
self.logger.info("---------->Received message: {}".format(str(parameter_map))) self.logger.info("---------->Received message: {}".format(str(parameter_map)))
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']))
self.logger.debug('Fired event is: {0}'.format(message_type)) self.logger.debug('Fired event is: {0}'.format(message_type))
except Exception as e: except Exception as e:

View file

@ -6,9 +6,10 @@
class PolicyBean(object): class PolicyBean(object):
"""docstring for PolicyBean""" """docstring for PolicyBean"""
def __init__(self, ahenk_policy_version=None, user_policy_version=None, ahenk_profiles=None, user_profiles=None, def __init__(self, policy_id=None, ahenk_policy_version=None, user_policy_version=None, ahenk_profiles=None, user_profiles=None,
timestamp=None, username=None, agent_execution_id=None, user_execution_id=None, timestamp=None, username=None, agent_execution_id=None, user_execution_id=None,
agent_expiration_date=None, user_expiration_date=None): agent_expiration_date=None, user_expiration_date=None, is_deleted=None, assign_date=None):
self.policy_id = policy_id
self.ahenk_policy_version = ahenk_policy_version self.ahenk_policy_version = ahenk_policy_version
self.user_policy_version = user_policy_version self.user_policy_version = user_policy_version
self.ahenk_profiles = ahenk_profiles self.ahenk_profiles = ahenk_profiles
@ -19,6 +20,14 @@ class PolicyBean(object):
self.user_execution_id = user_execution_id self.user_execution_id = user_execution_id
self.agent_expiration_date = agent_expiration_date self.agent_expiration_date = agent_expiration_date
self.user_expiration_date = user_expiration_date self.user_expiration_date = user_expiration_date
self.is_deleted = is_deleted
self.assign_date = assign_date
def get_policy_id(self):
return self.policy_id
def set_policy_id(self, policy_id):
self.policy_id = policy_id
def get_ahenk_policy_version(self): def get_ahenk_policy_version(self):
return self.ahenk_policy_version return self.ahenk_policy_version
@ -67,3 +76,15 @@ class PolicyBean(object):
def get_user_execution_id(self): def get_user_execution_id(self):
return self.user_execution_id return self.user_execution_id
def set_is_deleted(self, is_deleted):
self.is_deleted = is_deleted
def get_is_deleted(self):
return self.is_deleted
def set_assign_date(self, assign_date):
self.assign_date = assign_date
def get_assign_date(self):
return self.assign_date

View file

@ -8,8 +8,7 @@ from base.model.plugin_bean import PluginBean
class ProfileBean(object): class ProfileBean(object):
"""docstring for Profile""" """docstring for Profile"""
def __init__(self, p_id=None, create_date=None, label=None, description=None, overridable=None, active=None, deleted=None, profile_data=None, modify_date=None, policy_id=None, plugin=None, username=None):
def __init__(self, p_id=None, create_date=None, label=None, description=None, overridable=None, active=None, deleted=None, profile_data=None, modify_date=None, plugin=None, username=None):
self.id = p_id self.id = p_id
self.create_date = create_date self.create_date = create_date
self.modify_date = modify_date self.modify_date = modify_date
@ -19,6 +18,7 @@ class ProfileBean(object):
self.active = active self.active = active
self.deleted = deleted self.deleted = deleted
self.profile_data = profile_data self.profile_data = profile_data
self.policy_id = policy_id
self.plugin = plugin self.plugin = plugin
self.username = username self.username = username
@ -47,7 +47,7 @@ class ProfileBean(object):
self.label = label self.label = label
def get_description(self): def get_description(self):
return self.modify_date return self.description
def set_description(self, description): def set_description(self, description):
self.description = description self.description = description
@ -76,6 +76,12 @@ class ProfileBean(object):
def set_profile_data(self, profile_data): def set_profile_data(self, profile_data):
self.profile_data = profile_data self.profile_data = profile_data
def get_policy_id(self):
return self.policy_id
def set_policy_id(self, policy_id):
self.policy_id = policy_id
def get_plugin(self): def get_plugin(self):
return self.plugin return self.plugin

View file

@ -202,7 +202,7 @@ class PluginManager(object):
for usr_profile in user_profiles: for usr_profile in user_profiles:
if usr_profile.plugin.name == agent_profile.plugin.name: if usr_profile.plugin.name == agent_profile.plugin.name:
same_plugin_profile = usr_profile same_plugin_profile = usr_profile
policy.get_user_policy_version()
if same_plugin_profile is not None: if same_plugin_profile is not None:
if agent_profile.overridable.lower() == 'true': if agent_profile.overridable.lower() == 'true':
self.logger.debug( self.logger.debug(

View file

@ -21,5 +21,5 @@ krb5_store_password_if_offline = True
default_shell = /bin/bash default_shell = /bin/bash
ldap_id_mapping = True ldap_id_mapping = True
use_fully_qualified_names = False use_fully_qualified_names = False
fallback_homedir = /home/%u@%d fallback_homedir = /home/%u
access_provider = ad access_provider = ad

View file

@ -74,8 +74,8 @@ class ExecuteCancelSSSDAdAuthentication:
file_common_session = open(common_session_conf_path, 'r') file_common_session = open(common_session_conf_path, 'r')
file_data = file_common_session.read() file_data = file_common_session.read()
if "session optional pam_mkhomedir.so skel=/etc/skel umask=077" in file_data: if "session optional pam_mkhomedir.so skel=/etc/skel umask=077" in file_data:
file_data = file_data.replace("session optional pam_mkhomedir.so skel=/etc/skel umask=077", " ") file_data = file_data.replace("session optional pam_mkhomedir.so skel=/etc/skel umask=077", " ")
self.logger.info("common-session is configured") self.logger.info("common-session is configured")
else: else:
self.logger.error("common session is not configured") self.logger.error("common session is not configured")
@ -108,14 +108,6 @@ class ExecuteCancelSSSDAdAuthentication:
else: else:
self.logger.error("ad_info file not found") self.logger.error("ad_info file not found")
# Configure lightdm.service
pardus_xfce_path = "/usr/share/lightdm/lightdm.conf.d/99-pardus-xfce.conf"
if self.util.is_exist(pardus_xfce_path):
self.logger.info("99-pardus-xfce.conf exists. Deleting file.")
self.util.delete_file(pardus_xfce_path)
self.util.execute("systemctl restart nscd.service")
else:
self.logger.info("99-pardus-xfce.conf not found")
self.logger.info("AD Login iptal etme işlemi başarı ile sağlandı.") self.logger.info("AD Login iptal etme işlemi başarı ile sağlandı.")
return True return True

View file

@ -71,8 +71,8 @@ class ExecuteCancelSSSDAuthentication:
file_common_session = open(common_session_conf_path, 'r') file_common_session = open(common_session_conf_path, 'r')
file_data = file_common_session.read() file_data = file_common_session.read()
if "session optional pam_mkhomedir.so skel=/etc/skel umask=077" in file_data: if "session optional pam_mkhomedir.so skel=/etc/skel umask=077" in file_data:
file_data = file_data.replace("session optional pam_mkhomedir.so skel=/etc/skel umask=077", "") file_data = file_data.replace("session optional pam_mkhomedir.so skel=/etc/skel umask=077", "")
self.logger.info("common-session is configured") self.logger.info("common-session is configured")
file_common_session.close() file_common_session.close()

View file

@ -14,7 +14,7 @@ class ExecuteSSSDAdAuthentication:
def authenticate(self, domain_name, host_name, ip_address, password, ad_username): def authenticate(self, domain_name, host_name, ip_address, password, ad_username):
try: try:
# Create and Configure ad_info file # Create and Configure ad_info file
(result_code, p_out, p_err) = self.util.create_file("/etc/ahenk/ad_info") (result_code, p_out, p_err) = self.util.execute("touch /etc/ahenk/ad_info")
if (result_code == 0): if (result_code == 0):
self.logger.info("AD INFO başarılı bir şekilde oluşturuldu") self.logger.info("AD INFO başarılı bir şekilde oluşturuldu")
# Configure ad_info for deregisteration info # Configure ad_info for deregisteration info

View file

@ -15,7 +15,7 @@ class ExecuteSSSDAuthentication:
def authenticate(self, server_address, dn, admin_dn, admin_password): def authenticate(self, server_address, dn, admin_dn, admin_password):
try: try:
ldap_pwdlockout_dn = "cn=DefaultPolicy,ou=PasswordPolicies" + "," + dn ldap_pwdlockout_dn = "ou=PasswordPolicies" + "," + dn
# pattern for clearing file data from spaces, tabs and newlines # pattern for clearing file data from spaces, tabs and newlines
pattern = re.compile(r'\s+') pattern = re.compile(r'\s+')
@ -48,7 +48,7 @@ class ExecuteSSSDAuthentication:
file_data = file_data.replace("###ldap_search_base###", "ldap_search_base = " + dn) file_data = file_data.replace("###ldap_search_base###", "ldap_search_base = " + dn)
file_data = file_data.replace("###ldap_user_search_base###", "ldap_user_search_base = " + dn) file_data = file_data.replace("###ldap_user_search_base###", "ldap_user_search_base = " + dn)
file_data = file_data.replace("###ldap_group_search_base###", "ldap_group_search_base = " + dn) file_data = file_data.replace("###ldap_group_search_base###", "ldap_group_search_base = " + dn)
file_data = file_data.replace("###ldap_sudo_search_base###", "ldap_sudo_search_base = ou=Roles," + dn) file_data = file_data.replace("###ldap_sudo_search_base###", "ldap_sudo_search_base = ou=Role,ou=Groups," + dn)
file_sssd.close() file_sssd.close()
file_sssd = open(sssd_config_file_path, 'w') file_sssd = open(sssd_config_file_path, 'w')
@ -58,16 +58,23 @@ class ExecuteSSSDAuthentication:
# 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 -y")
if result_code != 0: if result_code != 0:
self.logger.error("SSSD packages couldn't be downloaded.") self.logger.error("SSSD packages couldn't be downloaded.")
return False return False
(result_code, p_out, p_err) = self.util.execute("chmod 600 {}".format(sssd_config_file_path))
if (result_code == 0):
self.logger.info("Chmod komutu başarılı bir şekilde çalıştırıldı")
else:
self.logger.error("Chmod komutu başarısız : " + str(p_err))
# configure common-session for creating home directories for ldap users # configure common-session for creating home directories for ldap users
file_common_session = open(common_session_conf_path, 'r') file_common_session = open(common_session_conf_path, 'r')
file_data = file_common_session.read() file_data = file_common_session.read()
if "session optional pam_mkhomedir.so skel=/etc/skel umask=077" not in file_data : if "session optional pam_mkhomedir.so skel=/etc/skel umask=077" not in file_data :
file_data = file_data + "\n" + "session optional pam_mkhomedir.so skel=/etc/skel umask=077" file_data = file_data + "\n" + "session optional pam_mkhomedir.so skel=/etc/skel umask=077"
self.logger.info("common-session is configured") self.logger.info("common-session is configured")
file_common_session.close() file_common_session.close()

View file

@ -50,7 +50,7 @@ class Registration:
else: else:
self.register(True) self.register(True)
def registration_request(self, hostname,username,password): def registration_request(self, hostname,username,password,directoryserver):
self.logger.debug('Requesting registration') self.logger.debug('Requesting registration')
# SetupTimer.start(Timer(System.Ahenk.registration_timeout(), timeout_function=self.registration_timeout,checker_func=self.is_registered, kwargs=None)) # SetupTimer.start(Timer(System.Ahenk.registration_timeout(), timeout_function=self.registration_timeout,checker_func=self.is_registered, kwargs=None))
@ -60,9 +60,11 @@ class Registration:
self.host = hostname self.host = hostname
self.user_name = username self.user_name = username
self.user_password= password self.user_password= password
self.directory_server = directoryserver
self.showUserNotify = False;
if(username is None and password is None and self.host is None ): if(username is None and password is None and self.host is None ):
self.showUserNotify = True;
self.host = self.conf_manager.get("CONNECTION", "host") self.host = self.conf_manager.get("CONNECTION", "host")
user_name= os.getlogin() user_name= os.getlogin()
@ -138,6 +140,28 @@ class Registration:
file_lightdm.close() file_lightdm.close()
self.logger.info("lightdm.conf has been configured.") self.logger.info("lightdm.conf has been configured.")
if self.desktop_env == "gnome":
pardus_gnome_path = "/etc/gdm3/greeter.dconf-defaults"
if not self.util.is_exist(pardus_gnome_path):
self.logger.info("Gnome conf doesn't exist")
else:
reading_file = open(pardus_gnome_path, "r")
new_file_content = ""
for line in reading_file:
stripped_line = line.strip()
new_line = stripped_line.replace("# disable-user-list=true", "disable-user-list=true")
new_file_content += new_line + "\n"
reading_file.close()
writing_file = open(pardus_gnome_path, "w")
writing_file.write(new_file_content)
writing_file.close()
self.logger.info("gdm.conf has been configured.")
# LDAP registration # LDAP registration
if self.directory_server == "LDAP": if self.directory_server == "LDAP":
self.install_and_config_ldap(reg_reply) self.install_and_config_ldap(reg_reply)
@ -343,6 +367,26 @@ class Registration:
self.logger.info("99-pardus-xfce.conf exists. Deleting file.") self.logger.info("99-pardus-xfce.conf exists. Deleting file.")
self.util.delete_file(pardus_xfce_path) self.util.delete_file(pardus_xfce_path)
if self.util.get_desktop_env() == "gnome":
pardus_gnome_path = "/etc/gdm3/greeter.dconf-defaults"
if not self.util.is_exist(pardus_gnome_path):
self.logger.info("Gnome conf doesn't exist")
else:
reading_file = open(pardus_gnome_path, "r")
new_file_content = ""
for line in reading_file:
stripped_line = line.strip()
new_line = stripped_line.replace("disable-user-list=true", "# disable-user-list=true")
new_file_content += new_line + "\n"
reading_file.close()
writing_file = open(pardus_gnome_path, "w")
writing_file.write(new_file_content)
writing_file.close()
self.logger.info("gdm.conf has been configured.")
Util.shutdown() Util.shutdown()
except Exception as e: except Exception as e:
self.logger.error("Error while running purge_and_unregister process.. Error Message " + str(e)) self.logger.error("Error while running purge_and_unregister process.. Error Message " + str(e))
@ -448,6 +492,7 @@ class Registration:
config.set('CONNECTION', 'uid', '') config.set('CONNECTION', 'uid', '')
config.set('CONNECTION', 'password', '') config.set('CONNECTION', 'password', '')
config.set('CONNECTION', 'host', '')
config.set('MACHINE', 'user_disabled', 'false') config.set('MACHINE', 'user_disabled', 'false')
with open(System.Ahenk.config_path(), 'w') as file: with open(System.Ahenk.config_path(), 'w') as file:

View file

@ -462,3 +462,5 @@ class Util:
return desktop_env return desktop_env

View file

@ -23,21 +23,30 @@ class GetFileContent(AbstractPlugin):
if self.is_exist(file_path): if self.is_exist(file_path):
self.logger.info("File exists: " + file_path) self.logger.info("File exists: " + file_path)
is_file_exists = True is_file_exists = True
file_content = self.read_file(file_path) # if the file size is less than 5K
self.context.create_response(code=self.message_code.TASK_PROCESSED.value, file_size = self.get_size(file_path) / 1024
message='Dosya içeriği başarıyla alındı..', if file_size <= 5:
data=json.dumps({'file_exists': is_file_exists, 'file_content': file_content}), file_content = self.read_file(file_path)
content_type=self.get_content_type().APPLICATION_JSON.value) self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
message='Dosya içeriği başarıyla alındı..',
data=json.dumps({'file_exists': is_file_exists, 'file_content': file_content}),
content_type=self.get_content_type().APPLICATION_JSON.value)
else:
self.logger.error("File size is too large. File Size: {0}K ".format(str(file_size)))
self.context.create_response(code=self.message_code.TASK_ERROR.value,
message='Dosya içeriği getirilemedi. Dosya boyutu çok büyük.',
content_type=self.get_content_type().APPLICATION_JSON.value)
else: else:
self.context.create_response(code=self.message_code.TASK_PROCESSED.value, self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
message='Dosya bulunamadı..', message='Dosya bulunamadı..',
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,
message='Dosya içeriği alınırken hata oluştu: {0}'.format(str(e))) message='Dosya içeriği alınırken hata oluştu: {0}'.format(str(e)))
def handle_task(task, context): def handle_task(task, context):
plugin = GetFileContent(task, context) plugin = GetFileContent(task, context)
plugin.handle_task() plugin.handle_task()

View file

@ -30,7 +30,6 @@ 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']
disabled_local_user = self.data['disableLocalUser']
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)
if execution_result is False: if execution_result is False:
@ -39,21 +38,23 @@ class ADLogin(AbstractPlugin):
content_type=self.get_content_type().APPLICATION_JSON.value) content_type=self.get_content_type().APPLICATION_JSON.value)
else: else:
# if get disabled_local_user TRUE set user_disabled in ahenk.conf. disabled local users then client reboot # if get disabled_local_user TRUE set user_disabled in ahenk.conf. disabled local users then client reboot
self.config.read(self.ahenk_conf_path) if self.has_attr_json(self.data, 'disableLocalUser') is True:
if disabled_local_user is True: disabled_local_user = self.data['disableLocalUser']
# self.registration.disable_local_users() self.config.read(self.ahenk_conf_path)
config = configparser.ConfigParser() if disabled_local_user is True:
config.read(self.ahenk_conf_path) # self.registration.disable_local_users()
config.set('MACHINE', 'user_disabled', 'true') config = configparser.ConfigParser()
config.read(self.ahenk_conf_path)
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,

View file

@ -29,7 +29,14 @@ class LDAPLogin(AbstractPlugin):
# version = self.data['version'] # version = self.data['version']
admin_dn = self.data['admin-dn'] admin_dn = self.data['admin-dn']
admin_password = self.data['admin-password'] admin_password = self.data['admin-password']
disabled_local_user = self.data['disableLocalUser']
if admin_dn is None:
admin_dn = self.Ahenk.dn()
if admin_password is None:
self.config.read(self.ahenk_conf_path)
if self.config.has_section('CONNECTION'):
admin_password = self.config.get("CONNECTION", "password")
execution_result = self.sssd_authentication.authenticate(server_address, dn, admin_dn, admin_password) execution_result = self.sssd_authentication.authenticate(server_address, dn, admin_dn, admin_password)
if execution_result is False: if execution_result is False:
@ -38,21 +45,23 @@ class LDAPLogin(AbstractPlugin):
content_type=self.get_content_type().APPLICATION_JSON.value) content_type=self.get_content_type().APPLICATION_JSON.value)
else: else:
# if get disabled_local_user TRUE set user_disabled in ahenk.conf. disabled local users then client reboot # if get disabled_local_user TRUE set user_disabled in ahenk.conf. disabled local users then client reboot
self.config.read(self.ahenk_conf_path) if self.has_attr_json(self.data, 'disableLocalUser') is True:
if disabled_local_user is True: disabled_local_user = self.data['disableLocalUser']
# self.registration.disable_local_users() self.config.read(self.ahenk_conf_path)
config = configparser.ConfigParser() if disabled_local_user is True:
config.read(self.ahenk_conf_path) # self.registration.disable_local_users()
config.set('MACHINE', 'user_disabled', 'true') config = configparser.ConfigParser()
config.read(self.ahenk_conf_path)
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,

View file

@ -0,0 +1,31 @@
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author:Tuncay ÇOLAK <tuncay.colak@tubitak.gov.tr>
## restart agents
from base.plugin.abstract_plugin import AbstractPlugin
class Restart(AbstractPlugin):
def __init__(self, task, context):
super(AbstractPlugin, self).__init__()
self.task = task
self.context = context
self.logger = self.get_logger()
self.message_code = self.get_message_code()
self.command_restart = 'reboot'
self.logger.debug('Parameters were initialized.')
def handle_task(self):
try:
result_code, p_out, p_err = self.execute(self.command_restart)
self.logger.info("restart agent success")
self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
message='İstemci yeniden başarıyla başlatıldı. .')
except Exception as e:
self.logger.error('A problem occured while handling Login-Manager task: {0}'.format(str(e)))
self.context.create_response(code=self.message_code.TASK_ERROR.value,
message='İstemci yeniden başlatılırken bir hata oluştu.')
def handle_task(task, context):
manage = Restart(task, context)
manage.handle_task()

View file

@ -5,16 +5,14 @@
from base.plugin.abstract_plugin import AbstractPlugin from base.plugin.abstract_plugin import AbstractPlugin
class LoginManager(AbstractPlugin): class Shutdown(AbstractPlugin):
def __init__(self, task, context): def __init__(self, task, context):
super(AbstractPlugin, self).__init__() super(AbstractPlugin, self).__init__()
self.task = task self.task = task
self.context = context self.context = context
self.logger = self.get_logger() self.logger = self.get_logger()
self.message_code = self.get_message_code() self.message_code = self.get_message_code()
self.command_shutdown = 'shutdown -h now' self.command_shutdown = 'shutdown -h now'
self.logger.debug('Parameters were initialized.') self.logger.debug('Parameters were initialized.')
def handle_task(self): def handle_task(self):
@ -29,5 +27,5 @@ class LoginManager(AbstractPlugin):
message='İstemci kapatılırken bir hata oluştu.') message='İstemci kapatılırken bir hata oluştu.')
def handle_task(task, context): def handle_task(task, context):
manage = LoginManager(task, context) manage = Shutdown(task, context)
manage.handle_task() manage.handle_task()