def get_pattern(string, regular_expression, log): if (convert.convert_bool(regular_expression) == True): try: pattern = re.search(regular_expression, string, re_options) except Exception as Except: pattern = False log( 'Excepción en la expresión regular: "{}". Excepción: "{}"'. format(repr(regular_expression), Except), WAR) else: if (pattern): log( 'Coincidencia {} en {}'.format(regular_expression, string), PER) else: pattern = False return (pattern)
def eject_to(self, blacklist, string, regular_expression, log): contrary = self.get_contrary(blacklist) blacklist = self.get_real_list(blacklist) pattern = self.get_pattern(string, regular_expression, log) cmp_data = (pattern) or (string in [ x.strip() for x in blacklist.split(',') if (convert.convert_bool(x)) ]) return (contrary != cmp_data)
def eject(self): if (convert.convert_bool(blacklist) == True) or ( convert.convert_bool(regular_expression_for_address)): if (self.eject_to(blacklist, self.client_address[0], regular_expression_for_address, self.imprint) == True): self.imprint( '¡No tiene permiso para ingresar a Evie!. Coincidencia: "{}" en la lista negra de direcciones' .format(self.client_address[0]), WAR) self.error403() request_count_safe['address_BLOCK'] += 1 return (True) if (convert.convert_bool(user_agent_list) == True) or ( convert.convert_bool(regular_expression_for_userAgent)): if (self.eject_to(user_agent_list, self.headers['User-Agent'], regular_expression_for_userAgent, self.imprint) == True): self.imprint( '¡No tiene permiso para ingresar a Evie!. Coincidencia: "{}" en la lista negra de agentes de usuario' .format(self.headers['User-Agent']), WAR) self.error403() request_count_safe['user_agent_BLOCK'] += 1 return (True) if (convert.convert_bool(honeypot_list) == True) or ( convert.convert_bool(regular_expression_for_address) == True): self.honeypot(honeypot_list, self.client_address[0], self.imprint)
data_type = args.data_type if (data_type == 'int'): try: value = int(value) except ValueError: print('El valor no es númerico') sys.exit(1) elif (data_type == 'bool'): if not (convert.convert_bool(value.lower())): value = False else: value = True elif (data_type == 'str'): pass else: print('El tipo de dato no está disponible ...') sys.exit(1)
def defend(command, address, bhost, bport, log): try: bhost = str(bhost) bport = str(bport) commands = [x.strip() for x in command.split(';') if (convert.convert_bool(x))] (host, port) = address # Bind (hostname, address) = my_addr.addr() for b_ in commands: cmd = b_ try: limit = int(cmd.split(None, 1)[0]) except: log('¡El limite debe ser un número!', debug.WAR) return cmd = ''.join(cmd.split(None, 1)[1:]).strip() for _key, _value in {'{ip}':host, '{port}':port, '{bhost}':bhost, '{bport}':bport, '{phost}':my_public_addr.addr}.items(): if (cmd.find(_key) != -1): if (isfunction(_value)): _value = str(_value()) cmd = cmd.replace(_key, _value) uniqid = sha1(cmd.encode()).hexdigest() db_result = int(wrap.read(uniqid, 'limit', agent=wrap.USE_DEFEND)) if not (limit == 0): if (db_result == 0): if (wrap.add(uniqid, {'limit':1}, agent=wrap.USE_DEFEND) == False): log('Lo siento no se pudo agregar un limite al almacén para la siguiente defensa: "{}"'.format(cmd), debug.COM) return elif (db_result >= limit): return else: if (wrap.write(uniqid, 'limit', db_result+1, agent=wrap.USE_DEFEND) == False): log('No se pudo actualizar el limite en el almacén para la siguiente defensa: "{}"'.format(cmd), debug.COM) return parsed = shlex.split(cmd) try: result = Popen(parsed, stdout=PIPE, stderr=STDOUT, universal_newlines=True) except FileNotFoundError: log('El ejecutable: "{}" no se puede ejecutar porque no existe ...'.format(parsed[0]), debug.WAR) return except Exception as Except: log('Ocurrio un error desconocido al ejecutar el siguiente comando: "{}". Excepción: "{}"'.format(cmd, Except), debug.WAR) return pid = result.pid name = "%s.%s.%s.log" % (host, uniqid, strftime('%d-%m-%Y')) output_func('\033[1;37m***\033[0m \033[1;32mIniciando\033[0m: \033[1;33mID\033[0m:\033[1;37m%s\033[0m: \033[1;33mpid\033[0m:\033[1;37m%d\033[0m \033[1;34m~\033[0m \033[1;33mfile\033[0m:\033[1;37m%s ***\033[0m\n' % (uniqid, pid, name), name) with result as _process: for c_ in _process.stdout: output_func("\033[1;34m%s\033[0m: \033[1m%s\033[0m\n" % (parsed[0], c_.rstrip()), name) output_func('\033[1;37m***\033[0m \033[1;32mFinalizado\033[0m: \033[1;33mID\033[0m:\033[1;37m%s\033[0m: \033[1;33mpid\033[0m:\033[1;37m%d\033[0m \033[1;34m~\033[0m \033[1;33mfile\033[0m:\033[1;37m%s ***\033[0m\n' % (uniqid, pid, name), name) except Exception as Except: log('Excepción ejecutando la defensa: {}'.format(Except), debug.COM)
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))