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
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')
Good instinct. Yes, an attacker being able to supply arbitrary format string is a vulnerability under python.
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.Look over the python format string specification and forbid functionality you don't want the user to have with a regex.