async def MainParser(args): try: (network, port, __) = netparse.parse(args.network) except Exception as err: logging.error(_("La dirección '%s' no es válida: %s"), args.network, err) return net = "%s:%d" % (network, port) server_conf = parse_config.parse()["Server"] db = await create_pool.create(server_conf.get("mysql_db")) logging.warning(_("Borrando red '%s' :-("), net) networkid = await db.return_first_result("extract_networkid", net) if (networkid is None): logging.error(_("La red no existe")) return else: (networkid, ) = networkid await db.return_first_result("delete_network", networkid) public_key_dst = "%s/servkeys/%s" % (server_conf.get("init_path"), hashlib.sha3_224( net.encode()).hexdigest()) logging.debug(_("Borrando clave pública: %s"), public_key_dst) if (os.path.isfile(public_key_dst)): os.remove(public_key_dst) else: logging.warning( _("No se pudo eliminar la clave pública porque no existe")) logging.info(_("Red '%s' eliminada."), network)
async def remote(self): # Usado para verificar si se encontró el servicio en algún nodo registrado init = False force = self.controller.request.force node = self.controller.request.node if (force): if (node == ()): logger.warning(_("%s: No se definió el nodo a conectar"), self.get_template(logging.WARNING)) await self.controller.write_status( errno.ECLIENT, _("No definió el nodo a conectar")) return elif (len(node) != 2): logger.warning( _("%s: La información proporcionada sobre el nodo no es correcta" ), self.get_template(logging.WARNING)) await self.controller.write_status( errno.ECLIENT, _("La información proporcionada sobre el nodo no es correcta" )) return else: (host, port) = node if not (isinstance(host, str)): logger.warning( _("%s: La dirección o el nombre del host no tiene un tipo correcto de dato" ), self.get_template(logging.WARNING)) await self.controller.write_status( errno.ECLIENT, _("La dirección o el nombre del host no tiene un tipo correcto de dato" )) return try: port = int(port) except (ValueError, TypeError): logger.warning( _("%s: El puerto del nodo no tiene un tipo correcto de dato" ), self.get_template(logging.WARNING)) await self.controller.write_status( errno.ECLIENT, _("El puerto del nodo no tiene un tipo correcto de dato" )) return networks = self.__parse_node("%s:%d" % (host, port)) else: path = self.__set_correct_path(self.controller.request.path) networks = self.controller.pool.execute_command( "service2net", path, True) async for network in networks: (networkid, node_str) = network try: (host, port, __) = netparse.parse(node_str) except Exception as err: logger.error(_("%s: La dirección '%s' no es válida: %s"), self.get_template(logging.ERROR), node_str, err) continue public_key = "%s/%s" % ( server_data, hashlib.sha3_224(node_str.encode()).hexdigest()) if not (os.path.isfile(public_key)): logger.warning( _("%s: La clave pública '%s' del nodo '%s' no existe o no es un archivo" ), self.get_template(logging.warning), public_key, node_str) await self.controller.write_status(errno.ESERVER) continue else: async with aiofiles.open(public_key, "rb") as fd: public_key_data = await fd.read() token = await self.controller.pool.return_first_result( "get_network_token", networkid) if (token is None): logger.warning( _("%s: No se pudo obtener el token del nodo '%s'"), self.get_template(logging.WARNING), node_str) await self.controller.write_status(errno.ESERVER) continue else: (token, ) = token user_server = await self.controller.pool.return_first_result( "get_user_network", networkid) if (user_server is None): logger.warning( _("%s: No se pudo obtener el nombre de usuario del nodo '%d'" ), self.get_template(logging.WARNING), node_str) await self.controller.write_status(errno.ESERVER) continue else: (user_server, ) = user_server logger.warning(_("%s: Conectando con %s..."), self.get_template(logging.WARNING), node_str) fut = client.simple_client(host, port, user_server, public_key_data) try: (UControl, __, sock) = await fut except: logging.exception(_("%s: ¡Error conectando con %s!"), self.get_template(logging.WARNING), node_str) continue else: logger.info(_("%s: Conectado: %s"), self.get_template(logging.INFO), node_str) # Indicamos que la operación fue exitosa if not (init): init = True # Agregamos el socket a la lista de descriptores de archivos para cerrarlo self.procs.locals.ProcStream.add_stream(sock, node_str) UControl.headers = self.controller.request.headers UControl.headers["force"] = False # No necesariamente el servicio puede requerir un token, pero todo dependerá de lo que decida el # administrador de ese nodo, así que igualmente se envía. UControl.set_token(token) UControl.del_node() # Mandamos los primeros datos que el cliente envió await UControl.write(self.controller.data) await self.__resend(UControl) async for data in self.controller.body: UControl.headers["force"] = False UControl.set_token(token) UControl.del_node() await UControl.write(data) await self.__resend(UControl) if not (init): logger.warning( _("%s: No se pudo encontrar un nodo que tenga el servicio requerido" ), self.get_template(logging.WARNING), ) await self.controller.write_status(errno.ENOENT, _("Servicio no encontrado"))
async def MainParser(args): user = args.user password = args.password new_password = args.new_password token_limit = args.token_limit time_cost = args.time_cost memory_cost = args.memory_cost parallelism = args.parallelism remote = args.remote network = args.network server_key = args.server_key public_key = args.public_key private_key = args.private_key if not (remote): config = parse_config.parse() server_conf = config["Server"] crypt_limits = config["Crypt Limits"] db = await create_pool.create(server_conf.get("mysql_db")) userid = await db.return_first_result("extract_userid", user) if (userid is None): logging.error(_("El usuario '%s' no existe"), user) return else: (userid, ) = userid logging.warning(_("Cambiando contraseña del usuario: %s"), user) logging.debug(_("Generando hash...")) time_init = time.time() logging.debug(_("Generando hash...")) time_end = time.time() - time_init pass2hash = generate_hash.generate(new_password, time_cost, memory_cost, parallelism, crypt_limits) await db.return_first_result("change_password", pass2hash, userid) if (token_limit is not None): logging.warning( _("Cambiando el límite de token's permitidos para el usuario: %s (%d)" ), user, userid) await db.return_first_result("change_token_limit", token_limit, userid) logging.info(_("Hecho.")) else: if (password is None): logging.error(_("Es necesario definir la contraseña actual")) return if (network is None): logging.error(_("Es necesario definir la dirección de la red")) return try: (addr, port, path) = netparse.parse(network, default_path="/generate_token") except Exception as err: logging.error(_("La dirección '%s' no es válida: %s"), network, err) return if (server_key is None) or (public_key is None) or (private_key is None): logging.error( _("Se debe definir absolutamente todas las claves para poder continuar" )) return if not (os.path.isfile(server_key)): logging.error(_("¡La clave pública del servidor no existe!")) return elif not (os.path.isfile(public_key)) or not ( os.path.isfile(private_key)): logging.error( _("¡La clave pública o privada del usuario no existe!")) return else: with open(server_key, "rb") as fd: server_key = fd.read() with open(public_key, "rb") as fd: public_key = fd.read() with open(private_key, "rb") as fd: private_key = fd.read() try: (UControl, UClient, __) = await client.simple_client( addr, port, user, server_key, public_key=public_key, private_key=private_key, uteslaclient=uteslaclient.UTeslaClient()) except tornado.iostream.StreamClosedError as err: logging.error(_("Hubo un error conectado a %s:%d: %s"), addr, port, err) return UClient.set_stream_control(UControl) try: await UClient.change_passwd(password, new_password, token_limit, path) except tornado.iostream.StreamClosedError as err: logging.error(_("Hubo un error interpretando los datos: %s"), err) if (UControl.request.get_status_code() != 0) and (UControl.request.get_status_code() != -1): logging.error(_("Posible error: %s"), UControl.request.get_status()) else: status = UControl.request.get_status() status_code = UControl.request.get_status_code() if (status is None) or (status_code == -1): logging.error( _("Error, no se definió correctamente el estado.")) return if (status_code == 0): logging.info(_("Contraseña cambiada satisfactoriamente")) else: logging.warning( _("Se obtuvo un código de estado diferente a 0.")) logging.warning(_("Código de estado: %d"), status_code) logging.warning(_("Estado: %s"), status)
async def MainParser(args): global key_limit_size try: (net, port, path) = netparse.parse(args.network, default_port=8080) except Exception as err: logging.error(_("La dirección '%s' no es válida: %s"), args.network, err) return if (path == "/"): logging.error(_("Debe colocar el nombre de la clave a descargar")) return else: path = path[1:] outfile = args.outfile convert = args.convert overwrite = args.overwrite key_limit_size = args.key_limit_size client_options = { "connect_timeout": args.connect_timeout, "request_timeout": args.request_timeout, "user_agent": args.user_agent, "max_redirects": args.max_redirects, "follow_redirects": args.follow_redirects } if not (os.path.isdir(outfile)): config = parse_config.parse()["Server"] if (outfile.lower() == "nodes"): outfile = "%s/%s" % (config["init_path"], config["server_data"]) elif (outfile.lower() == "users"): outfile = "%s/%s" % (config["init_path"], config["user_data"]) else: logging.error(_("El directorio '%s' no existe"), outfile) return if (convert): path = hashlib.sha3_224(path.encode()).hexdigest() try: key = await getKey("http://%s:%d/%s" % (net, port, path), **client_options) except tornado.httpclient.HTTPClientError as err: logging.error(_("Ocurrió un error inesperado en la petición: %s"), err) return except IncorrectLength as err: logging.error(str(err)) return else: fingerprint = hashlib.sha3_256(key).hexdigest() output = os.path.join(outfile, path) prompt = _("¿Deseas continuar con la operación (sí/no)? ") prompt_error = _("Por favor teclea 'sí' o 'no': ") if (os.path.isfile(output)) and (overwrite): logging.warning(_("¡La clave '%s' ya existe!"), path) with open(output, "rb") as fd: original = fd.read() original_fingerprint = hashlib.sha3_256(key).hexdigest() if (fingerprint == original_fingerprint): print( _("La clave ya ha sido almacenada: {}").format(output)) return print(_("La huella de la clave es SHA3_256:{}").format(fingerprint)) while (True): question = input(prompt).lower() if not (question): prompt = prompt_error continue if (question == "sí"): with open(output, "wb") as fd: fd.write(key) print(_("Guardada: {}").format(output)) break elif (question == "no"): print(_("Verificación de la clave fallida")) break else: prompt = prompt_error
async def MainParser(args): limit = args.limit only = args.only remote = args.remote network = args.network token = args.token username = args.username server_key = args.server_key public_key = args.public_key private_key = args.private_key n = 1 if (remote): if (network is None): logging.error(_("Es necesario definir la dirección de la red")) return if (token is None): logging.error(_("Es necesario definir el token de acceso")) return if (username is None): logging.error(_("Es necesario definir el nombre de usuario")) return if (server_key is None): logging.error(_("Es necesario definir la clave pública del servidor")) return if (public_key is None): logging.error(_("Es necesario definir la clave pública del usuario")) return if (private_key is None): logging.error(_("Es necesario definir la clave privada del usuario")) return try: (addr, port, path) = netparse.parse(network, default_path="/get_services") except Exception as err: logging.error(_("La dirección '%s' no es válida: %s"), network, err) return try: (UControl, UClient, __) = await client.simple_client( addr, port, username, server_key.read(32), public_key = public_key.read(32), private_key = private_key.read(32), uteslaclient = uteslaclient.UTeslaClient() ) except tornado.iostream.StreamClosedError as err: logging.error(_("Hubo un error conectado a %s:%d: %s"), addr, port, err) return UClient.set_stream_control(UControl) UControl.set_token(token) services = UClient.get_services(path) logging.warning(_("Obteniendo servicios...")) async for service in services: service_number = " %d " % (n) n += 1; headers = [ _("Nombre del servicio"), _("Ruta de acceso") ] values = [ service, "%s:%d/%s" % (addr, port, service) ] print(service_number.center(50, "=")) table.print_table(headers, values) if (UControl.request.get_status_code() != -1) and (UControl.request.get_status_code() != 0): logging.error(_("Error obteniendo los servicios: %s"), UControl.request.get_status()) else: db = await create_pool.create() services = db.execute_command("get_services", limit, only=only, basic=False ) init = False async for id_service, id_network, service, priority in services: if not (init): init = True headers = [ _("Identificador"), _("Le pertenece a"), _("Nombre del servicio"), _("Prioridad") ] (network,) = await db.return_first_result("id2network", id_network) values = [ id_service, "%d (%s)" % (id_network, network), service, priority ] service_number = " %d " % (n) n += 1 print(service_number.center(50, "=")) table.print_table(headers, values) if only is not None and not init: logging.error(_("No se pudo encontrar ningún servicio que le pertenezca al nodo '%d'"), only) elif not (init): print(_("Aún no hay servicios registrados :-("))
async def MainParser(args): network = args.network token = args.token username = args.username password = args.password server_key = args.server_key public_key = args.public_key private_key = args.private_key try: (addr, port, path) = netparse.parse(network, default_path="/generate_token") except Exception as err: logging.error(_("La dirección '%s' no es válida: %s"), network, err) return try: (UControl, UClient, __) = await client.simple_client( addr, port, username, server_key.read(options.KEY_LENGTH), public_key=public_key.read(options.KEY_LENGTH), private_key=private_key.read(options.KEY_LENGTH), uteslaclient=uteslaclient.UTeslaClient()) except tornado.iostream.StreamClosedError as err: logging.error(_("Hubo un error conectado a %s:%d: %s"), addr, port, err) return else: UClient.set_stream_control(UControl) UControl.set_token(token) try: token = await UClient.renew_token(password, path) except tornado.iostream.StreamClosedError as err: logging.error(_("Hubo un error interpretando los datos: %s"), err) if (UControl.request.get_status_code() != 0) and (UControl.request.get_status_code() != -1): logging.error(_("Posible error: %s"), UControl.request.get_status()) else: status = UControl.request.get_status() status_code = UControl.request.get_status_code() if (status is None) or (status_code == -1): logging.error(_("Error, no se definió correctamente el estado.")) return if (status_code == 0): print(_("Nuevo Token:"), token) else: logging.warning(_("Se obtuvo un código de estado diferente a 0.")) logging.warning(_("Código de estado: %d"), status_code) logging.warning(_("Estado: %s"), status)
async def MainParser(args): keyfile = args.keyfile title = args.title subtitle = args.subtitle html_file = args.html_file key_limit_size = args.key_limit_size glob_exp = args.glob_pattern workspace = args.__OPTIONS__["workspaces"][args.__OPTIONS__["index"]] try: (address, port, __) = netparse.parse(args.listen) except Exception as err: logging.error(_("La dirección '%s' no es válida: %s"), args.listen, err) sys.exit(1) return if not (os.path.exists(keyfile)): config = parse_config.parse()["Server"] if (keyfile.lower() == "server"): keyfile = config["pub_key"] path = os.path.dirname(keyfile) elif (keyfile.lower() == "users"): keyfile = "%s/%s" % (config["init_path"], config["user_data"]) path = keyfile elif (keyfile.lower() == "nodes"): keyfile = "%s/%s" % (config["init_path"], config["server_data"]) path = os.path.dirname(keyfile) or "." else: logging.error(_("El archivo '%s' no existe"), keyfile) sys.exit(1) return else: path = keyfile index = "%s/%s" % (workspace, html_file) if not (os.path.isfile(index)): logging.error(_("La plantilla '%s' no existe")) sys.exit(1) return app = tornado.web.Application([(r"/(.*)", ServerHandler, { "path": path, "key": keyfile, "index": index, "title": title, "subtitle": subtitle, "key_limit_size": key_limit_size, "glob_exp": glob_exp })], template_path=".") httpd = tornado.httpserver.HTTPServer(app) httpd.listen(port, address) logging.info(_("Escuchando en http://%s:%d"), address, port)
async def MainParser(args): _ = create_translation.create( "add_network", os.getenv("UTESLA_LOCALES_PLUGINS") or \ "modules/Cmd/locales-shared" ) network = args.network token = args.token username = args.username server_key = args.server_key public_key = args.import_public_key private_key = args.import_private_key only = array_strip.strip(args.only) exclude = array_strip.strip(args.exclude) priority = args.priority if not (os.path.isfile(server_key)): logging.error(_("¡La clave pública del servidor no existe!")) return elif not (os.path.isfile(public_key)) or not (os.path.isfile(private_key)): logging.error(_("¡La clave pública o privada del usuario no existe!")) return else: with open(server_key, "rb") as fd: server_key_data = fd.read() with open(public_key, "rb") as fd: public_key_data = fd.read() with open(private_key, "rb") as fd: private_key_data = fd.read() config = parse_config.parse() server_conf = config.get("Server") try: (addr, port, path) = netparse.parse(network, default_path="/get_services") except Exception as err: logging.error(_("La dirección '%s' no es válida: %s"), network, err) return net = "%s:%d" % (addr, port) net_hash = hashlib.sha3_224(net.encode()).hexdigest() db = await create_pool.create(server_conf.get("mysql_db")) init_path = server_conf.get("init_path") server_key_dst = "%s/servkeys/%s" % (init_path, net_hash) service_path = server_conf["services"] networkid = await db.return_first_result("extract_networkid", net) try: (UControl, UClient, __) = await client.simple_client( addr, port, username, server_key_data, public_key=public_key_data, private_key=private_key_data, uteslaclient=uteslaclient.UTeslaClient()) except tornado.iostream.StreamClosedError as err: logging.error(_("Hubo un error conectado a %s:%d: %s"), addr, port, err) return UClient.set_stream_control(UControl) UControl.set_token(token) services = UClient.get_services(path) logging.warning(_("Obteniendo servicios...")) try: async for service_name in services: status_code = UControl.request.get_status_code() status = UControl.request.get_status() if (status_code == 0): service_name = os.path.basename(service_name) service_abs = "%(service_path)s/%(service_name)s/%(service_name)s.py" % { "service_path": service_path, "service_name": service_name } for __ in range(2): if (networkid is None): logging.debug( _("La red '%s' no existe, pero se agregará..."), net) await db.return_first_result("insert_network", net, token, username) networkid = await db.return_first_result( "extract_networkid", net) else: break if (networkid is None): logging.error( _("¡No se pudo obtener el identificador de la red '%s' en la base de datos!" ), net) continue else: if (isinstance(networkid, tuple)): (networkid, ) = networkid if (os.path.isfile(service_abs)): logging.warning( _("El servicio '%s' ya existe de manera local. No se agregará." ), service_name) continue if (service_name in exclude): logging.warning( _("El servicio '%s' no se agregará o actualizará porque está en la lista de exclusión" ), service_name) elif (only != []) and not (service_name in only): logging.warning( _("No se incluirá el servicio %s porque sólo se prefieren algunos servicios y éste no está incluido ahí" ), service_name) else: serviceid = await db.return_first_result( "extract_serviceid", service_name) if (serviceid is None) or not (await db.return_first_result( "network_in_service", networkid, *serviceid)): logging.info( _("Agregando servicio '%s' de la red '%s'"), service_name, net) await db.return_first_result("insert_service", networkid, service_name, priority) else: logging.warning( _("'%s' ya está registrado en la red '%s'"), service_name, net) else: logging.error(_("Ocurrió un error con la petición: %s"), status) break if (UControl.request.get_status_code() != -1) and (UControl.request.get_status_code() != 0): logging.error(_("Error obteniendo los servicios: %s"), UControl.request.get_status()) except tornado.iostream.StreamClosedError as err: logging.error(_("Hubo un error interpretando los datos: %s"), err) if (UControl.request.get_status_code() != 0) and (UControl.request.get_status_code() != -1): logging.error(_("Posible error: %s"), UControl.request.get_status()) else: if not (os.path.isfile(server_key_dst)): logging.debug(_("Copiando '%s' a '%s'..."), server_key, server_key_dst) shutil.copy(server_key, server_key_dst) logging.info(_("Hecho."))