Exemple #1
0
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)
Exemple #2
0
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)
Exemple #3
0
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 :-("))
Exemple #4
0
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."))