Is it safe/secure to run .format() on user-provided strings in Python?

Viewed 149

Scenario: An end-user (untrusted) provides a string such as, "Hello, {name}!". On a server, I want to do string substitution on that user-provided string in the form of, my_string.format(name="Homer"). There are a great many things you can do with string formatting in Python, so I'm wondering whether it is a security concern to run a format() method on an untrusted string. Is it possible to provide a string value that, when Python's string substitution is used, will alter data outside of the string content itself?

1 Answers

String formatting is safe in a way that it does not have side effects. It won't change anything outside of that string.

It can still be a security issue depending on what you do with that string later on. The most obvious example is using string formatting for SQL statements; That's horrendously unsafe.

Related