4 ms·
I think asking how to sanitize it is really asking the wrong question. We shouldn't sanitize a format string from a user in the first place. We should get input
by tedmiston 10y ago
I think asking how to sanitize it is really asking the wrong question. We shouldn't sanitize a format string from a user in the first place. We should get input and generate a format string rather than allow one to be supplied "raw".
For example, using re.sub as another commenter pointed out.
An even more Pythonic solution would be to use the built-in string.Template [1] which at a glance appears to be safe against this kind of attack (but I haven't tested in code).
I'm not sure why Armin didn't mention string.Template in his post other than that it is much more restricted than str.format, however that kind of seems like the point to me.
[1]: https://docs.python.org/3.4/library/string.html#template-strings https://docs.python.org/3.4/library/string.html#template-str...
- daveguy 10y agoSince 2.4: https://docs.python.org/2/library/string.html#template-strings https://docs.python.org/2/library/string.html#template-strin...