Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is using eval together with argparse save?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No, it is not 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.

Regardless, just use getattr. eval is almost never the correct solution.

logging.basicConfig(level=getattr(logging, args.loglevel))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading