Lab Exercise Format Strings and Templates

This is a lab exercise on developing secure software. For more information, see the introduction to the labs.

Task

Practice eliminating string formatting vulnerabilities in Python.

Background

In this exercise, we'll adjust our string formatting so that it doesn't allow a user to control the format string.

If a user can control the format string in Python they can access value which they shouldn't. Particularly if those variable's values can be returned to the user as output, it could lead to information disclosure beyond what was intended by the developer.

Task Information

Please change the code below so the string formatting cannot disclose arbitrary program values.

The server-side program is written in Python and allows a user to specify a format string to control the output format of an event, shown here as user_format. The developer probably expected the user to provide a format string like '{event.level}' to control what is shown and where.

However, in many programming languages, allowing an untrusted user to control a format sting is a vulnerability. Format strings are miniature programming languages; running code provided by an untrusted user is dangerous. In the case of Python, an attacker might be able to provide a sneaky format string value like '{event.__init__.__globals__[CONFIG][SECRET_KEY]}' and reveal a secret value like a password or secret key.

In this case, as in many, there is no need for an untrusted user to control the format string at all. Where we can, we should use a constant format that cannot be controlled by a potential attacker. For purposes of this lab, instead of letting the user control the formatting string, set the format to the fixed value '{event.level},{event.message}' and don't forget to remove the no-longer-needed format parameter.

Use the “hint” and “give up” buttons if necessary.

Interactive Lab ()



This lab was developed by Jason Shepherd at Red Hat. with an modified version of the example code from Armin Ronacher's Be Careful with Python's New-Style String Format article, and modified by David A. Wheeler.