CTF

ISEC 2010 level8 random array

badcob 2010. 11. 10. 17:48
ISEC 2010 prequal 8번이었나 random array 로 bruteforce 하는  문제 .
난수 반복 때문에 한참 헤메다가 cpu 클럭으로 생성하게 함.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>


#define RAN_SIZE   28 
#define TRUE        1
#define RESULT      "result" 

int main(void)
{
    char buf[28] = { };
    char tmp[28] = { };
    char last[28] = {};

    char x[16] = { };
    char y[16] = { };

    char str[32] = "6445666F485F6CF526CC5457F3A4";

    int rand_num = 0;
    int len = 0;
    int count;
    int status = 0;
    int flag = 0;
    int i;

    FILE *fp;

    pid_t pid;
    clockid_t clock_id;
    long ret;
    char ptr = NULL;
    struct timespec t;

    pid = getpid();


    fp = fopen(RESULT, "a+");
    memcpy(buf,str,28);

    while(TRUE) {

        //get cpu clock
        clock_getcpuclockid(pid, &clock_id);
        clock_gettime(clock_id, &t);

        srand(t.tv_nsec);

        //shuffling the array

        do { 
            rand_num = rand() % RAN_SIZE;
            count = 0;
            if (len <= 0)
                goto LABEL_1;
            do {
                if (tmp[count] == rand_num) {
                    status = 1;
                }
                ++count;
            } while (count < len);

            if (status) {
                status = 0;
            }
            else {
LABEL_1:
                tmp[len++] = rand_num;
            }         
        } while (len < 28);

      // is it printable?
        for (i = 0; i < len; i=i+2) {
            sprintf(x,"%c%c",buf[tmp[i]],buf[tmp[i+1]]);
            ret = strtol(x,&ptr,16);
            sprintf(y,"%c",ret);
            if (( *y < 0x1f) || (*y > 0x7e)) {
                flag = 1;
                break;
            }
            strcat(last,y);
        }
        
        if (!flag) {
            fprintf(fp,"%s\n",last);
        }

        status = 0;
        len = 0;
        count = 0;
        rand_num = 0;
        flag = 0;
        memset(x,0x00,sizeof(x));
        memset(y,0x00,sizeof(y));
        memset(last,0x00,sizeof(last));
    }
    fclose(fp);
    return 0;
}


Python 으로는 아래처럼 random.shuffle 로 돌리면 된다.
import random, re

s = '6445666F485F6C5F6C2C54573F4A'

ran = []
for x in range(28):
    ran.append(str(x))

random.shuffle(ran)