3 ms·
So is the issue that it's a problem to let the format string be controlled arbitrarily? It's good to warn users around it because some may not know the dangers,
by yladiz 10y ago
So is the issue that it's a problem to let the format string be controlled arbitrarily? It's good to warn users around it because some may not know the dangers, but in general you don't trust user input, so I don't really see this as something you need to build something custom around, rather just be careful and follow good practices. It should be understood not to pass user data directly to internal code without sanitizing it. Proposing some custom code that uses undocumented internal features is overkill and also dangerous since things that aren't documented/internal can change suddenly.
- 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...