BUUCTF [De1CTF 2019] SSRF Me

  • Audit the source code and add some comments
#! /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): #python对象的初始化构造方法
        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): #命令执行,并且调用了下面的Scan函数
        result = {
    
    }
        result['code'] = 500
        if (self.checkSign()):#调用checkSign函数来判段
            if "scan" in self.action: #action中要有scan
                tmpfile = open("./%s/result.txt" % self.sandbox, 'w')
                resp = scan(self.param) # 自定义的scan()函数读取文件
                if (resp == "Connection Timeout"):
                    result['data'] = resp
                else:
                    print resp # 输出结果
                    tmpfile.write(resp)
                    tmpfile.close()
                result['code'] = 200
            if "read" in self.action: # action中要有read
                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): # checkSign用于上面的校验
        if (getSign(self.action, self.param) == self.sign):
            return True
        else:
            return False

#generate Sign For Action Scan.
@app.route("/geneSign", methods=['GET', 'POST'])
# /geneSign路由 
def geneSign():
    param = urllib.unquote(request.args.get("param", ""))
    # request.args.get()用于获取url上的参数 这里获取param
    action = "scan"
    return getSign(action, param)

@app.route('/De1ta',methods=['GET','POST']) # 这里执行了Exec(),应该是最后的注入点
# /De1ta路由
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())
    # json.dump将python对象转为python对象
@app.route('/')
def index():
    return open("code.txt","r").read()
    # 我们点入题目后的页面 返回的就是源代码

def scan(param):
    socket.setdefaulttimeout(1)
    # 经过1秒后,如果还未下载成功,自动跳入下一次操作,
    try:
        return urllib.urlopen(param).read()[:50]
    except:
        return "Connection Timeout"

def getSign(action, param):
    return hashlib.md5(secert_key + param + action).hexdigest()
    # action和param的md5加密

def md5(content):
    return hashlib.md5(content).hexdigest()
    # 文件内容的md5加密

def waf(param):
    check=param.strip().lower()
    if check.startswith("gopher") or check.startswith("file"):
    # gopher协议和file协议的waf 提醒我去复习gopher协议了
        return True
    else:
        return False

if __name__ == '__main__':
    app.debug = False
    app.run(host='0.0.0.0')
  • A brief summary of the code after auditing
  • There are three routes under the Flask framework
  • /geneSign:The returned test page is encrypted by md5secert_key + param + action
  • /De1ta:The core part of the topic
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
task = Task(action, param, sign, ip)
return json.dumps(task.Exec())
  • Get a series of data, param filters gopher and file, generate Task object, call Exec() command execution function to read the file
  • /:Return to the source code, no use problem gave the download place
  • In the first step of executing the Exec() function, there is aif(self.checkSign())
def checkSign(self): # checkSign用于上面的校验
    if (getSign(self.action, self.param) == self.sign):
        return True
    else:
        eturn False
def getSign(action, param):
    return hashlib.md5(secert_key + param + action).hexdigest()
  • So the sign we passed in should be consistent with the sign generated by getSign()
  • So we visit the /geneSignroute get upload? param=flag.txtread
  • adf80ee5dfe9c60c8575ebd2c8baacf1Page back
  • This is the md5 encrypted value returned by the page when action=readscan param=flag.txt
  • Because the action is fixed to scan when it is generated, only param=readscan is required
def geneSign():
    param = urllib.unquote(request.args.get("param", ""))
    # request.args.get()用于获取url上的参数 这里获取param
    action = "scan"
    return getSign(action, param)

Guess you like

Origin blog.csdn.net/CyhDl666/article/details/114576159