Profiling SSTI in Flask/Jinja2 Analysis

Source: Internet
Author: User

Profiling SSTI in Flask/Jinja2 Analysis
Part 1

If you have never heard of a server template injection (SSTI) attack, or do not know much about it, you are advised to read this article written by James Kettle before continuing to read this article.

As a security practitioner, we are helping enterprises make risk-based decisions. Because risks are the product of influences and attributes, we cannot calculate the corresponding risk values correctly without knowing the true influence of a vulnerability. As a developer who often uses the Flask framework, James's research prompted me to figure out how much impact SSTI has on the applications that develop stacks Based on Flask/Jinja2. This article is the result of my research. If you want to learn more about the background, you can refer to this article by Ryan Reid, which provides more information about SSTI in the Flask/Jinja2 application.

0x00 Setup

To evaluate the impact of SSTI in the Flask/Jinja2 stack, let's build a small poc program with the code below.

[email protected](404)def page_not_found(e):    template = '''{%% extends "layout.html" %%}{%% block body %%}    
Oops! That page doesn't exist. % s {% endblock %} ''' % (request. url) return render_template_string (template), 404

Behind this code, the developer thought it would be silly to create a single template file for a small 404 page, so he created a template string in the 404 view function. The developer wants to display the wrong URL entered by the user. However, the developer chooses to use string formatting to dynamically Add the URL to the template string, instead of passing the URL to the template content through the render_template_string function. It feels quite reasonable, right? This is the worst thing I have ever seen.

When testing this function, we saw the expected results.

Most people will immediately think of XSS, and their ideas are correct. Adding <script> alert (42) </script> at the end of the URL triggers an XSS vulnerability.

The target code is easily used by XSS, but in James's article, he pointed out that XSS is a sign of SSTI. This is a good example. If we go deeper and add {7 + 7} at the end of the URL, we can see that the template engine calculates the mathematical expression, the application parses the response into 14.

We have detected the SSTI vulnerability in the target application.

0x01 Analysis

To get an available exp, the next step is to go deep into the template environment and use the SSTI vulnerability to find points that can be exploited by attackers. Modify the vulnerability preview function in the poc program, as shown below.

[email protected](404)def page_not_found(e):    template = '''{%% extends "layout.html" %%}{%% block body %%}    
Oops! That page doesn' t exist. % s {% endblock %} ''' % (request. url) return render_template_string (template, dir = dir, help = help, locals = locals,), 404

We pass the dir, help, and locals built-in functions into the render_template_string function, and add them to the template environment through function calls to use them for introspection through vulnerabilities, to discover available points in the template program.

Let's pause for a moment to discuss how the template content is described in the document. There are several final sources of objects in the template content.

Jinja globalsFlask template the object added by the globals developer

We are most concerned about points 1st and 2nd, because they are usually the default settings and are available in any Flask/Jinja2 stack program with SSTI. 3rd points depend on applications, and there are many implementation methods. This stackoverflow discussion contains several examples. Although we will not discuss the 3rd points in depth in this article, this must be taken into account in the Code audit-related Flask/Jinja2 stack application source code.

Our approach should be as follows in order to use the province to continue our research.

Read the document! You can use dir to save locals objects and find everything available in the template content. Use dir and help to gain insight into all object analysis and any interesting Python source code (after all, everything in the stack is open source) 0x02 Results

Through the introspection request object, we will make the first interesting exploration and discovery. The request object is a global variable of the Flask template, representing the "current request object (flask. request )". When you access the request object in the view, it contains all the information you expected to see. There is an object called environ in the request object. Request. environ is a dictionary that contains objects related to the server environment. There is a shutdown_server method in this dictionary. The corresponding key value is werkzeug. server. shutdown. So let's guess what happens when we inject {request. environ ['werkzeug. server. shutdown '] ()} to the server? Yes, it will produce a denial-of-service and its low-level. This method does not exist when gunicorn is used to run the application, so the vulnerability may be restricted by the development environment.

The second interesting result is the internal config object. The config object is a global variable of the Flask template, representing the "current configuration object (flask. config )". It is a dictionary-like object that contains all the configuration values of the application. In most cases, sensitive information such as database connection strings, third-party service creden。, and SECRET_KEY is contained. You can easily view these configurations by injecting payload {config. items.

Do not think that storing these configuration options in environment variables can prevent such information leakage. Once the related configuration values are parsed by the Framework, the config object will include them all.

Our most interesting findings also come from the internal config object. Although the config object is a dictionary-like object, it is also a subclass containing several unique methods: from_envvar, from_object, from_pyfile, and root_path. Finally, let's go into the source code. The following code is the from_object method in the Config object, flask/config. py.

#!python    def from_object(self, obj):        """Updates the values from the given object.  An object can be of one        of the following two types:            -   a string: in this case the object with that name will be imported        -   an actual object reference: that object is used directly            Objects are usually either modules or classes.            Just the uppercase variables in that object are stored in the config.        Example usage::                app.config.from_object('yourapplication.default_config')            from yourapplication import default_config            app.config.from_object(default_config)            You should not use this function to load the actual configuration but        rather configuration defaults.  The actual config should be loaded        with :meth:`from_pyfile` and ideally from a location not within the        package because the package might be installed system wide.            :param obj: an import name or object        """        if isinstance(obj, string_types):            obj = import_string(obj)        for key in dir(obj):            if key.isupper():                self[key] = getattr(obj, key)        def __repr__(self):        return '

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.