Can Python's string .format() be made safe for untrusted format strings?

后端 未结 2 737
猫巷女王i
猫巷女王i 2021-01-01 13:04

I\'m working on a web app where users will be able to supply strings that the server will then substitute variables into.

Preferably I\'d like to use PEP 3101 format

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 13:36

    Good instinct. Yes, an attacker being able to supply arbitrary format string is a vulnerability under python.

    • The denial of service is probably the most simple to address. In this case, limiting the size of the string or the number of operators within the string will mitigate this issue. There should be a setting where no reasonable user will need to generate a string with more variables than X, and this amount of computation isn't at risk of being exploited in a DoS attack.
    • Being able to access attributes within an object could be dangerous. However, I don't think that the Object parent class has any useful information. The object supplied to the format would have to contain something sensitive. In any case, this type of notation can limited with a regular expression.
    • If the format strings are user supplied then a user might need to know the error message for debugging. However, error mesages can contain senstive information such as local paths or class names. Make sure to limit the information that an attacker can obtain.

    Look over the python format string specification and forbid functionality you don't want the user to have with a regex.

提交回复
热议问题