Пример #1
0
def encrypt(file, extension=EXTENSION):

    key = generate_uniqkey.generate(32)
    filename  = '{}.{}'.format(file, extension)

    if (os.path.isfile(file)):

        with open(file, 'rb') as obj:

            file_encrypt = simplycrypt.encrypt(key, obj.read(), False)

        with open(file, 'wb') as obj:

            obj.write(file_encrypt)

        os.rename(file, filename)

        return({
                    'filename':'{}/{}'.format(os.getcwd(), filename),
                    'length':len(file_encrypt),
                    'password':key
                    
                })

    else:

        raise FileNotFoundError('¡El archivo "{}" no existe!'.format(file))
Пример #2
0
    def directorServer(self,
                       username,
                       passphrase,
                       addr=None,
                       pub_addr=False,
                       lport=16666,
                       sys_version='',
                       server_version=''):

        if (self.__directorInit == True):

            raise serverDirectorIsInit('El servidor ya está iniciado')

        self.__directorInit = True
        BaseHTTPRequestHandler.sys_version = str(sys_version)
        BaseHTTPRequestHandler.server_version = str(server_version)

        _address = self.__get_my_addr(addr, pub_addr)

        HTTPServerHandler._username = username
        HTTPServerHandler._passphrase = passphrase

        HTTPServerHandler.db_path = self.db_path
        HTTPServerHandler.db_pass = self.db_pass

        HTTPServerHandler._object = self

        httpd = ThreadingHTTPServer(('', lport), HTTPServerHandler)

        _hash = self.showServerHash()

        if (_hash == False):

            _hash = generate_uniqkey.generate()

            wrap_secure.add('hash', _hash, self.db_pass, self.db_path)

        self.directorResponse = self.send(('addPeer', {
            'url':
            'http://%s:%d' % (_address, lport),
            'username':
            username,
            'passphrase':
            passphrase,
            'db_passwd':
            self.db_pass,
            'hash':
            _hash
        }))

        try:

            httpd.serve_forever()

        finally:

            httpd.shutdown()
            self.__directorInit = False
Пример #3
0
def encrypt(raw, public_key):

    raw = dump(raw)

    rsa_test = rsa.main()
    rsa_test.import_PublicKey(public_key)

    key_session = generate_uniqkey.generate(32)

    aes_test = aes.AESCript(key_session.encode())

    key_session = rsa_test.encrypt(key_session)

    content = {}

    content['key_session'] = key_session
    content['content'] = aes_test.encrypt(raw.encode())

    return (encode(compress(dump(content).encode())))
Пример #4
0
def execute(data, bot_id, log):

    if not (check_values.check(data, 2) == True):

        log.logger(nomenclature_error, debug.WAR)

        return (False, None)

    (key, value) = data

    profile = '%s/%s/%s' % (db_dirname, profiles, bot_id)

    create_folder.create(profile)

    execute = True
    result = None
    bot_id = str(bot_id)

    if (key == 'ping'):

        log.logger('ping ... haciendo pong ...', debug.INF)
        result = (1, 'pong')

    elif (key == 'SEND-FILE'):

        if (check_values.check(value, 2) == False):

            log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            _content = value[0]
            filename = basename(str(value[1]))
            file_path = '{}/{}'.format(profile, filename)
            _bak_file_path = rename_order.rename(file_path)

            log.logger('Verificando la existencia del archivo ...', debug.INF)

            if not (_bak_file_path == False):

                log.logger(
                    'El archivo: "{}" existe, renombrando a: "{}"'.format(
                        file_path, _bak_file_path), debug.WAR)

                file_path = _bak_file_path

            else:

                log.logger(
                    'No existe: "{}", procediendo a escribir ...'.format(
                        file_path), debug.PER)

            log.logger('Escribiendo: "{}" ...'.format(file_path), debug.PER)

            try:

                if (cipher_file == True):

                    wrap_file.wrap(file_path, wrap._new_passwd, _content)

                else:

                    with open(file_path, 'wb') as file_object:

                        file_object.write(bytes_convert.convert(_content))

            except Exception as Except:

                log.logger(
                    'Ocurrio un error escribiendo a: "{}"'.format(file_path),
                    debug.WAR)
                execute = False

            else:

                log.logger('Escrito: "{}" ...'.format(file_path), debug.PER)

    elif (key == 'RECV-FILE'):

        file_path = '{}/{}/{}'.format(share_folder, bot_id,
                                      basename(str(value)))

        if (isfile(file_path)):

            log.logger('Enviando el archivo: "{}" ...'.format(file_path),
                       debug.PER)

            try:

                if (cipher_file == True):

                    result = wrap_file.wrap(file_path, wrap._new_passwd)

                    if (result == False):

                        log.logger(
                            '{}, no se pudo desencriptar..., Intentando sin desencriptar...'
                            .format(file_path), debug.WAR)

                if (result == False) or (cipher_file == False):

                    with open(file_path, 'rb') as file_object:

                        result = file_object.read()

            except Exception as Except:

                log.logger(
                    'Ocurrio un error leyendo a: "{}"'.format(file_path))
                execute = False

            else:

                log.logger('Enviando ...', debug.WAR)

        else:

            log.logger(
                'El archivo: "{}", no existe ...'.format(basename(file_path)),
                debug.COM)

            result = '0'
            execute = False

    elif (key == 'SHELL-EXEC'):

        result = []
        _commands = wrap.read(bot_id, 'commands', separate=True)
        _index = 0

        if not (_commands == False):

            try:

                if (len(_commands) == 0):

                    raise IndexError

                for _ in _commands:

                    if (_[0] == False):

                        result.append(_[1])

                        if (wrap.write(bot_id,
                                       'commands',
                                       True,
                                       target=wrap.TARGET_SUBINDEX_UPDATE,
                                       array_subindex=(_index, 0),
                                       separate=True) == True):

                            log.logger(
                                'No se volverá a ejecutar "{}" ...'.format(
                                    _[1]), debug.WAR)

                        else:

                            log.logger(
                                'Hubo un error actualizando los datos del comando: "{}"'
                                .format(_[1]))

                    _index += 1

            except IndexError:

                log.logger(
                    'Aún no hay comandos ingresados por parte del encargado de administrar el bot',
                    debug.WAR)

                result = (False, None)

            else:

                if (len(result) > 0):

                    log.logger('Ejecutara "{}"'.format(', '.join(result)),
                               debug.PER)

                    result = (True, result)

                else:

                    log.logger(
                        'No se puede ejecutar comandos, ya que no están disponibles!',
                        debug.WAR)

                    result = (False, None)

        else:

            log.logger(
                'Ocurrio un error leyendo los comandos de: "{}"'.format(
                    bot_id), debug.WAR)
            execute = False

    elif (key == 'addserver'):

        bot_servers = wrap.read(bot_id, 'servers', separate=True)

        if not (bot_servers == False):

            result = bot_servers
            _servers = []

            for _ in result:

                _servers.append(_[0])

            if not (len(_servers) == 0):

                log.logger(
                    'Enviando servidores secundarios: "{}"'.format(
                        ', '.join(_servers)), debug.WAR)

            else:

                log.logger('No hay servidores secundarios disponibles ...',
                           debug.WAR)
                execute = False

        else:

            log.logger(
                'Ocurrio un error leyendo los servidores secundario de: "{}"'.
                format(bot_id), debug.COM)
            execute = False

    elif (key == 'getPeers'):

        log.logger('Leyendo base de datos de los puntos ...', debug.INF)

        _data = wrap.getall(agent=wrap.USE_PEER)

        if (len(_data) > 0):

            log.logger('Enviando puntos de la red ...', debug.INF)

            result = uniqdata.uniqdata(
                list(list(_data.values())[0].values())[0])

        else:

            log.logger('Aún no hay puntos en la red ...', debug.COM)

            execute = False

    elif (key == 'addPeer'):

        if not (isinstance(value, dict)):

            log.logger(
                'El tipo de dato de los puntos a agregar no es un diccionario ...',
                debug.WAR)
            execute = False

        else:

            if (None in [
                    log.logger('{}, No está definido'.format(x), debug.WAR)
                    for x in
                ['url', 'username', 'passphrase', 'db_passwd', 'hash']
                    if (key_check_in_dict.check(value, x) == False)
            ]):

                execute = False

            else:

                _result = []
                _data = wrap.read(bot_id, 'peers', agent=wrap.USE_PEER)
                _hash = value['hash']
                _exists = value in _data if not (_data == False) else False

                log.logger(
                    'Agregando punto en la red -> {} ({})'.format(
                        value['url'], value['hash']), debug.PER)

                if (_data == False):

                    if (wrap.add(bot_id, {'peers': [value]},
                                 agent=wrap.USE_PEER) == True):

                        log.logger('Primer punto de la red agregado ...',
                                   debug.INF)

                    else:

                        log.logger(
                            'Hubo un error agregando un punto de la red por primera vez ...',
                            debug.COM)

                        execute = False

                else:

                    if (_exists == True):

                        log.logger('El punto de la red ya existe!', debug.WAR)
                        log.logger('Actualizando datos ...', debug.INF)

                    else:

                        log.logger('Nuevo punto en la red detectado ...',
                                   debug.INF)

                    _result.append(value)

                    for _ in _data:

                        if (_['hash'] == _hash):

                            log.logger(
                                'Coincidencia: "%s"; Editando ...' % (_hash),
                                debug.PER)

                            _['url'] = value['url']
                            _['db_passwd'] = value['db_passwd']
                            _['passphrase'] = value['passphrase']
                            _['username'] = value['username']

                        _result.append(_)

                    _result = uniqdata.uniqdata(_result)

                    if (wrap.add(bot_id, {'peers': _result},
                                 agent=wrap.USE_PEER) == True):

                        log.logger('Puntos escritos con éxito!', debug.INF)

                    else:

                        log.logger(
                            'Error escribiendo datos de los puntos de la red ...',
                            debug.COM)

    elif (key == 'getQueue'):

        result = wrap.read(bot_id, 'Queue', separate=True)

        if not (result == []):

            if (wrap.write(bot_id,
                           'Queue',
                           None,
                           separate=True,
                           target=wrap.TARGET_UNSET) == True):

                log.logger('¡Se reiniciaron los comandos en cola!', debug.WAR)

            else:

                log.logger(
                    'Hubo un error actualizando los comandos en cola...',
                    debug.COM)

        else:

            log.logger('Aún no hay comandos en cola', debug.WAR)

    elif (key == 'loadModule'):

        moduleName = basename(str(value)).strip()

        if not (moduleName == '') and not (re.search(r'(?=\.+)', moduleName)):

            log.logger('Va a cargar un complemento...', debug.WAR)

            # Por ahora la ruta se especifica de esta forma porque sólo es válida para arquitecturas de 32bits con SO Windows

            modulePath = '{}/{}/rook/src/init.py'.format(
                global_conf.databases['complements'], moduleName)

            log.logger('Cargando a "{}" ...'.format(modulePath), debug.PER)

            if (isfile(modulePath)):

                with open(modulePath, 'rb') as file_object:

                    result = file_object.read()

                log.logger('¡Complemento cargado!', debug.INF)

            else:

                log.logger(
                    '{}, No existe como complemento ...'.format(moduleName),
                    debug.WAR)
                execute = False

        else:

            log.logger('El nombre del complemento no es válido')
            execute = False

    elif (key == 'resultModule'):

        if (check_values.check(value, 4) == False):

            log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            log.logger('Envío un resultado de un complemento ...', debug.INF)

            config = {
                'result': value[1],
                'log': log,
                'bot_id': bot_id,
                'remote_addr': log.address,
                'function': value[2],
                'exception': value[3],
                'args': parse_args
            }

            moduleName = basename(str(value[0])).strip()
            modulePath = '{}.{}.evie.init'.format(
                global_conf.databases['complements'],
                moduleName).replace('/', '.')

            if not (moduleName == '') and not (re.search(
                    r'(?=\.+)', moduleName)):

                log.logger(
                    'Interactuando con el complemento "{}" ...'.format(
                        moduleName), debug.PER)

                try:

                    data = {}
                    mod = importlib.reload(importlib.import_module(modulePath))

                    def moduleMain(*args, **kwargs):

                        try:

                            mod.main(*args, **kwargs)

                        except Exception as Except:

                            log.logger(
                                'Ocurrio un error al ejecutar el complemento "{}". Excepción: "{}"'
                                .format(moduleName, Except), debug.WAR)

                    if (hasattr(mod, 'main') == True):

                        if not (isfunction(getattr(mod, 'main')) == True):

                            log.logger('¡main, no es una función!', debug.WAR)

                            return (False, None)

                    else:

                        log.logger('La función "main" no está definida',
                                   debug.WAR)

                        return (False, None)

                    for _ in getfullargspec(mod.main).args:

                        if not (_ in config):

                            log.logger(
                                '{} no es un parámetro válido'.format(_),
                                debug.WAR)

                            return (False, None)

                        else:

                            data[_] = config[_]

                    mod_thread = threading.Thread(
                        target=moduleMain,
                        name=generate_uniqkey.generate(),
                        kwargs=data)
                    mod_thread.start()

                except ModuleNotFoundError:

                    log.logger(
                        '¡El complemento "{}" no existe!'.format(moduleName),
                        debug.WAR)
                    execute = False

                except Exception as Except:

                    log.logger(
                        'Error importando "{}": {}'.format(moduleName, Except),
                        debug.WAR)
                    execute = False

                else:

                    log.logger(
                        'Nuevo hilo iniciado ({}) para {} ...'.format(
                            mod_thread.name, moduleName), debug.PER)

            else:

                log.logger('El nombre del complemento no es válido', debug.WAR)
                execute = False

    else:

        access = wrap.write(bot_id, 'data', data, separate=True)

        if (access == True):

            log.logger('¡Datos agregados con éxito!', debug.INF)

        else:

            log.logger(
                '¡Hubo un error desconocido al agregar datos al almacén!',
                debug.COM)
            execute = False

    return (execute, result)
Пример #5
0
                print(
                    'Limite de creación de bot\'s superados por parte de "%s" ...'
                    % (_))
                sys.exit(1)

        else:

            print(
                'Ocurrio un error analizando el siguiente administrador: "%s"'
                % (_))
            sys.exit(1)

if (bot_id.lower() == 'random'):

    bot_id = generate_uniqkey.generate()

profile_dirname = '%s/%s' % (profile, bot_id)

if (bot_id in bot_id_list):

    print('Remplazando: %s' % (bot_id))

else:

    print('Creando: %s' % (bot_id))

print(
    'La generación de claves puede tardar un siglo a un milenio, sea paciente ...'
)
Пример #6
0
if (long_ == None):

    if not (secret_key == False):

        _print('Clave secreta: %s' % (secret_key))

    else:

        _print('¡Hay un error leyendo la clave secreta!')

else:

    if (long_ >= 32):

        _print('Actualizando clave secreta ...')

        secret_key = separate_space.separate(generate_uniqkey.generate(long_))

        if (wrap.add('secret_key', {'secret_key': secret_key},
                     agent=wrap.USE_SECRET_KEY) == True):

            _print('Clave secreta actualizada: "%s"' % (secret_key))

        else:

            _print('Error actualizando la clave secreta ...')

    else:

        _print('La longitud de la clave secreta debe ser mayor o igual qué 32')
Пример #7
0
def loop_config(close=False):

    # Globals vars

    # Globals

    global conf_hash, new_conf, use_keys, init

    # Server

    global realm, LHOST, LPORT, RPATH, public_key, private_key, resolve_dns, resolve_port

    # Login

    global false_username, false_passphrase, recover, max_retry, retry_seconds, denied_method

    # honeypot

    global blacklist, honeypot_list, tools, user_agent_list, regular_expression_for_address, regular_expression_for_userAgent, re_options

    # style

    global time, logger, logs

    # templates

    global TEMPLATE_FOLDER, TEMPLATE_ERROR404, TEMPLATE_ERROR511, TEMPLATE_ERROR400, TEMPLATE_ERROR403, TEMPLATE_CREDENTIALS, webmaster_email, TEMPLATE_ERROR500

    # TOKEN SYSTEM:
    ###############

    global token, new_token

    # SECRET KEY SYSTEM:
    ####################

    global secret_key, new_secret_key

    while (True):

        try:

            # Configuration

            conf_file = wrap.getall(wrap.USE_CONFIG)

            if (conf_file == {}):

                exit_force(
                    'Aún no se escriben datos en el archivos de configuración ...'
                )

            else:

                # check config

                key_detect(dict(conf_file), [group_name])
                conf = dict(conf_file[group_name])
                new_conf_hash = sha1(str(conf).encode()).hexdigest()

                if (new_conf_hash != conf_hash):

                    conf_hash = new_conf_hash

                    # Check global config

                    key_detect(conf, [
                        'proxy', 'login', 'server', 'templates', 'honeypot',
                        'style'
                    ])

                    # Style configuration

                    style = conf['style']

                    # Check Style

                    key_detect(style, ['time', 'log'])

                    time = str(style['time'])
                    style_log = 'logs/%s' % (
                        strftime('%H.%m.%S.%d-%m-%Y.log')) if (
                            convert.convert_bool(
                                style['log']) == True) else False
                    logger = logging.logger(output=style_log, time_format=time)

                    # Server configuration

                    server = conf['server']

                    # Check Server

                    key_detect(server, [
                        'sys_version', 'server_version', 'realm', 'lhost',
                        'lport', 'rpath', 'rdns', 'rport', 'public_service',
                        'user_agent', 'nodes_rule', 'cipher_file'
                    ])

                    realm = str(server['realm'])
                    LHOST = str(server['lhost'])
                    LPORT = convert.convert_int(server['lport'])
                    BaseHTTPRequestHandler.sys_version = str(
                        server['sys_version'])
                    BaseHTTPRequestHandler.server_version = str(
                        server['server_version'])
                    RPATH = str(server['rpath'])
                    bit_size = convert.convert_int(server['bit_size'])
                    resolve_dns = convert.convert_int(server['rdns'])
                    resolve_port = convert.convert_int(server['rport'])
                    cipher_file = convert.convert_bool(server['cipher_file'])

                    # Comunicación

                    execute_command_to_admin.RULE = str(server['nodes_rule'])
                    execute_command_to_admin.cipher_file = cipher_file
                    execute_command.cipher_file = cipher_file
                    execute_command.parse_args = complements_info

                    if (re.match(r'(?!(RANDOM|STRICT))',
                                 execute_command_to_admin.RULE)):

                        execute_command_to_admin.RULE = random.choice(
                            ['STRICT', 'RANDOM'])
                        logger.log(
                            'Regla inválida; Usando "{}" como regla...'.format(
                                execute_command_to_admin.RULE), WAR)

                    execute_public_command.public_service = [
                        x.strip()
                        for x in str(server['public_service']).split(',')
                    ] if not (convert.convert_bool(server['public_service'])
                              == True) else False
                    execute_public_command.user_agent = str(
                        server['user_agent'])

                    # Proxy configuration

                    proxy = conf['proxy']

                    # Check proxy

                    key_detect(proxy, ['proxy_list'])
                    proxy_list = proxy['proxy_list']

                    if (convert.convert_bool(proxy_list)):

                        try:

                            proxy_list = convert.convert_dict(proxy_list)

                        except Exception as Except:

                            logger.log(
                                'Error parseando los datos. Excepción: {}'.
                                format(Except), COM)
                            logger.log('No se usara un proxy :/ ...', WAR)

                        else:

                            if (proxy_list.get('proxy') == None):

                                logger.log(
                                    'No configuró correctamente los valores de los proxy\'s...',
                                    WAR)

                            else:

                                current_proxy = random.choice(
                                    proxy_list['proxy'])

                                for _ in [
                                        'proxy_type', 'proxy_addr',
                                        'proxy_port', 'rds', 'username',
                                        'password'
                                ]:

                                    if (key_check_in_dict.check(
                                            current_proxy, _) == False):

                                        current_proxy = False
                                        logger.log('{} no está definido...',
                                                   WAR)
                                        break

                                if not (current_proxy == False):

                                    proxy_requirement_type = (
                                        isinstance(current_proxy['proxy_type'],
                                                   str)
                                        and current_proxy['proxy_type']
                                        in ['SOCKS4', 'SOCKS5', 'HTTP'])
                                    proxy_requirement_addr = isinstance(
                                        current_proxy['proxy_addr'], str)
                                    proxy_requirement_port = isinstance(
                                        current_proxy['proxy_port'], int)
                                    proxy_requirement_rds = isinstance(
                                        current_proxy['rds'], bool)
                                    proxy_requirement_username = (
                                        isinstance(current_proxy['username'],
                                                   str)
                                        or current_proxy['username'] == None)
                                    proxy_requirement_password = isinstance(
                                        current_proxy['password'], str
                                    ) or current_proxy['password'] == None

                                    if (proxy_requirement_addr) and (
                                            proxy_requirement_port
                                    ) and (proxy_requirement_rds) and (
                                            proxy_requirement_username) and (
                                                proxy_requirement_password):

                                        try:

                                            convex.transfor(
                                                proxy_type=socks.PROXY_TYPES.
                                                get(current_proxy['proxy_type']
                                                    ),
                                                proxy_addr='{}:{}'.format(
                                                    current_proxy[
                                                        'proxy_addr'],
                                                    current_proxy['proxy_port']
                                                ),
                                                rdns=current_proxy['rds'],
                                                username=current_proxy[
                                                    'username'],
                                                password=current_proxy[
                                                    'password'])

                                        except Exception as Except:

                                            logger.log(
                                                'No se pudo configurar el proxy. Excepcion: {}'
                                                .format(Except))

                                        else:

                                            logger.log(
                                                'Proxy: {}://{}:{}'.format(
                                                    current_proxy[
                                                        'proxy_type'],
                                                    current_proxy[
                                                        'proxy_addr'],
                                                    current_proxy['proxy_port']
                                                ), PER)

                                    else:

                                        logger.log(
                                            'Algunos tipos de datos no son correctos, por lo tanto no se puede configurar el proxy'
                                        )

                                else:

                                    logger.log(
                                        'No se puede usar un proxy, porque no está siguiendo la especificación acordada',
                                        WAR)

                    else:

                        convex.restruct()

                    # Log in configuration

                    login = conf['login']

                    # Check Log in

                    key_detect(login, [
                        'false_username', 'false_passphrase', 'recover',
                        'max_retry', 'retry_seconds', 'denied_method'
                    ])

                    max_retry = convert.convert_int(login['max_retry'])
                    retry_seconds = convert.convert_int(login['retry_seconds'])
                    denied_method = str(login['denied_method'])
                    false_username = str(login['false_username'])
                    false_passphrase = str(login['false_passphrase'])
                    recover = convert.convert_bool(login['recover'])

                    # Simple Honeypot configuration

                    simpleHoneypot = conf['honeypot']

                    # Check Simple Honeypot

                    key_detect(simpleHoneypot, [
                        'blacklist', 'honeypot_list', 'tools',
                        'user_agent_black_list',
                        'regular_expression_for_address',
                        'regular_expression_for_userAgent', 're_options'
                    ])

                    re_options = convert.convert_int(
                        simpleHoneypot['re_options'])
                    regular_expression_for_address = str(
                        simpleHoneypot['regular_expression_for_address'])
                    regular_expression_for_userAgent = str(
                        simpleHoneypot['regular_expression_for_userAgent'])
                    blacklist = str(simpleHoneypot['blacklist'])
                    honeypot_list = str(simpleHoneypot['honeypot_list'])
                    tools = str(simpleHoneypot['tools'])
                    user_agent_list = str(
                        simpleHoneypot['user_agent_black_list'])

                    # Server keys

                    _server_keys = wrap.read('keys', agent=wrap.USE_SERVER)

                    if (_server_keys == False):

                        logger.log(
                            'El par de claves aún no son son generados ... generando ...',
                            WAR)
                        logger.log('Tamaño a generar: "%d"' % (bit_size), PER)

                        _keys = generate_keys(bit_size)
                        (public_key, private_key) = (_keys['public_key'],
                                                     _keys['private_key'])

                        if (wrap.add('keys', _keys,
                                     agent=wrap.USE_SERVER) == True):

                            logger.log('El par de claves fueron generadas ...')
                            logger.log('Desencriptando ...')

                            try:

                                private_key = _decrypt_rsa_private_key._decrypt(
                                    private_key, rsa_passphrase)

                            except ValueError:

                                logger.log(
                                    'Error desencriptado la clave privada ...',
                                    COM)
                                exit_force()

                            else:

                                logger.log('¡Clave desencriptada!')

                        else:

                            logger.log(
                                'Error escribiendo las claves en el almacén ...',
                                COM)
                            exit_force()

                    else:

                        if (use_keys == True):

                            use_keys = False

                            (public_key,
                             private_key) = (_server_keys['public_key'],
                                             _server_keys['private_key'])

                            logger.log('Desencriptando clave privada ...')

                            try:

                                private_key = _decrypt_rsa_private_key._decrypt(
                                    private_key, rsa_passphrase)

                            except ValueError:

                                logger.log(
                                    'Error desencriptado la clave privada ...',
                                    COM)
                                exit_force()

                            else:

                                logger.log('Clave desencriptada con éxito.')

                    # Local information

                    templates = conf['templates']

                    # Check Local information

                    key_detect(templates, [
                        'folder', 'error400', 'error404', 'error403',
                        'error511', 'credentials', 'webmaster_email',
                        'error500'
                    ])

                    TEMPLATE_FOLDER = str(templates['folder'])
                    TEMPLATE_ERROR400 = '%s/%s' % (TEMPLATE_FOLDER,
                                                   templates['error400'])
                    TEMPLATE_ERROR404 = '%s/%s' % (TEMPLATE_FOLDER,
                                                   templates['error404'])
                    TEMPLATE_ERROR403 = '%s/%s' % (TEMPLATE_FOLDER,
                                                   templates['error403'])
                    TEMPLATE_ERROR511 = '%s/%s' % (TEMPLATE_FOLDER,
                                                   templates['error511'])
                    TEMPLATE_ERROR500 = '%s/%s' % (TEMPLATE_FOLDER,
                                                   templates['error500'])
                    TEMPLATE_CREDENTIALS = '%s/%s' % (TEMPLATE_FOLDER,
                                                      templates['credentials'])
                    webmaster_email = templates['webmaster_email']

                    # Server information

                    if (RPATH == 'RANDOM'):

                        RPATH = token_urlsafe(
                            convert.convert_int(
                                global_conf.token['path_max_length']))

                    if not (new_conf == True):

                        logger.log('Se actualizo la configuración!')

                    else:

                        new_conf = False

                _secret_key = wrap.read('secret_key',
                                        'secret_key',
                                        agent=wrap.USE_SECRET_KEY)

                if (_secret_key == False):

                    logger.log('Generando clave secreta ...')

                    secret_key = separate_space.separate(
                        generate_uniqkey.generate())
                    new_secret_key = True

                    if (wrap.add('secret_key', {'secret_key': secret_key},
                                 agent=wrap.USE_SECRET_KEY)):

                        logger.log(f'Clave secreta generada -> {secret_key}',
                                   PER)

                    else:

                        logger.log('Error generando la clave secreta ...', COM)
                        exit_force()

                else:

                    if (_secret_key != secret_key):

                        if (new_secret_key == False):

                            logger.log(f'Clave secreta -> {_secret_key}', PER)

                            new_secret_key = True

                        else:

                            logger.log(
                                f'Clave secreta actualizado -> {_secret_key}',
                                PER)

                        secret_key = _secret_key

                _token = wrap.read('token', 'token', agent=wrap.USE_TOKEN)

                if (_token == False):

                    logger.log('Generando un nuevo token de acceso ...')

                    token = generate_uniqkey.generate()
                    new_token = True

                    if (wrap.add('token', {'token': token},
                                 agent=wrap.USE_TOKEN)):

                        logger.log(f'Token de acceso generado -> {token}', PER)

                    else:

                        logger.log('Error generando el token de acceso ...',
                                   COM)
                        exit_force()

                else:

                    if (_token != token):

                        if (new_token == False):

                            logger.log(f'Token de acceso -> {_token}', PER)

                            new_token = True

                        else:

                            logger.log(f'Token actualizado -> {_token}', PER)

                        token = _token

            if (close == True):

                break

            else:

                init = True

            sleep(1)

        except Exception as Except:

            exit_force('Error en la configuración: "{}"'.format(Except))
Пример #8
0
    def do_POST(self):

        global request_count_safe

        share = False
        request_count_safe['POST'] += 1

        if (self.eject() == True): return

        content_length = self.headers['Content-Length']

        if (content_length == None):

            self.do_AUTHHEAD()
            return

        content_length = int(content_length)

        if (content_length <= 0):

            self.do_AUTHHEAD()
            return

        post_data = self.rfile.read(content_length)

        if (len(post_data) <= 0):

            self.do_AUTHHEAD()
            return

        try:

            _extract_post_data = extract_http_post_data.extract(post_data)

        except Exception as Except:

            _extract_post_data = False

        else:

            rusername = _extract_post_data.get('username')
            rpassword = _extract_post_data.get('passphrase')
            data_ = _extract_post_data.get('data')
            runiqkey = _extract_post_data.get('uniqkey')
            security_chars = _extract_post_data.get('chars')
            security_number = _extract_post_data.get('security_number')
            security_decrement_number = _extract_post_data.get(
                'decrement_number')
            security_iterations = _extract_post_data.get('iterations')
            reply = _extract_post_data.get('reply')

            if (None in [
                    rusername, rpassword, data_, runiqkey, security_chars,
                    security_number, security_decrement_number,
                    security_iterations
            ]):

                _extract_post_data = False
                evalue_exp = None

            else:

                _decipher = lambda dat: hibrid.decrypt(dat, private_key)

                try:

                    rusername = _decipher(rusername)
                    rpassword = _decipher(rpassword)
                    data_ = _decipher(data_)
                    runiqkey = _decipher(runiqkey)
                    security_chars = _decipher(security_chars)
                    security_number = _decipher(security_number)
                    security_decrement_number = _decipher(
                        security_decrement_number)
                    security_iterations = _decipher(security_iterations)
                    reply = _decipher(reply)

                except:

                    self.imprint(
                        'No se pudo desencriptar los datos por parámetros ...',
                        WAR)

                    _extract_post_data = False

                else:

                    evalue_exp = [
                        True, True, True, True, False, True, True, True, True
                    ]

        if (_extract_post_data == False):

            try:

                data = hibrid.decrypt(post_data, private_key)

            except Exception as Except:

                self.imprint(
                    'Error desencriptando datos. Intentando con el cifrado simetrico ...',
                    WAR)

                try:

                    data = simplycrypt.decrypt(token, post_data)

                    if (data == None):

                        raise

                except Exception as Except:

                    self.imprint(
                        'No se desencriptaron los datos ni con el cifrado simetrico ...',
                        COM)
                    self.do_AUTHHEAD()
                    return

                else:

                    self.imprint(
                        'Los datos fueron desencriptados, por lo tanto, se usarán en el acceso público ...',
                        INF)
                    share = True
                    evalue_exp = None

            else:

                # Credentials

                rusername = data.get('username')
                rpassword = data.get('passphrase')
                data_ = data.get('data')
                bot_id = data.get('id')
                runiqkey = data.get('uniqkey')
                security_chars = data.get('chars')
                security_number = data.get('security_number')
                security_decrement_number = data.get('decrement_number')
                security_iterations = data.get('iterations')
                reply = data.get('reply')

                # Evaluamos

                evalue_exp = list(
                    map(evalue, [
                        rusername, rpassword, runiqkey, data_, bot_id,
                        security_chars, security_number,
                        security_decrement_number, security_iterations
                    ]))

        if not (urlparse(self.path).path == '/' + RPATH):

            if (evalue_exp == [
                    False, True, False, True, True, True, True, True, True
            ]):

                if (check_credentials.check(
                        rpassword,
                        bot_id,
                        logger,
                        self.client_address,
                        max_retry,
                        retry_seconds,
                        denied_method,
                        resolve_dns,
                        iterations=security_iterations,
                        chars=security_chars,
                        decrement_number=security_decrement_number,
                        security_number=security_number)):

                    self.found200()

                    bot_information = wrap.read(bot_id, separate=True)
                    _username = bot_information['username']
                    command = hibrid.encrypt(
                        execute_command.execute(
                            data_,
                            bot_id,
                            log=debug.log(self.client_address,
                                          '%s:(%s)' % (_username, bot_id),
                                          logger, resolve_dns, resolve_port)),
                        bot_information['keys'][0])

                    self.wfile.write(command)

                else:

                    self.error403()
                    self.imprint('Quiere acceder como un bot!', COM)

            else:

                self.do_AUTHHEAD()

        else:

            if (evalue_exp == [
                    True, True, True, True, False, True, True, True, True
            ]):

                self.imprint(
                    'Verificando si las credenciales de "%s" son correctas ...'
                    % (rusername), WAR)

                if (check_administrators.check(
                        username=rusername,
                        passphrase=rpassword,
                        uniqkey=runiqkey,
                        recover=recover,
                        log=debug.log(self.client_address, rusername, logger,
                                      resolve_dns),
                        address=self.client_address,
                        max_retry=max_retry,
                        retry_seconds=retry_seconds,
                        denied_method=denied_method,
                        iterations=security_iterations,
                        chars=security_chars,
                        decrement_number=security_decrement_number,
                        security_number=security_number)):

                    self.found200()

                    admin_information = wrap.read(rusername,
                                                  agent=wrap.USE_ADMIN,
                                                  separate=True)
                    self.imprint(
                        '(%s): Actualizada la clave única de "%s" ...' %
                        (rusername, runiqkey), PER)
                    uniqkey_updated = generate_uniqkey.generate()

                    if not (wrap.write(rusername,
                                       'uniqkey',
                                       uniqkey_updated,
                                       agent=wrap.USE_ADMIN,
                                       separate=True) == True):

                        self.error500()

                        log.logger('¡No se pudo actualizar la clave única!',
                                   debug.COM)

                        return

                    self.imprint(
                        '(%s): ... A: "%s"' % (rusername, uniqkey_updated),
                        PER)
                    command = execute_command_to_admin.execute(
                        data_, rusername,
                        debug.log(self.client_address, rusername, logger,
                                  resolve_dns), evalue(reply))

                    if (command == False):

                        self.imprint('Ejecuto un comando erroneo', COM)

                        command = hibrid.encrypt(
                            (False, None, uniqkey_updated),
                            admin_information['keys'][0])

                        self.wfile.write(command)

                        return

                    command = hibrid.encrypt((True, command, uniqkey_updated),
                                             admin_information['keys'][0])

                    self.wfile.write(command)

                else:

                    self.error403()
                    self.imprint('Ingreso credenciales incorrectas!', WAR)

            elif (share == True):

                self.found200()
                command = execute_public_command.execute(
                    data,
                    debug.log(self.client_address, 'Public', logger,
                              resolve_dns))

                if (command == False):

                    self.imprint(
                        'Ejecuto un comando erroneo o hubo un error en la entrada de datos ...',
                        COM)

                self.wfile.write(simplycrypt.encrypt(token, command))

            else:

                self.error511()
Пример #9
0

def _print(string):

    print(f'[Token-Update]: {string}')


if (long_ == None):

    if not (token == False):

        _print('Token: %s' % (token))

    else:

        _print('¡Hay un error leyendo el token!')

else:

    _print('Actualizando token ...')

    token = generate_uniqkey.generate(long_)

    if (wrap.add('token', {'token': token}, agent=wrap.USE_TOKEN) == True):

        _print('Token actualizado: "%s"' % (token))

    else:

        _print('Error actualizando el token de acceso ...')
def execute(data, admin, log, reply):

    if not (check_values.check(data, 2) == True):

        log.logger(nomenclature_error, debug.WAR)

        return(False, None)

    else:

        if not (check_values.check(data[0], 2) == True):

            log.logger(nomenclature_error, debug.WAR)

            return(False, None)

    try:

        ((key, value), (use_nodes, node_headers)) = data

    except TypeError:

        ((key, value), use_nodes) = data
        node_headers = None

    if (reply == True):

        use_nodes = False

    admin = str(admin)
    limits = 1
    result = None
    execute = True
    error = False

    if (check_privileges.check(admin, key) == False):

        return(False, (-1, log.logger('No tiene permiso o hace falta el siguiente privilegio: "%s"' % (key), debug.COM)))

    if not (use_nodes == False):

        log.logger('Usará a Evie como el nodo de entrada ...', debug.WAR)

        if (check_privileges.check(admin, 'useNodes') == False):

            return(False, (False, log.logger('No tiene permiso de usar a Evie como el nodo de inicio ...', debug.WAR)))

        # - - - - - - - - - - - - - - - - - - - -  - - -

        try:

            check_headers.check(node_headers)

        except check_headers.InvalidHeader:

            return(False, (False, log.logger('El encabezado no es válido para la petición ...', debug.WAR)))

        nodes = wrap.read(use_nodes, 'list', agent=wrap.USE_NODE)

        if (nodes == False):

            return(False, (False, log.logger('No se encontró nodos disponibles a partir del (id)entificador proporcionado', debug.WAR)))

        wrap_nodes = {}
        end_node = nodes[-1]
        nodes_order = nodes[:-1]
        if (RULE == 'RANDOM'):
            shuffle(nodes_order)
        nodes = nodes_order + [end_node]
        node_rule = 0
        secrets_keys = [x[2] for x in nodes[:-1]]

        for _ in nodes:

            if (_[0] == nodes[0][0]):

                wrap_nodes[None] = [0, None, None]
                _first_node_url = _[0]
                _first_node_token = _[1]

                continue

            secret_key = secrets_keys[node_rule]

            if not (_[0] == end_node[0]):

                wrap_nodes[simplycrypt.encrypt(secret_key, _[0])] = [1, simplycrypt.encrypt(secret_key, _[1]), sha1(_[0].encode()).hexdigest()]
        
            else:
                
                wrap_nodes[simplycrypt.encrypt(secret_key, _[0])] = [1, None, sha1(_[0].encode()).hexdigest()]

            node_rule += 1

        _cipher = lambda string: hibrid.encrypt(string, end_node[4])

        _construct = {}
        _construct['username'] = end_node[1]
        _construct['passphrase'] = end_node[2]
        _construct['uniqkey'] = end_node[3]
        _construct['iterations'] = end_node[5]
        _construct['security_number'] = end_node[6]
        _construct['decrement_number'] = end_node[7]
        _construct['chars'] = end_node[8]
        _construct['data'] = _cipher(((key, value), False))
        _construct['reply'] = _cipher('1')
        
        response = connector.connect(_first_node_url, _first_node_token, 'resend', (wrap_nodes, _construct), log, headers=node_headers)
        response = str(response) if (response == None) else response

        if (response == False):

            log.logger('¡Ocurrio un error con la respuesta!', debug.WAR)

        else:

            log.logger('Recibido (lon:%d) ... mandando respuesta final ...' % (len(response)), debug.INF)
        
        return(response)
    
    if (key == 'listBots'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            log.logger('Mandando lista de rook\'s ...', debug.INF)

            users = {}
            end_limit = check_int.check(value[0])
            pattern = str(value[1])

            if not (end_limit == None):

                log.logger('Indexando rook\'s ...', debug.INF)

                for bot_id, bot_name in enum_bots.enum(admin, False):

                    if (re.search(pattern, bot_name, re.IGNORECASE)):

                        users[bot_id] = bot_name
                    
                    if (limits == end_limit):

                        break
                    
                    limits += 1

                if (len(users) == 0):

                    log.logger('¡No se obtuvo ninguna coincidencia!', debug.WAR)

                else:

                    log.logger('Mandando "%d" rook\'s ...' % (len(users)), debug.PER)
                
                result = users

            else:

                result = log.logger(convert_int_error.format(value), debug.WAR)
                execute = False

    elif (key == 'getData'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            log.logger('Mandando datos ...', debug.INF)
            
            bot_id = str(value[0])
            end_limit = check_int.check(value[1])

            if not (end_limit == None):

                if (admin_in_bot.check(admin, bot_id)):

                    log.logger('Mandando datos de: "{}" ...'.format(bot_id), debug.PER)

                    result = listOrder(bot_id, 'data', end_limit)

                else:

                    result = log.logger('No tiene permisos para obtener los datos de "{}"'.format(bot_id), debug.WAR)
                    execute = False

            else:

                result = log.logger(convert_int_error.format(value[1]), debug.WAR)
                execute = False

    elif (key == 'getCommands'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            log.logger('Mandando comandos ...', debug.INF)

            bot_id = str(value[0])
            end_limit = check_int.check(value[1])

            if not (end_limit == None):

                if (admin_in_bot.check(admin, value[0])):

                    log.logger('Mandando comandos de: "{}"'.format(bot_id), debug.PER)

                    result = listOrder(bot_id, 'commands', end_limit)

                else:

                    result = log.logger('No tiene permisos para obtener los comandos de "{}"'.format(bot_id), debug.WAR)
                    execute = False

            else:

                result = log.logger(convert_int_error.format(value[1]), debug.WAR)
                execute = False

    elif (key == 'executeCommand'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            bot_id = str(value[0])
            _cmd = str(value[1])

            log.logger('Agregará un comando a ser ejecutado por: "{}"'.format(bot_id), debug.PER)

            if (admin_in_bot.check(admin, bot_id)):

                # [False, command], donde "False", qué quiere decir que aún no se ejecuta ese comando

                if (wrap.write(bot_id, 'commands', [False, _cmd], separate=True) == True):

                    result = log.logger('Se agrego el comando: "{}"'.format(_cmd), debug.PER)
            
                else:

                    result = log.logger('Error agregando el comando "{}" a "{}"'.format(_cmd, bot_id), debug.COM)
                    execute = False

            else:

                result = log.logger('No tiene permiso de agregarle "{}" a "{}" ...'.format(_cmd, bot_id), debug.WAR)
                execute = False

    elif (key == 'shareBot'):
        
        if (check_values.check(value, 5) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            bot_id = str(value[0])
            _secundaryServerAddr = str(value[1])
            _api_key = str(value[2])
            _headers = value[3]
            _shareFiles = bool(value[4])

            try:

                check_headers.check(_headers)

            except check_headers.InvalidHeader:

                result = log.logger('El encabezado no es válido para la petición ...', debug.WAR)
                execute = False

            else:

                if (check_url.check(_secundaryServerAddr, log) == False):

                    log.logger('Se va a compartir el rook: "{}" para el siguiente servidor: "{}"'.format(bot_id, _secundaryServerAddr), debug.WAR)

                    if (admin_in_bot.check(admin, bot_id)):
                        
                        response = sharebot.share(bot_id, _secundaryServerAddr, _api_key, _headers, _shareFiles, log)

                        if (response == True):

                            log.logger('Agregando servidor secundario a :: "{}"'.format(bot_id), debug.WAR)

                            _secundaryServers = wrap.read(bot_id, 'servers', separate=True)
                            _server = '%s://%s/' % (urlparse(_secundaryServerAddr).scheme, urlparse(_secundaryServerAddr).netloc)
                           
                            if not (_server in _secundaryServers):

                                _obj = wrap.getall(wrap.USE_TMP)

                                _hash_server = sha1(_secundaryServerAddr.encode()).hexdigest()

                                if not (_obj.get(_hash_server) == None):

                                    if (wrap.write(bot_id, 'servers', [_server, _obj[_hash_server]['pub_key']], separate=True) == True):

                                        result = log.logger('Agregado, servidor secundario: "{}" a "{}"'.format(_server, bot_id), debug.PER)

                                    else:


                                        execute = False
                                        result = log.logger('Error agregando el servidor secundario: "{}"'.format(_server), debug.COM)

                                else:


                                    execute = False
                                    result = log.logger('Hubo un error, no se pudo obtener la clave pública del servidor secundario: "{}"'.format(_server), debug.COM)

                            else:

                                execute = False
                                result = log.logger('¡El servidor secundario ya existe!', debug.WAR)

                        else:

                            result = log.logger('Ocurrio un error enviando el rook: "{}"'.format(response[1]), debug.WAR)
                            execute = False

                    else:

                        result = log.logger('No tiene permisos para compartir el siguiente rook "{}"'.format(bot_id), debug.WAR)
                        execute = False

                else:

                    result = log.logger('La dirección del servidor secundario no es correcta ...', debug.WAR)
                    execute = False

    elif (key == 'getToken'):
        
        log.logger('Compartiendo el token de acceso público ...', debug.INF)
        
        result = wrap.read('token', 'token', agent=wrap.USE_TOKEN)

    elif (key == 'listServers'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            log.logger('Mandando lista de servidores secundarios ...', debug.INF)

            bot_id = str(value[0])
            end_limit = check_int.check(value[1])
            
            if not (end_limit == None):

                if (admin_in_bot.check(admin, bot_id)):
                    
                    log.logger('Enviado, lista de servidores secundarios', debug.INF)

                    result = []
                    _dat = listOrder(bot_id, 'servers', end_limit)

                    [result.append(x[0]) for x in _dat]

                else:

                    result = log.logger('No tiene permiso para obtener los servidores secundarios de "{}"'.format(bot_id), debug.WAR)
                    execute = False

            else:

                result = log.logger(convert_int_error.format(value[1]))
                execute = False

    elif (key == 'delServer'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            log.logger('Borrara un servidor secundario ...', debug.WAR)
            
            bot_id = str(value[0])
            _index = check_int.check(value[1], False)
            
            if (_index == None):

                result = log.logger('{}, No es un indíce correcto'.format(value[1]), debug.WAR)
                execute = False

            else:

                if (admin_in_bot.check(admin, bot_id)):

                    try:

                        secundaryServer = wrap.read(bot_id, 'servers', separate=True)[_index]

                        if (wrap.write(bot_id, 'servers', _index, target=wrap.TARGET_DELETE_INDEX, separate=True) == True):

                            result = log.logger('Borro el servidor secundario: "{} - (indíce:{})"'.format(secundaryServer[0], _index), debug.COM)

                        else:

                            result = log.logger('No se puede borrar el servidor secundario ...', debug.WAR)
                            execute = False

                    except IndexError:

                        result = log.logger('Es probable que el indíce proporcionado no sea correcta para la operación ...', debug.COM)
                        execute = False

                else:

                    result = log.logger('No tiene permiso para borrar el servidor secundario de "{}"'.format(bot_id), debug.WAR)
                    execute = False

    elif (key == 'writeNodes'):

        log.logger('Escribirá nodos ...', debug.WAR)
        log.logger('Comprobando que siga la especificación acordada ...', debug.WAR)
        log.logger('Comprobando el tipo de dato ...', debug.INF)

        if not (isinstance(value, list)):

            error = True 
            log.logger('El tipo de dato no es correcto ...', debug.WAR)

        else:

            log.logger('El tipo de dato es correcto', debug.INF)

            if (len(value) < 2):

                error = True
                result = log.logger('¡La longitud de los nodos no es correcta!', debug.WAR)

            else:

                log.logger('La longitud de los nodos es correcta', debug.INF)

                _init_node = value[:-1]
                _end_node = value[-1]

                if not (isinstance(_init_node, list)) or not (isinstance(_end_node, list)):

                    error = True
                    log.logger('¡El tipo de dato de los nodos intermedios o del nodo final no es correcta!', debug.WAR)

                else:

                    if not (len(_init_node) >= 1):

                        error = True
                        log.logger('¡La longitud de los nodos intermedios no es correcta!', debug.WAR)

                    else:

                        log.logger('Comprobando longitud de los nodos intermedios individualmente ...', debug.INF)

                        if not ([] == [log.logger('¡La longitud de {} no es correcta!'.format(x), debug.WAR) for x in _init_node if (len(x) != 3)]):

                            error = True
                            result = log.logger('La longitud de un nodo intermedio no es correcta ...', debug.WAR)

                        else:

                            log.logger('La longitud de los nodos intermedios es correcta', debug.INF)
                            log.logger('Comprobando las direcciónes de los nodos intermedios ...', debug.WAR)

                            for i, _ in enumerate(_init_node):

                                log.logger('Comprobando dirección: {}'.format(_[0]), debug.WAR)

                                _url = value[i][0] = str(_[0])
                                value[i][1] = str(_[1]) 

                                error = check_url.check(_url, log)

                                if (error == True):

                                    break

                            if (error == False):

                                log.logger('Comprobando longitud del nodo final  ...', debug.WAR)

                                if not (len(_end_node) == 9):

                                    error = True
                                    result = log.logger('La longitud del nodo final no es correcta ...', debug.WAR)

                                else:

                                    log.logger('La longitud del nodo final es correcta', debug.INF)
                                    log.logger('Comprobando que no haya campos vacios ...', debug.WAR)

                                    if (True in [True for x in _end_node if (x == '')]):

                                        error = True
                                        result = log.logger('Hay campos sin definir ...', debug.WAR)

                                    else:

                                        log.logger('Comprobando la dirección del nodo final: {}'.format(_end_node[0]), debug.WAR)

                                        error = check_url.check(_end_node[0], log)

        if (error == False):

            log.logger('¡Comprobación exitosa!', debug.INF)

            _nodes = []
            log.logger('Generando (id)entificador del nodo ...', debug.INF)
            _node_id = generate_uniqkey.generate()
            log.logger('Generado: %s' % (_node_id), debug.PER)

            [_nodes.append(x[0]) for x in value]

            log.logger('Escribiendo nodos "%s" en el almacén' % (' -> '.join(_nodes)), debug.PER)

            if (wrap.add(_node_id, {'list':value}, agent=wrap.USE_NODE) == True):

                log.logger('Nodos escritos correctamente (ID:{})'.format(_node_id), debug.PER)

                result = _node_id

            else:

                result = log.logger('No se pudo escribir los nuevos nodos (ID:{})'.format(_node_id), debug.WAR)
                execute = False

        else:

            execute = False

    elif (key == 'addNode'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            node_id = str(value[0])
            node = value[1]

            if not (isinstance(node, list)):

                result = log.logger('¡El tipo de dato del nodo no es correcto!', debug.WAR)
                execute = False

            else:

                if (len(node) != 3):

                    result = log.logger('La longitud del nodo no es correcta', debug.WAR)
                    execute = False

                else:

                    if (check_url.check(node[0], log) == True):

                        result = log.logger('¡La dirección URL no es válida!', debug.WAR)
                        execute = False

                    else:

                        if (wrap.write(node_id, 'list', node, agent=wrap.USE_NODE, target=wrap.TARGET_INSERT, index_insert=-1) == True):

                            result = log.logger('Nuevo nodo agregado: {} (ID:{})'.format(node[0], node_id), debug.PER)

                        else:

                            result = log.logger(log.logger('No se pudo agregar al nodo: "{}" (ID:{})'.format(node[0], node_id)), debug.COM)
                            execute = False

    elif (key == 'getNodes'):

        action = str(value)

        if (action.lower() == 'all'):

            log.logger('Obteniendo datos de todos los nodos', debug.INF)

            result = wrap.getall(agent=wrap.USE_NODE)

        else:

            log.logger('Obteniendo datos del nodo -> {}'.format(action), debug.PER)

            result = wrap.read(action, 'list', agent=wrap.USE_NODE)

        if not (result == False):

            log.logger('Enviando los datos de los nodos ...', debug.INF)

        else:

            result = log.logger('Error enviando los datos de los nodos', debug.COM)
            execute = False

    elif (key == 'delNodes'): 

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            node = str(value[0])
            action = str(value[1])

            log.logger('Borrara nodos ...', debug.WAR)

            if (str(action).lower() == 'all'):

                log.logger('Borrando los nodos del ID: "{}"'.format(node), debug.COM)

                if (wrap.delete(node) == True):

                    result = log.logger('Borrado, todos los nodos de "{}"'.format(node), debug.WAR)

                else:

                    result = log.logger('Error borrando: "{}"'.format(node), debug.WAR)
                    execute = False
        
            else:

                _index = check_int.check(action, False)

                if not (_index == None):

                    log.logger('Verificando que haya minimo, un nodo intermedio y el nodo final, para evitar un borrado peligroso ...', debug.WAR)

                    _nodes = wrap.read(node, 'list', agent=wrap.USE_NODE)

                    if not (_nodes == False):

                        if (len(_nodes) > 2):
                            
                            if not (_index == -1) and not (_index == len(_nodes)-1):

                                _node_to_delete = _nodes[_index][0]

                                log.logger('Borrando el nodo -> {} (ID:{})'.format(_node_to_delete, node), debug.COM)

                                if (wrap.write(node, 'list', action, agent=wrap.USE_NODE, target=wrap.TARGET_DELETE_INDEX) == True):

                                    result = log.logger('Borrado: "{}" (ID:{})'.format(_node_to_delete, node), debug.WAR)

                                else:

                                    result = log.logger('Error borrando "{}" (ID:{})'.format(_node_to_delete, node), debug.COM)
                                    execute = False

                            else:

                                result = log.logger('¡No se puede borrar el nodo final!', debug.WAR)
                                execute = False

                        else:

                            result = log.logger('No puede borrar nodos, mientras haya solamente un nodo intermedio', debug.WAR)
                            execute = False

                    else:

                        result = log.logger('¡No existe el nodo especificado!', debug.WAR)
                        execute = False

                else:

                    result = log.logger(convert_int_error.format(action), debug.WAR)
                    execute = False

    elif (key == 'updateNode'):
        
        if (check_values.check(value, 4) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            node_id = str(value[0])
            value_ = str(value[1])
            _index = check_int.check(value[2], False)
            _subindex = check_int.check(value[3], False)

            if (_index == None):

                error = True

                result = log.logger('{}, No es un indíce correcto'.format(_index), debug.WAR)

            if (_subindex == None):

                error = True

                result = log.logger('{}, No es un sub-indíce correcto'.format(_subindex), debug.WAR)

            if (error == False):

                log.logger('Actualizando nodo: "ID:{}"'.format(node_id), debug.PER)

                _get_nodes = wrap.read(node_id, 'list', agent=wrap.USE_NODE)[-1]

                if (_index == -1) or (_index == len(_get_nodes)-1):

                    if (_subindex != 0):

                        return(False, log.logger('No puedes actualizar ningún dato del nodo final al menos que sea la dirección URL', debug.WAR))

                if (_subindex == 0):

                    log.logger('Actualizará la dirección URL de un nodo...', debug.WAR)

                    if (check_url.check(value_, log) == True):

                        return(False, log.logger('La dirección URL no es válida', debug.WAR))

                if (wrap.write(node_id, 'list', value_, agent=wrap.USE_NODE, target=wrap.TARGET_SUBINDEX_UPDATE, array_subindex=(_index, _subindex)) == True):

                    result = log.logger('Nodo (ID:{}) actualizado con éxito'.format(node_id), debug.PER)

                else:

                    result = log.logger('Error actualizando el nodo: "ID:{}"'.format(node_id), debug.COM)
                    execute = False

            else:

                execute = False

    elif (key == 'access_list'):

        log.logger('Enviando lista de las fechas de inicio de sesión ..."', debug.INF)

        end_limit = check_int.check(value)

        if not (end_limit == None):
        
            result = listOrder(admin, 'lastLogin', end_limit, agent=wrap.USE_ADMIN)

        else:

            result = log.logger(convert_int_error.format(value))
            execute = False

    elif (key == 'ping'):

        log.logger('ping ... haciendo pong ...', debug.INF)

    elif (key == 'getPeers'):

        log.logger('Obtendrá todos los puntos de la red ...', debug.WAR)

        result = wrap.getall(wrap.USE_PEER)

        if (len(result) == 0):

            result = log.logger('Aún no hay nodos en la red...', debug.WAR)
            execute = False

        else:

            log.logger('Mandando %d puntos ...' % (len(result)), debug.PER)

    elif (key == 'upload'):

        if (check_values.check(value, 3) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            _content = value[0]
            _filename = os.path.basename(str(value[1]))
            bot_id = os.path.basename(str(value[2]))

            if (admin_in_bot.check(admin, bot_id)):

                _save = '%s/%s' % (share_folder, bot_id)

                create_folder.create(_save)

                _save += '/%s' % (_filename)

                log.logger('Escribiendo archivo "{}" ...'.format(_save), debug.PER)

                _bak_save = rename_order.rename(_save)

                if not (_bak_save == False):

                    log.logger('El archivo ya existe ...', debug.WAR)

                    _save = _bak_save

                    log.logger('Renombrado a: "{}"'.format(_save), debug.PER)

                try:

                    if (cipher_file == True):

                        wrap_file.wrap(_save, wrap._new_passwd, _content)

                    else:

                        with open(_save, 'wb') as file_object:

                            file_object.write(bytes_convert.convert(_content))

                except Exception as Except:

                    result = log.logger('Ocurrio una excepción escribiendo a: "{}". Excepción: "{}"'.format(_filename, Except), debug.WAR)
                    execute = False

                else:

                    result = log.logger('El archivo "{}" fue subido satisfactoriamente ...'.format(_filename), debug.PER)

            else:

                result = log.logger('No tiene permiso para subir el archivo "{}" a el espacio de directorio de "{}"'.format(_filename, bot_id), debug.COM)
                execute = False

    elif (key == 'download'):

        if (check_values.check(value, 2) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            _filename = os.path.basename(str(value[0]))
            bot_id = os.path.basename(str(value[1]))

            if (admin_in_bot.check(admin, bot_id)):
            
                _save = '{}/{}/{}'.format(profile_folder, bot_id, _filename)
                
                log.logger('Quiere recuperar el archivo: "{}" ...'.format(_save), debug.PER)

                if (os.path.isfile(_save)):

                    log.logger('Leyendo archivo ...', debug.INF)

                    try:

                        if (cipher_file == True):

                            result = wrap_file.wrap(_save, wrap._new_passwd)

                            if (result == False):

                                log.logger('{}, no se pudo desencriptar..., Intentando sin desencriptar...'.format(_save), debug.WAR)

                        if (result == False) or (cipher_file == False):

                            with open(_save, 'rb') as file_object:

                                result = file_object.read()

                    except Exception as Except:

                        result = log.logger('Ocurrio una excepción leyendo a: "{}". Excepción: "{}"'.format(_filename, Except), debug.WAR)
                        execute = False

                    else:

                        log.logger('Leido.', debug.INF)
                        log.logger('Enviando archivo: "{}" ...'.format(_save), debug.PER)

                else: 

                    result = log.logger('El archivo "{}" no existe ...'.format(os.path.basename(_save)), debug.WAR)
                    execute = False

            else:

                result = log.logger('No tiene permiso para descargar el archivo "{}" de "{}"'.format(os.path.basename(_save), value[1]), debug.COM)
                execute = False

    elif (key == 'sharedFiles'):

        if (check_values.check(value, 3) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            _bot_id = os.path.basename(str(value[0]))
            end_limit = check_int.check(value[1])
            pattern = str(value[2])
            _files = '{}/{}'.format(share_folder, _bot_id)

            log.logger('Mandando lista de archivos compartidos de "{}"'.format(_bot_id), debug.WAR)

            if not (end_limit == None):

                if (os.path.isdir(_files)):

                    result = []

                    for _ in listLimit.list_(sorted(os.listdir(_files)), end_limit):

                        result.append(_) if (re.search(pattern, _, re.IGNORECASE)) else None

                    if (len(result) == 0):

                        log.logger('¡No se obtuvo ninguna coincidencia!', debug.WAR)

                    else:

                        log.logger('Mandado %d archivos ...' % (len(result)), debug.PER)

                else:

                    result = log.logger('No se ha creado el directorio compartido de: "{}"'.format(_bot_id), debug.WAR)
                    execute = False

            else:

                result = log.logger(convert_int_error.format(value[1]), debug.WAR)
                execute = False

    elif (key == 'listFiles'):

        if (check_values.check(value, 3) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:
        
            _bot_id = os.path.basename(str(value[0]))
            _files = '{}/{}'.format(profile_folder, _bot_id)
            end_limit = check_int.check(value[1])
            pattern = str(value[2])

            log.logger('Mandando lista de archivos de "{}"'.format(_bot_id), debug.WAR)
            
            if not (end_limit == None):

                if (os.path.isdir(_files)):

                    result = []

                    for _ in listLimit.list_(sorted(os.listdir(_files)), end_limit):

                        result.append(_) if (re.search(pattern, _, re.IGNORECASE)) else None

                    if (len(result) == 0):

                        log.logger('¡No se obtuvo ninguna coincidencia!', debug.WAR)

                    else:

                        log.logger('Mandando %d archivos ...' % (len(result)), debug.PER)

                else:

                    result = log.logger('El directorio de perfil de "{}" no existe ...'.format(_bot_id), debug.COM)
                    execute = False

            else:

                result = log.logger(convert_int_error.format(value[1]), debug.WAR)
                execute = False

    elif (key == 'addQueue'):

        if (check_values.check(value, 3) == False):

            result = log.logger(nomenclature_error, debug.WAR)
            execute = False

        else:

            _bot_id = str(value[1])
            _command = str(value[0])
            _args = value[2]

            if (isinstance(_args, dict)):

                log.logger('Agregará un comando del sistema a la cola de: "{}"'.format(_bot_id), debug.PER)

                if (admin_in_bot.check(admin, _bot_id)):

                    if (wrap.write(_bot_id, 'Queue', [_command, _args], separate=True) == True):

                        result = log.logger('Se agregó "{}" a la cola ...'.format(_command), debug.PER)
                
                    else:

                        result = log.logger('Error agregando el comando del sistema "{}" a "{}"'.format(_command, _bot_id), debug.COM)
                        execute = False

                else:

                    result = log.logger('No tiene permiso de agregarle "{}" a "{}" ...'.format(_command, _bot_id), debug.WAR)
                    execute = False

            else:

                result = log.logger('¡El tipo de dato de los parámetros no es correcto!', debug.WAR)
                execute = False

    else:

        return(False)

    return(execute, result)
Пример #11
0
        print(
            'Es la primera vez que se creará un administrador ... Convirtiéndolo en *root* ...'
        )
        root = True

    print('Configurando valores ...')

    wrap.add(username, {
        'root':
        root,
        'passphrase':
        db_hash.hash(passphrase, iterations, security_chars, security_number,
                     decrement_number),
        'uniqkey':
        generate_uniqkey.generate(),
        'lastLogin': [],
        'lastUniqkey':
        None,
        'privileges':
        privileges,
        'keys':
        rsa.export(),
        'max_bot':
        max_bot,
        'iterations':
        iterations,
        'securityNumber':
        security_number,
        'security_chars':
        security_chars,
Пример #12
0
def execute(data, log):

    if not (isinstance(data, dict)):

        log.logger('¡El tipo de dato de los datos no es correcto!', debug.WAR)
        return (False)

    if (len(data) != 2):

        log.logger('¡La longitud de los datos no es correcta!', debug.WAR)
        return (False)

    if (data.get('token') == None) or (data.get('command') == None):

        log.logger('¡Hace falta el token o el comando!', debug.WAR)
        return (False)

    _keys = wrap.read('keys', agent=wrap.USE_SERVER)

    if (_keys == False):

        log.logger('No se pudo leer el par de claves de Evie...', debug.COM)
        return (False)

    (pub_key, priv_key) = (_keys['public_key'], _keys['private_key'])
    real_token = wrap.read('token', 'token', agent=wrap.USE_TOKEN)
    real_secret_key = wrap.read('secret_key',
                                'secret_key',
                                agent=wrap.USE_SECRET_KEY)

    if (real_token == False):

        log.logger('No se pudo leer el token de acceso...', debug.COM)
        return (False)

    token = data['token']

    if not (isinstance(token, str)):

        log.logger('El tipo de dato del token de acceso no es correcto...',
                   debug.WAR)
        return (False)

    if (token == real_token):

        log.logger('Correcto, el token de acceso es correcto ...', debug.INF)

    else:

        log.logger('Incorrecto, el token de acceso es incorrecto ...',
                   debug.COM)
        return (False)

    (key, value) = data['command']

    if not (isinstance(key, str)):

        log.logger('¡El tipo de dato del comando o el valor no es correcto!',
                   debug.WAR)
        return (False)

    if not (public_service == False):

        if not (key in public_service):

            log.logger(
                '%s, No está habilitado en estos momentos o no existe ...' %
                (key), debug.WAR)
            return (False)

    if (key == 'getPubKey'):

        log.logger('Desea obtener la clave pública del servidor ...',
                   debug.WAR)

        return (pub_key)

    elif (key == 'saveData'):

        log.logger('Construyendo perfil de un rook ...', debug.INF)

        if not (isinstance(value, list)):

            log.logger('¡El tipo de dato no es correcto!', debug.WAR)

            return (False)

        if (len(value) != 2):

            log.logger('La longitud de los datos no es correcta', debug.WAR)

            return (False)

        if not (isinstance(value[0], dict)) or not (isinstance(value[1],
                                                               dict)):

            log.logger(
                'El tipo de dato de la información del rook o los archivos de él, no es correcto',
                debug.WAR)

            return (False)

        (bot_id, bot_data) = tuple(value[0].items())[0]

        if not (isinstance(bot_data, dict)):

            log.logger(
                'El tipo de dato de la información del rook no es correcto',
                debug.WAR)

            return (False)

        for _ in global_conf.keys_bot:

            if (key_check_in_dict.check(bot_data, _) == False):

                log.logger(
                    'No está definido la clave "{}" en la información del rook'
                    .format(_), debug.WAR)

                return (False)

        profile_dir = '{}/{}/{}/{}'.format(getcwd(),
                                           global_conf.databases['database'],
                                           global_conf.databases['profiles'],
                                           bot_id)

        if not isdir(profile_dir):

            makedirs(profile_dir)

            log.logger('Creado, el directorio de perfil: "%s"' % (profile_dir),
                       debug.PER)

        bot_data['profile'] = profile_dir
        bot_data['admins'] = real_extract_root_administrators.extract()

        if (bot_id in show_user_rooks.show()):

            log.logger(
                'No se puede almacenar los datos de "%s" en el almacén, porque ya existe'
                % (bot_id), debug.WAR)

            return (False)

        log.logger('Almacenando datos de "%s" en el almacén ...' % (bot_id),
                   debug.PER)

        if (wrap.add(bot_id, bot_data, username=bot_id,
                     separate=True) == True):

            log.logger(
                'Se almacenaron los datos de "%s" con éxito.' % (bot_id),
                debug.PER)

            if not (value[1] == {}):

                log.logger('Almacenando archivos ...', debug.INF)

                for filename, content_file in value[1].items():

                    filename = '%s/%s' % (profile_dir, basename(filename))

                    _bak_filename = rename_order.rename(filename)

                    if not (_bak_filename == False):

                        filename = _bak_filename

                    log.logger('Escribiendo: "%s" ...' % (filename), debug.PER)

                    try:

                        with open(filename, 'wb') as _obj:

                            _obj.write(bytes_convert.convert(content_file))

                    except Exception as Except:

                        log.logger(
                            'Error escribiendo: {}. Excepción: {}'.format(
                                filename, Except), debug.COM)

                    else:

                        log.logger('Escrito: "%s"' % (filename), debug.PER)

            return (True)

        else:

            log.logger('No se guardaron los datos en el almacén ... ')

            return (False)

    elif (key == 'resend'):

        if (len(value) != 2):

            log.logger(
                '¡La longitud de los datos de los nodos no es correcta!',
                debug.WAR)
            return (False)

        (nodes, reply) = value

        if not (isinstance(reply, dict)):

            log.logger(
                '¡El tipo de dato de la réplica de los datos no es correcto!',
                debug.WAR)
            return (False)

        if (len(reply) != 9):

            log.logger(
                '¡La longitud de la réplica de los datos no es correcta!',
                debug.WAR)
            return (False)

        for _ in [
                'username', 'passphrase', 'uniqkey', 'iterations',
                'security_number', 'decrement_number', 'chars', 'data', 'reply'
        ]:

            if (key_check_in_dict.check(reply, _) == False):

                log.logger('¡{}, No está incluida en la réplica!'.format(_),
                           debug.WAR)
                return (False)

        if not (isinstance(nodes, dict)):

            log.logger(
                '¡El tipo de dato de los nodos intermedios no es correcto!',
                debug.WAR)
            return (False)

        if not (len(nodes) >= 2):

            log.logger('¡La longitud de los nodos no es correcta!', debug.WAR)
            return (False)

        check_nodes = [nodes[x] for x in nodes]

        if not ([] == [None for x in check_nodes if (len(x) != 3)]):

            log.logger('¡La longitud de un intermedio no es correcta!',
                       debug.WAR)
            return (False)

        if (check_nodes[0][0] != 0):

            log.logger('¡No se puede enviar datos al nodo inicial!', debug.WAR)
            return (False)

        nodes_list = list(nodes)

        for _key, _value in nodes.items():

            (_init, _token, url_sum) = _value

            if not (isinstance(_init, int)):

                log.logger('¡El tipo de dato del indicador no es correcto!',
                           debug.WAR)
                return (False)

            if (_init > 1) or (_init < 0):

                log.logger('¡El indicador no es correcto!', debug.WAR)
                return (False)

            if (_init == 1):

                nodes[_key][0] = 0
                break

        try:
            _key = simplycrypt.decrypt(real_secret_key, _key)

        except:

            log.logger(
                '¡Error desencriptando la dirección URL del siguiente nodo!',
                debug.COM)
            return (False)

        if (len(url_sum) != 40):

            log.logger(
                '¡La longitud de la suma de verificación de la URL no es correcta!',
                debug.WAR)
            return (False)

        end_point = nodes[nodes_list[-1]][-1]

        if not (url_sum == end_point):

            try:

                _token = simplycrypt.decrypt(real_secret_key, _token)

            except:

                log.logger(
                    '¡Error desencriptando el token de acceso de "{}"!'.format(
                        _key), debug.WAR)
                return (False)

            log.logger('Enviando datos al siguiente nodo -> %s' % (_key),
                       debug.PER)

            _data = connector.connect(_key,
                                      _token,
                                      'resend', (nodes, reply),
                                      log,
                                      headers={'User-Agent': user_agent})

            log.logger('Re-enviado ...', debug.INF)

        else:

            log.logger('Re-enviando datos al nodo final -> "%s"' % (_key),
                       debug.PER)

            try:

                _data = requests.post(_key,
                                      data=reply,
                                      timeout=global_conf.connector['timeout'],
                                      verify=False,
                                      headers={
                                          'User-Agent': user_agent
                                      }).content

            except Exception as Except:

                _data = str(Except)

                log.logger('Ocurrio una excepción: "%s"' % (Except), debug.WAR)

            else:

                log.logger('Los datos se re-enviaron satisfactoriamente ...',
                           debug.INF)

        return (_data)

    elif (key == 'sendSOS'):

        log.logger('Envió un mensaje ...', debug.INF)
        log.logger('Gurdando ...', debug.INF)

        if not (isinstance(value, dict)):

            log.logger(
                '¡No está siguiendo la especificación para almacenar mensajes!',
                debug.WAR)

            return (False)

        for _ in ['nickname', 'subject', 'message', 'files']:

            if (value.get(_) == None):

                log.logger('Falta definir: "%s"' % (_), debug.WAR)

                return (False)

        nickname = str(value['nickname'])
        subject = str(value['subject'][:98])
        message = str(value['message'])

        for _ in [nickname, subject, message]:

            if (_.strip() == ''):

                log.logger('¡Hay campos vacios!', debug.WAR)

                return (False)

        time_ = time()
        _files = value['files']
        _folder = None

        if not (isinstance(_files, list)):

            log.logger('¡El tipo de dato de los archivos no es correcto!',
                       debug.WAR)

            return (False)

        _message_id = generate_uniqkey.generate()

        log.logger('ID: %s' % (_message_id), debug.PER)

        if not (_files == []):

            _folder = '%s/%s' % (public_files, _message_id)

            create_folder.create(_folder)

            for _ in _files:

                if (len(_) != 2):

                    log.logger('¡La longitud de la tupla no es correcta!',
                               debug.WAR)

                    return (False)

                (_filename, _content) = _
                _filename = basename(str(_filename))

                log.logger('Envió un archivo: {}'.format(_filename), debug.PER)
                log.logger('Escribiendo ...', debug.INF)

                _save = '%s/%s' % (_folder, _filename)

                try:

                    with open(_save, 'wb') as _file_object:

                        _file_object.write(bytes_convert.convert(_content))

                except Exception as Except:

                    log.logger(
                        'Ocurrio una excepción al guardar a "{}". Excepción: {}'
                        .format(_filename, Except))

                else:

                    log.logger('Escrito: %s' % (_save), debug.PER)

        if (wrap.add(_message_id, {
                'nickname': nickname,
                'subject': subject,
                'message': message,
                'time': time_,
                'profile': _folder
        },
                     agent=wrap.USE_MESSAGE) == True):

            log.logger('Guardado: %s' % (_message_id), debug.PER)

            return (True)

        else:

            log.logger('No se pudo guardar el mensaje: %s' % (_message_id),
                       debug.WAR)

            return (False)

    else:

        return (False)