3 ms·
> It should be understood not to pass user data directly to internal code without sanitizing it. But how do you sanitize it? If you hadn't read this article an
by geofft 10y ago
> It should be understood not to pass user data directly to internal code without sanitizing it.
But how do you sanitize it? If you hadn't read this article and were told to sanitize a format string, how would you implement that?
Unless you know exactly what the problem is, you're basically reduced to writing your own string formatter. (Though see 'anderskaseorg's example, it's a lot less code if you do.)
- tedmiston 10y agoI 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...