Python security: New string format vulnerability analysis and solutions

Source: Internet
Author: User
A recent python string formatting vulnerability has aroused my attention. today, I will discuss the security vulnerability of a new syntax for formatting strings introduced by Python, recently, a python string formatting vulnerability has aroused my attention. today, I will discuss the security vulnerability of a new syntax for formatting strings introduced by Python, and provides corresponding security solutions.

When we use str for untrusted user input. format will pose a security risk-I have known about this problem for a long time, but I have not realized its severity until today. Attackers can exploit this vulnerability to bypass the Jinja2 sandbox, which may cause serious information leakage. At the same time, I provide a new security version for str. format at the end of this article.

It should be noted that this is a very serious security risk. the reason for writing this article is that most people may not know how easy it is to be used.

Core issues

Inspired by. NET, Python 2.6 introduced a new syntax for formatting strings. Of course, in addition to Python, Rust and other programming languages also support this syntax. With the help. format () method. this syntax can be applied to bytes and unicode strings (in Python 3, it can only be used for unicode strings). In addition, it can also be mapped to a more customizable string. formatter API.

One feature of this syntax is that people can use it to determine the location and keyword parameters of the string format, and can explicitly re-sort the data items at any time. In addition, it can even access the properties and data items of the object-this is the root cause of the security problem here.

In general, people can use it to do the following:

>>> 'class of {0} is {0.__class__}'.format(42)"class of 42 is "

Essentially, anyone who can control the format string may access various internal properties of the object.

Where is the problem?

The first question is how to control the format string. You can start from the following:

1. untrusted translator in the string file. We are likely to get through them because many applications translated into multiple languages use this new Python string formatting method, but not everyone will perform a comprehensive review of all input strings.

2. configuration exposed by the user. Some system users can configure certain behaviors, which may be exposed in the format of strings. I have seen some users configure notification emails, log message formats, and other basic templates through Web applications.

Hazard level

If you just pass the C interpreter object to a string in this format, it will not be too dangerous, because in this case, you will expose at most some integer classes and other things.

However, once a Python object is passed to a string in this format, it will be troublesome. This is because the number of things that can be exposed from Python functions is quite amazing. The following is a hypothetical Web application scenario where keys can be leaked:

CONFIG = {    'SECRET_KEY': 'super secret key'} class Event(object):    def __init__(self, id, level, message):        self.id = id        self.level = level        self.message = message def format_event(format_string, event):    return format_string.format(event=event)

If you can inject format_string here, they can find the following secret string:

{event.__init__.__globals__[CONFIG][SECRET_KEY]}
Sandbox-based formatting

So what should I do if I want other people to provide formatted strings? In fact, some undisclosed internal mechanisms can be used to change the string formatting behavior.

from string import Formatterfrom collections import Mapping class MagicFormatMapping(Mapping):    """This class implements a dummy wrapper to fix a bug in the Python    standard library for string formatting.     See http://bugs.python.org/issue13598 for information about why    this is necessary.    """     def __init__(self, args, kwargs):        self._args = args        self._kwargs = kwargs        self._last_index = 0     def __getitem__(self, key):        if key == '':            idx = self._last_index            self._last_index += 1            try:                return self._args[idx]            except LookupError:                pass            key = str(idx)        return self._kwargs[key]     def __iter__(self):        return iter(self._kwargs)     def __len__(self):        return len(self._kwargs) # This is a necessary API but it's undocumented and moved around# between Python releasestry:    from _string import formatter_field_name_splitexcept ImportError:    formatter_field_name_split = lambda \        x: x._formatter_field_name_split(){C} class SafeFormatter(Formatter):     def get_field(self, field_name, args, kwargs):        first, rest = formatter_field_name_split(field_name)        obj = self.get_value(first, args, kwargs)        for is_attr, i in rest:            if is_attr:                obj = safe_getattr(obj, i)            else:                obj = obj[i]        return obj, first def safe_getattr(obj, attr):    # Expand the logic here.  For instance on 2.x you will also need    # to disallow func_globals, on 3.x you will also need to hide    # things like cr_frame and others.  So ideally have a list of    # objects that are entirely unsafe to access.    if attr[:1] == '_':        raise AttributeError(attr)    return getattr(obj, attr) def safe_format(_string, *args, **kwargs):    formatter = SafeFormatter()    kwargs = MagicFormatMapping(args, kwargs)    return formatter.vformat(_string, args, kwargs)

Now we can use the safe_format method to replace str. format:

>>> '{0.__class__}'.format(42)"">>> safe_format('{0.__class__}', 42)Traceback (most recent call last):  File "", line 1, inAttributeError: __class__
Summary:

There is one sentence in program development: do not trust user input at any time! It seems that this sentence makes sense. So remember!

[Course recommendation]

Python free online video tutorial

The above is Python security: detailed analysis of new string format vulnerabilities and solutions. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.