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

后端 未结 2 738
猫巷女王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:18

    This simple Formatter override blocks users from accessing attributes. It still allows formatting and conversion of types.

    from string import Formatter
    class SafeFormatter(Formatter):
            def get_field(self, field_name, args, kwargs):
                if '.' in field_name or '[' in field_name:
                    raise Exception('Invalid format string.')
                return super().get_field(field_name,args,kwargs)
    
    form = SafeFormatter()
    fname = form.format(format,num=1,id='hello')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题