Esempio n. 1
0
    def get_file(self, local_path=None, file_name=None):
        self.logger.debug('Getting file ...')
        try:
            tmp_file_name = str(Util.generate_uuid())
            local_full_path = System.Ahenk.received_dir_path() + tmp_file_name
            sftp = paramiko.SFTPClient.from_transport(self.connection)
            sftp.get(self.target_path, local_full_path)

            if local_path is None:
                receive_path = System.Ahenk.received_dir_path()
            else:
                receive_path = local_path
            if file_name is not None:
                f_name = file_name
            else:
                f_name = str(Util.get_md5_file(local_full_path))
            Util.rename_file(local_full_path, receive_path + f_name)
            self.logger.debug('File was downloaded to {0} from {1}'.format(
                receive_path, self.target_path))
        except Exception as e:
            self.logger.warning(
                'A problem occurred while downloading file. Exception message: {0}'
                .format(str(e)))
            raise
        return f_name
Esempio n. 2
0
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.message_manager = scope.get_message_manager()
        self.event_manager = scope.get_event_manager()
        self.messenger = scope.get_messenger()
        self.conf_manager = scope.get_configuration_manager()
        self.db_service = scope.get_db_service()
        self.util = Util()
        self.servicename = 'im.liderahenk.org'
        self.local_user_disable = None

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

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

        self.directory_server = None

        if self.is_registered():
            self.logger.debug('Ahenk already registered')
        else:
            self.register(True)
Esempio n. 3
0
    def write_to_global_profile(self):

        process = subprocess.Popen(self.command_get_users_currently_login,
                                   stdin=None,
                                   env=None,
                                   cwd=None,
                                   stderr=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   shell=True)
        process.wait()
        p_out = process.stdout.read().decode("unicode_escape")
        users = []

        if p_out != None:
            users = str(p_out).split('\n')
            users.pop()

            if 'root' in users:
                users.remove('root')

        logging.debug('Logged-in users: {0}'.format(users))

        if str(self.today) in self.days:

            if not (self.start_minute < self.current_minute < self.end_minute
                    and self.current_date <= self.last_date):
                for user in users:
                    logging.debug('User \'{0}\' will log out.'.format(user))
                    process = subprocess.Popen(
                        self.command_logout_user.format(user),
                        stdin=None,
                        env=None,
                        cwd=None,
                        stderr=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        shell=True)
                    process.wait()

            elif int(self.end_minute) - int(self.current_minute) == int(
                    self.duration):
                for user in users:
                    Util.send_notify(
                        'Lider Ahenk',
                        'Oturum {0} dakika sonra kapatılacak!'.format(
                            str(self.duration)), ':0', user)
                pass
        else:
            for user in users:
                Util.send_notify('Lider Ahenk', 'Oturum şimdi kapatılacak!',
                                 ':0', user)
                logging.debug('User \'{0}\' will log out.'.format(user))
                process = subprocess.Popen(
                    self.command_logout_user.format(user),
                    stdin=None,
                    env=None,
                    cwd=None,
                    stderr=subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    shell=True)
                process.wait()
Esempio n. 4
0
    def agreement_update(self, arg):

        try:
            json_data = json.loads(arg)
            transfer_manager = FileTransferManager(json_data['protocol'],
                                                   json_data['parameterMap'])

            transfer_manager.transporter.connect()
            file_name = transfer_manager.transporter.get_file()
            transfer_manager.transporter.disconnect()

            agreement_content = Util.read_file(
                System.Ahenk.received_dir_path() + file_name)
            Util.delete_file(System.Ahenk.received_dir_path() + file_name)
            # TODO
            title = 'Kullanıcı Sözleşmesi'

            if agreement_content is not None and agreement_content != '':
                old_content = self.db_service.select_one_result(
                    'contract', 'content',
                    'id =(select MAX(id) from contract)')
                if old_content is None or Util.get_md5_text(
                        old_content) != Util.get_md5_text(agreement_content):
                    self.db_service.update(
                        'contract', self.db_service.get_cols('contract'),
                        [agreement_content, title, json_data['timestamp']])
        except Exception as e:
            self.logger.warning(
                'A problem occurred while updating agreement. Error Message : {0}'
                .format(str(e)))
Esempio n. 5
0
    def unregister_msg(self):

        user_name = self.db_service.select_one_result('session', 'username')
        display = self.db_service.select_one_result('session', 'display')

        self.logger.debug('User : '******'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['type'] = 'UNREGISTER'
        data['from'] = str(self.conf_manager.get('CONNECTION', 'uid'))
        data['password'] = str(self.conf_manager.get('CONNECTION', 'password'))

        data['userName'] = user_registration_info[0]
        data['userPassword'] = user_registration_info[1]

        #data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
        #data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
        #data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
        # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Unregister message was created')
        return json_data
Esempio n. 6
0
    def login_msg(self, username, ip=None):
        data = dict()
        data['type'] = 'LOGIN'
        data['username'] = username
        data['ipAddresses'] = str(
            System.Hardware.Network.ip_addresses()).replace('[', '').replace(
                ']', '')
        data['timestamp'] = Util.timestamp()
        data['userIp'] = ip
        data['osVersion'] = System.Os.version()
        data['diskTotal'] = System.Hardware.Disk.total()
        data['diskUsed'] = System.Hardware.Disk.used()
        data['diskFree'] = System.Hardware.Disk.free()
        data['memory'] = System.Hardware.Memory.total()
        data['hostname'] = str(System.Os.hostname())
        data['agentVersion'] = str(Util.get_agent_version())

        self.logger.debug('USER IP : ' + str(ip) + ' IPADDRESSES : ' +
                          str(System.Hardware.Network.ip_addresses()).replace(
                              '[', '').replace(']', ''))

        data['hardware.monitors'] = str(System.Hardware.monitors()),
        data['hardware.screens'] = str(System.Hardware.screens()),
        data['hardware.usbDevices'] = str(System.Hardware.usb_devices()),
        data['hardware.printers'] = str(System.Hardware.printers()),
        data['hardware.systemDefinitions'] = str(
            System.Hardware.system_definitions()),

        json_data = json.dumps(data)
        self.logger.debug('Login message was created')
        return json_data
Esempio n. 7
0
    def change_permissions_for_local_users(self):
        if self.disable_local_users is False:
            content = Util.read_file('/etc/passwd')
            change_permisson = "chmod -R 700 {}"
            for p in pwd.getpwall():
                self.logger.info(
                    "User: '******' will change home directory of username".
                    format(p.pw_name))
                if not sysx.shell_is_interactive(p.pw_shell):
                    continue
                if p.pw_uid == 0:
                    continue
                if p.pw_name in content:
                    Util.execute(change_permisson.format(p.pw_dir))

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

        file_dir_mode = open(add_user_conf_file, 'w')
        file_dir_mode.write(file_data)
        file_dir_mode.close()
        self.logger.info("add user mode changed to 0700 in file {}".format(
            add_user_conf_file))
Esempio n. 8
0
 def delete_polkit_user(self):
     content = "[Configuration] \nAdminIdentities=unix-user:root"
     ahenk_policy_file = "/etc/polkit-1/localauthority.conf.d/99-ahenk-policy.conf"
     if not Util.is_exist(ahenk_policy_file):
         self.logger.info('Ahenk polkit file not found')
     else:
         Util.delete_file(ahenk_policy_file)
         self.logger.info("Delete polkit file")
Esempio n. 9
0
    def ask(self, username, display):

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

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

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

        except Exception as e:
            self.logger.error(
                'A Problem occurred while displaying agreement. Error Message: {0}'
                .format(str(e)))
Esempio n. 10
0
    def clean(self):
        print('Ahenk cleaning..')
        try:
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            db_path = config.get('BASE', 'dbPath')

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

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

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

            config.set('CONNECTION', 'uid', '')
            config.set('CONNECTION', 'password', '')

            with open(System.Ahenk.config_path(), 'w') as file:
                config.write(file)
            file.close()
            print('Ahenk cleaned.')
        except Exception as e:
            print(
                'Error while running clean command. Error Message {0}'.format(
                    str(e)))
Esempio n. 11
0
    def clean(self):
        print('Ahenk cleaning..')
        try:
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            db_path = config.get('BASE', 'dbPath')

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

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

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

            config.set('CONNECTION', 'uid', '')
            config.set('CONNECTION', 'password', '')

            with open(System.Ahenk.config_path(), 'w') as file:
                config.write(file)
            file.close()
            print('Ahenk cleaned.')
        except Exception as e:
            print('Error while running clean command. Error Message {0}'.format(str(e)))
Esempio n. 12
0
 def registration_timeout(self):
     self.logger.error(
         'Could not reach registration response from Lider. Be sure XMPP server is reachable and it supports anonymous message, Lider is running properly '
         'and it is connected to XMPP server! Check your Ahenk configuration file (/etc/ahenk/ahenk.conf)'
     )
     self.logger.error('Ahenk is shutting down...')
     print('Ahenk is shutting down...')
     Util.show_message(
         os.getlogin(), ':0',
         "Lider MYS sistemine ulaşılamadı. Lütfen sunucu adresini kontrol ediniz....",
         "HATA")
     System.Process.kill_by_pid(int(System.Ahenk.get_pid_number()))
Esempio n. 13
0
    def ask(self, username, display):

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

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

        except Exception as e:
            self.logger.error(
                'A Problem occurred while displaying agreement. Error Message: {0}'.format(str(e)))
Esempio n. 14
0
    def execute_script(self, arg):
        try:
            self.logger.debug('Executing script...')
            messenger = Scope().get_instance().get_messenger()

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

            self.logger.debug('Executed script')

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

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

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

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

                    else:
                        data['md5'] = md5

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

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

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

            self.logger.debug('Executed script')

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

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

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

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

                    else:
                        data['md5'] = md5

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

            messenger.send_direct_message(json.dumps(data))
        except Exception as e:
            self.logger.error(
                'A problem occurred while running execute script action. Error Message :{0}'.format(
                    str(e)))
Esempio n. 16
0
    def get_file(self):

        self.logger.debug('[FileTransfer] Getting file ...')
        file_md5 = None
        try:
            tmp_file_name = str(Util.generate_uuid())
            local_full_path = System.Ahenk.received_dir_path() + tmp_file_name
            urllib.request.urlretrieve(self.url, local_full_path)
            file_md5 = str(Util.get_md5_file(local_full_path))
            Util.rename_file(local_full_path, System.Ahenk.received_dir_path() + file_md5)
            self.logger.debug('File was downloaded to {0} from {1}'.format(local_full_path, self.url))
        except Exception as e:
            self.logger.error(
                'A problem occurred while downloading file. Exception message: {0}'.format(str(e)))
            raise
        return file_md5
Esempio n. 17
0
 def manufacturer():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-manufacturer')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 18
0
    def agreement_answer_msg(self, username, answer):
        data = dict()
        data['type'] = 'AGREEMENT_STATUS'
        data['username'] = username
        data['accepted'] = answer
        data['timestamp'] = Util.timestamp()
        contract_content = self.db_service.select_one_result('contract', 'content',
                                                             'id =(select MAX(id) from contract)')
        if contract_content is not None and contract_content != '':
            data['md5'] = Util.get_md5_text(contract_content)
        else:
            data['md5'] = ''

        json_data = json.dumps(data)
        self.logger.debug('Agreement answer message was created')
        return json_data
Esempio n. 19
0
 def machine_model():
     try:
         result_code, p_out, p_err = Util.execute(
             'sudo dmidecode --string system-version')
         return str(p_out)
     except:
         raise
Esempio n. 20
0
    def agreement_answer_msg(self, username, answer):
        data = dict()
        data['type'] = 'AGREEMENT_STATUS'
        data['username'] = username
        data['accepted'] = answer
        data['timestamp'] = Util.timestamp()
        contract_content = self.db_service.select_one_result(
            'contract', 'content', 'id =(select MAX(id) from contract)')
        if contract_content is not None and contract_content != '':
            data['md5'] = Util.get_md5_text(contract_content)
        else:
            data['md5'] = ''

        json_data = json.dumps(data)
        self.logger.debug('Agreement answer message was created')
        return json_data
Esempio n. 21
0
    def __init__(self, parameter_map):

        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.configuration_manager = scope.get_configuration_manager()
        logging.getLogger("paramiko").setLevel(logging.INFO)

        try:
            self.target_hostname = parameter_map['host']
            self.target_port = parameter_map['port']
            self.target_username = parameter_map['username']
            self.target_path = parameter_map['path']
            self.target_password = None
            self.p_key = None
            if Util.has_attr_json(parameter_map, 'password'):
                self.target_password = parameter_map['password']
            else:
                self.p_key = parameter_map['pkey']
        except Exception as e:
            self.logger.error(
                'A problem occurred while parsing ssh connection parameters. Error Message: {0}'
                .format(str(e)))

        self.connection = None
        self.logger.debug('Parameters set up')
Esempio n. 22
0
 def product_name():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-product-name')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 23
0
 def version():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string bios-version')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 24
0
 def serial_number():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-serial-number')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 25
0
 def asset_tag():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string baseboard-asset-tag')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 26
0
 def release_date():
     try:
         result_code, p_out, p_err = Util.execute(
             'dmidecode --string bios-release-date')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 27
0
    def policy_request_msg(self, username):
        data = dict()
        data['type'] = 'GET_POLICIES'

        user_policy_number = self.db_service.select_one_result(
            'policy', 'version',
            'type = \'U\' and name = \'' + username + '\'')
        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['agentPolicyVersion'] = machine_policy_number

        data['username'] = str(username)
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Get Policies message was created')
        return json_data
Esempio n. 28
0
    def unregister(self, msg):
        j = json.loads(msg)
        status = str(j['status']).lower()

        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 ")

        if 'not_authorized' == str(status):
            self.logger.info('Registration 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.',
                   'Kullanıcı Yetkilendirme Hatası')
        else :
            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 sistemi yeniden başlatmanız gerekmektedir.", "") :
                registration= Scope.get_instance().get_registration()
                registration.purge_and_unregister()
Esempio n. 29
0
 def usb_devices():
     result_code, p_out, p_err = Util.execute('lsusb')
     arr = []
     if result_code == 0:
         for line in p_out.splitlines():
             if ':' in line and 'Device 001' not in line.split(':')[0]:
                 arr.append(line)
     return arr
Esempio n. 30
0
 def logout_msg(self, username):
     data = dict()
     data['type'] = 'LOGOUT'
     data['username'] = str(username)
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Logout message was created')
     return json_data
Esempio n. 31
0
    def __init__(self):
        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.message_manager = scope.get_message_manager()
        self.event_manager = scope.get_event_manager()
        self.messenger = scope.get_messenger()
        self.conf_manager = scope.get_configuration_manager()
        self.db_service = scope.get_db_service()
        self.util = Util()

        self.event_manager.register_event('REGISTRATION_RESPONSE',
                                          self.registration_process)

        if self.is_registered():
            self.logger.debug('Ahenk already registered')
        else:
            self.register(True)
Esempio n. 32
0
 def screens():
     result_code, p_out, p_err = Util.execute('xrandr')
     arr = []
     if result_code == 0:
         for line in p_out.splitlines():
             if len(list(set(line.split(' ')).intersection(['connected']))) > 0:
                 arr.append(line)
     return arr
Esempio n. 33
0
 def logout_msg(self, username):
     data = dict()
     data['type'] = 'LOGOUT'
     data['username'] = str(username)
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Logout message was created')
     return json_data
Esempio n. 34
0
 def system_definitions():
     result_code, p_out, p_err = Util.execute('dmidecode -t system')
     arr = []
     if result_code == 0:
         for line in p_out.splitlines():
             line = line.strip()
             if len(list(set(line.split(' ')).intersection(['Manufacturer:', 'Product']))) > 0:
                 arr.append(line)
     return arr
Esempio n. 35
0
 def login_msg(self, username):
     data = dict()
     data['type'] = 'LOGIN'
     data['username'] = username
     data['ipAddresses'] = str(System.Hardware.Network.ip_addresses()).replace('[', '').replace(']', '')
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Login message was created')
     return json_data
Esempio n. 36
0
    def install_plugin(self, arg):
        plugin = json.loads(arg)
        self.logger.debug('Installing missing plugin')
        try:
            plugin_name = plugin['pluginName']
            plugin_version = plugin['pluginVersion']

            try:
                transfer_manager = FileTransferManager(plugin['protocol'],
                                                       plugin['parameterMap'])
                transfer_manager.transporter.connect()
                file_name = transfer_manager.transporter.get_file()
                transfer_manager.transporter.disconnect()
                downloaded_file = System.Ahenk.received_dir_path() + file_name
            except Exception as e:
                self.logger.error(
                    'Plugin package could not fetch. Error Message: {0}.'.
                    format(str(e)))
                self.logger.error('Plugin Installation is cancelling')
                self.plugin_installation_failure(plugin_name, plugin_version)
                return

            try:
                Util.install_with_gdebi(downloaded_file)
                self.logger.debug('Plugin installed.')
            except Exception as e:
                self.logger.error(
                    'Could not install plugin. Error Message: {0}'.format(
                        str(e)))
                self.plugin_installation_failure(plugin_name, plugin_version)
                return

            try:
                Util.delete_file(downloaded_file)
                self.logger.debug('Temp files were removed.')
            except Exception as e:
                self.logger.error(
                    'Could not remove temp file. Error Message: {0}'.format(
                        str(e)))

        except Exception as e:
            self.logger.error(
                'A problem occurred while installing new Ahenk plugin. Error Message:{0}'
                .format(str(e)))
    def get_file(self):

        self.logger.debug('[FileTransfer] Getting file ...')
        file_md5 = None
        try:
            tmp_file_name = str(Util.generate_uuid())
            local_full_path = System.Ahenk.received_dir_path() + tmp_file_name
            urllib.request.urlretrieve(self.url, local_full_path)
            file_md5 = str(Util.get_md5_file(local_full_path))
            Util.rename_file(local_full_path,
                             System.Ahenk.received_dir_path() + file_md5)
            self.logger.debug('File was downloaded to {0} from {1}'.format(
                local_full_path, self.url))
        except Exception as e:
            self.logger.error(
                'A problem occurred while downloading file. Exception message: {0}'
                .format(str(e)))
            raise
        return file_md5
Esempio n. 38
0
 def ldap_registration_msg(self):
     data = dict()
     data['type'] = 'REGISTER_LDAP'
     data['from'] = str(self.conf_manager.get('REGISTRATION', 'from'))
     data['password'] = str(self.conf_manager.get('REGISTRATION', 'password'))
     data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
     data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
     data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('LDAP Registration message was created')
     return json_data
Esempio n. 39
0
 def unregister_msg(self):
     data = dict()
     data['type'] = 'UNREGISTER'
     data['from'] = str(self.conf_manager.get('REGISTRATION', 'from'))
     data['password'] = str(self.conf_manager.get('REGISTRATION', 'password'))
     data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
     data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
     data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
     # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Unregister message was created')
     return json_data
Esempio n. 40
0
    def get_file(self, local_path=None, file_name=None):
        self.logger.debug('Getting file ...')
        try:
            tmp_file_name = str(Util.generate_uuid())
            local_full_path = System.Ahenk.received_dir_path() + tmp_file_name
            sftp = paramiko.SFTPClient.from_transport(self.connection)
            sftp.get(self.target_path, local_full_path)

            if local_path is None:
                receive_path = System.Ahenk.received_dir_path()
            else:
                receive_path = local_path
            if file_name is not None:
                f_name = file_name
            else:
                f_name = str(Util.get_md5_file(local_full_path))
            Util.rename_file(local_full_path, receive_path + f_name)
            self.logger.debug('File was downloaded to {0} from {1}'.format(receive_path, self.target_path))
        except Exception as e:
            self.logger.warning('A problem occurred while downloading file. Exception message: {0}'.format(str(e)))
            raise
        return f_name
Esempio n. 41
0
    def install_plugin(self, arg):
        plugin = json.loads(arg)
        self.logger.debug('Installing missing plugin')
        try:
            plugin_name = plugin['pluginName']
            plugin_version = plugin['pluginVersion']

            try:
                transfer_manager = FileTransferManager(plugin['protocol'], plugin['parameterMap'])
                transfer_manager.transporter.connect()
                file_name = transfer_manager.transporter.get_file()
                transfer_manager.transporter.disconnect()
                downloaded_file = System.Ahenk.received_dir_path() + file_name
            except Exception as e:
                self.logger.error(
                    'Plugin package could not fetch. Error Message: {0}.'.format(str(e)))
                self.logger.error('Plugin Installation is cancelling')
                self.plugin_installation_failure(plugin_name, plugin_version)
                return

            try:
                Util.install_with_gdebi(downloaded_file)
                self.logger.debug('Plugin installed.')
            except Exception as e:
                self.logger.error('Could not install plugin. Error Message: {0}'.format(str(e)))
                self.plugin_installation_failure(plugin_name, plugin_version)
                return

            try:
                Util.delete_file(downloaded_file)
                self.logger.debug('Temp files were removed.')
            except Exception as e:
                self.logger.error('Could not remove temp file. Error Message: {0}'.format(str(e)))

        except Exception as e:
            self.logger.error(
                'A problem occurred while installing new Ahenk plugin. Error Message:{0}'.format(
                    str(e)))
Esempio n. 42
0
    def agreement_update(self, arg):

        try:
            json_data = json.loads(arg)
            transfer_manager = FileTransferManager(json_data['protocol'], json_data['parameterMap'])

            transfer_manager.transporter.connect()
            file_name = transfer_manager.transporter.get_file()
            transfer_manager.transporter.disconnect()

            agreement_content = Util.read_file(System.Ahenk.received_dir_path() + file_name)
            Util.delete_file(System.Ahenk.received_dir_path() + file_name)
            # TODO
            title = 'Kullanıcı Sözleşmesi'

            if agreement_content is not None and agreement_content != '':
                old_content = self.db_service.select_one_result('contract', 'content',
                                                                'id =(select MAX(id) from contract)')
                if old_content is None or Util.get_md5_text(old_content) != Util.get_md5_text(agreement_content):
                    self.db_service.update('contract', self.db_service.get_cols('contract'),
                                           [agreement_content, title, json_data['timestamp']])
        except Exception as e:
            self.logger.warning(
                'A problem occurred while updating agreement. Error Message : {0}'.format(str(e)))
Esempio n. 43
0
    def agreement_request_msg(self):
        data = dict()
        data['type'] = 'REQUEST_AGREEMENT'

        """
        contract_content = self.db_service.select_one_result('contract', 'content', 'id =(select MAX(id) from contract)')
        if contract_content is not None and contract_content != '':
            data['md5'] = Util.get_md5_text(contract_content)
        else:
            data['md5'] = ''
        """

        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Agreement request message was created')
        return json_data
Esempio n. 44
0
    def policy_request_msg(self, username):
        data = dict()
        data['type'] = 'GET_POLICIES'

        user_policy_number = self.db_service.select_one_result('policy', 'version',
                                                               'type = \'U\' and name = \'' + username + '\'')
        machine_policy_number = self.db_service.select_one_result('policy', 'version', 'type = \'A\'')

        data['userPolicyVersion'] = user_policy_number
        data['agentPolicyVersion'] = machine_policy_number

        data['username'] = str(username)
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Get Policies message was created')
        return json_data
Esempio n. 45
0
    def __init__(self, parameter_map):

        scope = Scope().get_instance()
        self.logger = scope.get_logger()
        self.configuration_manager = scope.get_configuration_manager()
        logging.getLogger("paramiko").setLevel(logging.INFO)

        try:
            self.target_hostname = parameter_map['host']
            self.target_port = parameter_map['port']
            self.target_username = parameter_map['username']
            self.target_path = parameter_map['path']
            self.target_password = None
            self.p_key = None
            if Util.has_attr_json(parameter_map, 'password'):
                self.target_password = parameter_map['password']
            else:
                self.p_key = parameter_map['pkey']
        except Exception as e:
            self.logger.error(
                'A problem occurred while parsing ssh connection parameters. Error Message: {0}'.format(str(e)))

        self.connection = None
        self.logger.debug('Parameters set up')
Esempio n. 46
0
    def run(self):

        while self.keep_run:
            try:
                try:
                    item_obj = self.in_queue.get(block=True)
                    obj_name = item_obj.obj_name
                except Exception as e:
                    self.logger.error(
                        "[Plugin] A problem occurred while executing process. Error Message: {0}".format(str(e))
                    )

                if obj_name == "TASK":
                    self.logger.debug("[Plugin] Executing task")
                    command = (
                        Scope.get_instance()
                        .get_plugin_manager()
                        .find_command(
                            self.getName(), item_obj.get_plugin().get_version(), item_obj.get_command_cls_id().lower()
                        )
                    )
                    self.context.put("task_id", item_obj.get_id())

                    if item_obj.get_file_server() is not None and item_obj.get_file_server() != "null":
                        self.context.put("protocol", json.loads(item_obj.get_file_server())["protocol"])
                        self.context.put("parameterMap", json.loads(item_obj.get_file_server())["parameterMap"])

                    task_data = item_obj.get_parameter_map()

                    self.logger.debug("[Plugin] Sending notify to user about task process")

                    if System.Sessions.user_name() is not None and len(System.Sessions.user_name()) > 0:
                        for user in System.Sessions.user_name():
                            Util.send_notify(
                                "Lider Ahenk",
                                "{0} eklentisi şu anda bir görev çalıştırıyor.".format(self.getName()),
                                System.Sessions.display(user),
                                user,
                            )

                    self.logger.debug("[Plugin] Handling task")
                    command.handle_task(task_data, self.context)

                    if self.context.data is not None and self.context.get("responseCode") is not None:
                        self.logger.debug("[Plugin] Creating response")
                        response = Response(
                            type=MessageType.TASK_STATUS.value,
                            id=item_obj.get_id(),
                            code=self.context.get("responseCode"),
                            message=self.context.get("responseMessage"),
                            data=self.context.get("responseData"),
                            content_type=self.context.get("contentType"),
                        )

                        if response.get_data() and response.get_content_type() != ContentType.APPLICATION_JSON.value:
                            success = False
                            try:
                                file_manager = FileTransferManager(
                                    json.loads(item_obj.get_file_server())["protocol"],
                                    json.loads(item_obj.get_file_server())["parameterMap"],
                                )
                                file_manager.transporter.connect()
                                md5 = str(json.loads(response.get_data())["md5"])
                                success = file_manager.transporter.send_file(
                                    System.Ahenk.received_dir_path() + md5, md5
                                )
                                file_manager.transporter.disconnect()
                            except Exception as e:
                                self.logger.error(
                                    "[Plugin] A problem occurred while file transferring. Error Message :{0}".format(
                                        str(e)
                                    )
                                )

                            self.logger.debug("[Plugin] Sending response")

                            message = self.messaging.task_status_msg(response)
                            if success is False:
                                response = Response(
                                    type=MessageType.TASK_STATUS.value,
                                    id=item_obj.get_id(),
                                    code=MessageCode.TASK_ERROR.value,
                                    message="Task processed successfully but file transfer not completed. Check defined server conf",
                                )
                                message = self.messaging.task_status_msg(response)

                            Scope.get_instance().get_messenger().send_direct_message(message)

                        else:
                            self.logger.debug("[Plugin] Sending task response")
                            Scope.get_instance().get_messenger().send_direct_message(
                                self.messaging.task_status_msg(response)
                            )

                    else:
                        self.logger.error(
                            "[Plugin] There is no Response. Plugin must create response after run a task!"
                        )

                elif obj_name == "PROFILE":

                    self.logger.debug("[Plugin] Executing profile")
                    profile_data = item_obj.get_profile_data()
                    policy_module = (
                        Scope.get_instance()
                        .get_plugin_manager()
                        .find_policy_module(item_obj.get_plugin().get_name(), item_obj.get_plugin().get_version())
                    )
                    self.context.put("username", item_obj.get_username())

                    execution_id = self.get_execution_id(item_obj.get_id())
                    policy_ver = self.get_policy_version(item_obj.get_id())

                    self.context.put("policy_version", policy_ver)
                    self.context.put("execution_id", execution_id)

                    # if item_obj.get_file_server() is not None  and item_obj.get_file_server() !='null':
                    #     self.context.put('protocol', json.loads(item_obj.get_file_server())['protocol'])
                    #     self.context.put('parameterMap', json.loads(item_obj.get_file_server())['parameterMap'])

                    self.logger.debug("[Plugin] Sending notify to user about profile process")

                    Util.send_notify(
                        "Lider Ahenk",
                        "{0} eklentisi şu anda bir profil çalıştırıyor.".format(self.getName()),
                        System.Sessions.display(item_obj.get_username()),
                        item_obj.get_username(),
                    )
                    self.logger.debug("[Plugin] Handling profile")
                    policy_module.handle_policy(profile_data, self.context)

                    if self.context.data is not None and self.context.get("responseCode") is not None:
                        self.logger.debug("[Plugin] Creating response")
                        response = Response(
                            type=MessageType.POLICY_STATUS.value,
                            id=item_obj.get_id(),
                            code=self.context.get("responseCode"),
                            message=self.context.get("responseMessage"),
                            data=self.context.get("responseData"),
                            content_type=self.context.get("contentType"),
                            execution_id=execution_id,
                            policy_version=policy_ver,
                        )

                        if response.get_data() and response.get_content_type() != ContentType.APPLICATION_JSON.value:
                            success = False
                            try:
                                file_manager = FileTransferManager(
                                    json.loads(item_obj.get_file_server())["protocol"],
                                    json.loads(item_obj.get_file_server())["parameterMap"],
                                )
                                file_manager.transporter.connect()
                                md5 = str(json.loads(response.get_data())["md5"])
                                success = file_manager.transporter.send_file(
                                    System.Ahenk.received_dir_path() + md5, md5
                                )
                                file_manager.transporter.disconnect()
                            except Exception as e:
                                self.logger.error(
                                    "[Plugin] A problem occurred while file transferring. Error Message :{0}".format(
                                        str(e)
                                    )
                                )

                            self.logger.debug("[Plugin] Sending response")

                            message = self.messaging.task_status_msg(response)
                            if success is False:
                                response = Response(
                                    type=MessageType.POLICY_STATUS.value,
                                    id=item_obj.get_id(),
                                    code=MessageCode.POLICY_ERROR.value,
                                    message="Policy processed successfully but file transfer not completed. Check defined server conf",
                                )
                                message = self.messaging.task_status_msg(response)
                            Scope.get_instance().get_messenger().send_direct_message(message)
                        else:
                            self.logger.debug("[Plugin] Sending profile response")
                            Scope.get_instance().get_messenger().send_direct_message(
                                self.messaging.policy_status_msg(response)
                            )
                    else:
                        self.logger.error(
                            "[Plugin] There is no Response. Plugin must create response after run a policy!"
                        )
                elif "MODE" in obj_name:
                    module = Scope.get_instance().get_plugin_manager().find_module(obj_name, self.name)
                    if module is not None:
                        if item_obj.obj_name in ("LOGIN_MODE", "LOGOUT_MODE", "SAFE_MODE"):
                            self.context.put("username", item_obj.username)
                        try:
                            self.logger.debug(
                                "[Plugin] {0} is running on {1} plugin".format(str(item_obj.obj_name), str(self.name))
                            )
                            module.handle_mode(self.context)
                        except Exception as e:
                            self.logger.error(
                                "[Plugin] A problem occurred while running {0} on {1} plugin. Error Message: {2}".format(
                                    str(obj_name), str(self.name), str(e)
                                )
                            )

                    if item_obj.obj_name is "SHUTDOWN_MODE":
                        self.logger.debug("[Plugin] {0} plugin is stopping...".format(str(self.name)))
                        self.keep_run = False
                else:
                    self.logger.warning("[Plugin] Not supported object type: {0}".format(str(obj_name)))

                self.context.empty_data()
            except Exception as e:
                self.logger.error("[Plugin] Plugin running exception. Exception Message: {0} ".format(str(e)))
Esempio n. 47
0
 def received_dir_path():
     path = '/tmp/.ahenk/'
     if Util.is_exist(path) is False:
         Util.create_directory(path)
         Util.set_permission(path, '777')
     return path
Esempio n. 48
0
 def manufacturer():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-manufacturer')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 49
0
 def release_date():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string bios-release-date')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 50
0
 def product_name():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-product-name')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 51
0
 def serial_number():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-serial-number')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 52
0
 def asset_tag():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string baseboard-asset-tag')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 53
0
 def version():
     try:
         result_code, p_out, p_err = Util.execute('dmidecode --string bios-version')
         return int(result_code), str(p_out), str(p_err)
     except:
         raise
Esempio n. 54
0
    def run_command_from_fifo(self, num, stack):
        """ docstring"""

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

            if json_data is not None:

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

                if str(json_data['event']) == 'login':
                    username = json_data['username']
                    display = json_data['display']
                    desktop = json_data['desktop']
                    self.logger.info('login event is handled for user: {0}'.format(username))
                    login_message = self.message_manager.login_msg(username)
                    self.messenger.send_direct_message(login_message)

                    agreement = Agreement()
                    agreement_choice = None

                    if agreement.check_agreement(username) is not True:
                        self.logger.debug('User {0} has not accepted agreement.'.format(username))
                        thread_ask = Process(target=agreement.ask, args=(username, display,))
                        thread_ask.start()

                        agreement_timeout = self.conf_manager.get('SESSION', 'agreement_timeout')

                        timeout = int(agreement_timeout)  # sec
                        timer = time.time()
                        while 1:
                            if thread_ask.is_alive() is False:
                                self.logger.warning('{0} was answered the question '.format(username))
                                if Agreement().check_agreement(username) is True:
                                    self.logger.warning('Choice of {0} is YES'.format(username))
                                    agreement_choice = True
                                    break
                                elif Agreement().check_agreement(username) is False:
                                    self.logger.warning('Choice of {0} is NO'.format(username))
                                    agreement_choice = False
                                    Util.close_session(username)
                                    break

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

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

                    if agreement_choice is True:
                        self.db_service.delete('session', 'username=\'{0}\''.format(username))

                        self.logger.info(
                            'Display is {0}, desktop env is {1} for {2}'.format(display, desktop,
                                                                                username))
                        session_columns = self.db_service.get_cols('session')
                        self.db_service.update('session', session_columns,
                                               [username, display, desktop, Util.timestamp()])
                        get_policy_message = self.message_manager.policy_request_msg(username)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    Util.delete_file(System.Ahenk.fifo_file())
                    Scope().get_instance().get_custom_param('ahenk_daemon').stop()
                else:
                    self.logger.error('Unknown command error. Command:' + json_data['event'])
                self.logger.debug('Processing of handled event is completed')
Esempio n. 55
0
 def init_fifo_file():
     """ docstring"""
     if Util.is_exist(System.Ahenk.fifo_file()):
         Util.delete_file(System.Ahenk.fifo_file())
     Util.create_file(System.Ahenk.fifo_file())
     Util.set_permission(System.Ahenk.fifo_file(), '600')
Esempio n. 56
0
    def set_event(self, *args):

        if args is None or len(args) < 1:
            print('Lack of arguments')

        params = args[0]
        data = dict()

        if System.Ahenk.is_running() is True:

            if len(params) > 1 and params[1] == 'clean':
                print('Ahenk stopping')
                System.Process.kill_by_pid(int(System.Ahenk.get_pid_number()))
                self.clean()
                return False

            elif len(params) == 5 and params[1] == 'login':
                print('{0} logging in'.format(str(params[2])))
                data['event'] = params[1]
                data['username'] = params[2]
                data['desktop'] = params[3]
                data['display'] = params[4]

            elif len(params) == 3 and params[1] == 'logout':
                print('{0} logging out'.format(str(params[2])))
                data['event'] = params[1]
                data['username'] = params[2]

            elif len(params) == 2 and params[1] == 'stop':
                data['event'] = 'stop'

            elif len(params) == 4 and params[1] == 'load' and params[2] == '-p':
                data['event'] = 'load'
                data['plugins'] = params[3]

            elif len(params) == 4 and params[1] == 'reload' and params[2] == '-p':
                data['event'] = 'reload'
                data['plugins'] = params[3]

            elif len(params) == 4 and params[1] == 'remove' and params[2] == '-p':
                data['event'] = 'remove'
                data['plugins'] = params[3]

            elif len(params) > 5 and params[1] == 'send':
                data['event'] = params[1]
                response = dict()
                response['timestamp'] = str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M"))
                response['responseMessage'] = 'This content was sent via ahenk terminal command'

                if params[2] == '-t':
                    response['responseCode'] = MessageCode.TASK_PROCESSED.value
                    response['type'] = MessageType.TASK_STATUS.value
                    response['taskId'] = params[3]
                    if params[4] == '-m':
                        response['contentType'] = ContentType.APPLICATION_JSON.value
                        response['responseData'] = params[5]
                    elif params[4] == '-f':
                        if os.path.exists(str(params[5])):
                            response['contentType'] = self.get_relevant_type(str(params[5]))
                            response['responseData'] = Util.read_file(str(params[5]), 'rb')
                    else:
                        print(
                            'Wrong or missing parameter. Usage: send -t <task_id> -m|-f <message_content>|<file_path>')
                        return None

                    if len(params) > 6:
                        if params[6] == '-e':
                            response['responseCode'] = MessageCode.TASK_ERROR.value
                        elif params[6] == '-w':
                            response['responseCode'] = MessageCode.TASK_WARNING.value
                        elif params[6] == '-s':
                            response['responseCode'] = MessageCode.TASK_PROCESSED.value
                        else:
                            print(
                                'Wrong or missing parameter.(-e|-s|-w parameters are optional) Usage: send -t <task_id> -m|-f <message_content>|<file_path> -e|-s|-w')
                            return None

                elif len(params) > 7 and params[2] == '-p':
                    response['responseCode'] = MessageCode.POLICY_PROCESSED.value
                    response['type'] = MessageType.POLICY_STATUS.value
                    response['policyVersion'] = params[3]

                    if params[4] == '-c':
                        response['commandExecutionId'] = params[5]

                        if params[6] == '-m':
                            response['contentType'] = ContentType.APPLICATION_JSON.value
                            response['responseData'] = params[7]
                        elif params[6] == '-f':
                            if os.path.exists(str(params[7])):
                                response['contentType'] = self.get_relevant_type(str(params[7]))
                                response['responseData'] = Util.read_file(str(params[7]), 'rb')
                        else:
                            print(
                                'Wrong or missing parameter. Usage: send -p <policy_version> -c <command_execution_id> -m|-f <message_content>|<file_path>')
                            return None

                        if len(params) > 8:
                            if params[8] == '-e':
                                response['responseCode'] = MessageCode.POLICY_ERROR.value
                            elif params[8] == '-w':
                                response['responseCode'] = MessageCode.POLICY_WARNING.value
                            elif params[8] == '-s':
                                response['responseCode'] = MessageCode.POLICY_PROCESSED.value
                            else:
                                print(
                                    'Wrong or missing parameter.(-e|-s|-w parameters are optional) Usage: send -p <policy_version> -c <command_execution_id> -m|-f <message_content>|<file_path> -e|-s|-w')
                                return None

                    else:
                        print(
                            'Wrong or missing parameter. Usage: send -p <policy_version> -c <command_execution_id> -m|-f <message_content>|<file_path> -e|-s|-w')
                        return None

                resp = str(response).replace("\"{", "{")
                resp = resp.replace("}\"", "}")
                resp = resp.replace("'", "\"")
                data['message'] = json.loads(resp)
                # data['message'] = ast.literal_eval(str(response))

            else:
                print('Wrong or missing parameter. Usage : %s start|stop|restart|status|clean|send')
                return None
        else:

            if params[1] == 'clean':
                self.clean()

            else:
                print('Ahenk not running!')
                return None

        if len(data) > 0:
            fifo = Fifo()
            thread = threading.Thread(target=fifo.push(str(json.dumps(data)) + '\n'))
            thread.start()

        return True