I use argparse and eval to change loglevels of logging.
parser = argparse.ArgumentParser(
description="Adds New Location to the Snipe-IT Server")
parser.add_argument('-l', '--loglevel', type=str, default='WARNING', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
args = parser.parse_args()
logging.basicConfig(level=eval(f"logging.{args.loglevel}"))
I wonder if it is save to use eval in this case? I don't know if choices limit in this case the inputs.
No, it is not quite safe. It won't be too hard for a knowledgable malicious user to hack the argparse
module to be able to pass any thing they want through the CLI.
However, at this point they might as well just write their own malicious program than trying to use yours as an attack vector.
Even if one deems this very specific usage of eval
safer because its input is validated, knowingly using a function that exposes a huge attack surface when a safe and easy alternative is available (getattr
in this case) is a very questionable decision.
Moreover, the codebase might change in the future (eg. the sanitization code might be removed or modified) leaving the eval
usage more vulnerable than it already was.
Regardless, just use getattr
. eval
is almost never the correct solution.
logging.basicConfig(level=getattr(logging, args.loglevel))