기본 콘텐츠로 건너뛰기

Memory-Protection_GS

Memory-Protection_GS

메모리 보호 기법 - GS

간단한 버퍼 오버플로우 예제 코드를 이용하여 GS 메모리 보호 기법에 대해서 알아보자.

먼저 Visual Studio를 실행하여 C++ Win32 콘솔 응용 프로그램 프로젝트를 생성한다.

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

int main(int argc, char* argv[]) {
	char test[10];
	strcpy(test, argv[1]);

	printf("result: %s", test);
	return 0;
}

소스 코드 입력 후에 프로젝트에 설정된 보호 기법을 모두 제거한다.

  • properties > C/C++ > Code Generation
    • Enable C++ Exceptions: No
    • Basic Runtime Checks: Default
    • Security Check: Disable Security Check (/GS-)
  • properties > Linker > Advanced
    • Randomized Base Address: No (/DYNAMICBASE:NO)
    • Data Execution Prevention (DEP): No (/NXVOMPAT:NO)

빌드 후 생성된 실행 파일 디렉터리로 이동하여 정상 동작을 테스트한다.

GS.exe AAA
result: AAA

GS.exe AAAAAAAAAAAAAAAAAAAAAA
Segmentation fault

windbg.exe -I명령어를 입력하면 windbg 가 등록되어 단순 오류 발생 확인에 그치지 않고 디버깅할 수 있게 해주므로 유용하게 활용할 수 있다.

windbg를 실행 후 프로그램 인자로 많은 양의 'A’를 전달하여 오류 상세 내용을 확인해보자. eip가 41414141로 설정되어 명령어를 읽어오지 못하고 Access Violation이 발생한 것을 볼 수 있다.

0:000> uf GS!main
    4 004115b0 55              push    ebp
    4 004115b1 8bec            mov     ebp,esp
    4 004115b3 83ec4c          sub     esp,4Ch
    4 004115b6 53              push    ebx
    4 004115b7 56              push    esi
    4 004115b8 57              push    edi
    6 004115b9 b804000000      mov     eax,4
    6 004115be c1e000          shl     eax,0
    6 004115c1 8b4d0c          mov     ecx,dword ptr [ebp+0Ch]
    6 004115c4 8b1401          mov     edx,dword ptr [ecx+eax]
    6 004115c7 52              push    edx
    6 004115c8 8d45f4          lea     eax,[ebp-0Ch]
    6 004115cb 50              push    eax
    6 004115cc e8cafaffff      call    GS!ILT+150(_strcpy) (0041109b)
    6 004115d1 83c408          add     esp,8
    8 004115d4 8d45f4          lea     eax,[ebp-0Ch]
    8 004115d7 50              push    eax
    8 004115d8 68305b4100      push    offset GS!`string' (00415b30)
    8 004115dd e885fcffff      call    GS!ILT+610(_printf) (00411267)
    8 004115e2 83c408          add     esp,8
    9 004115e5 33c0            xor     eax,eax
   10 004115e7 5f              pop     edi
   10 004115e8 5e              pop     esi
   10 004115e9 5b              pop     ebx
   10 004115ea 8be5            mov     esp,ebp
   10 004115ec 5d              pop     ebp
   10 004115ed c3              ret

이제 properties로 이동하여 GS를 설정해보자. strcpy 함수는 취약함수로 빌드 시도 시 보안 경고로 인해 실패할 수 있다. 코드 최상단에 아래 #define을 추가한다.

#define _CRT_SECURE_NO_WARNINGS
  • properties > C/C++ > Code Generation
    • Security Check: Enable Security Check (/GS-)
0:000> uf GS!main
GS!main [c:\users\nabab\documents\visual studio 2015\projects\gs\gs\main.cpp @ 6]:
    6 004115a0 55              push    ebp
    6 004115a1 8bec            mov     ebp,esp
    6 004115a3 83ec50          sub     esp,50h
    6 004115a6 a10c704100      mov     eax,dword ptr [GS!__security_cookie (0041700c)]
    6 004115ab 33c5            xor     eax,ebp
    6 004115ad 8945fc          mov     dword ptr [ebp-4],eax
    6 004115b0 53              push    ebx
    6 004115b1 56              push    esi
    6 004115b2 57              push    edi
    8 004115b3 b804000000      mov     eax,4
    8 004115b8 c1e000          shl     eax,0
    8 004115bb 8b4d0c          mov     ecx,dword ptr [ebp+0Ch]
    8 004115be 8b1401          mov     edx,dword ptr [ecx+eax]
    8 004115c1 52              push    edx
    8 004115c2 8d45f0          lea     eax,[ebp-10h]
    8 004115c5 50              push    eax
    8 004115c6 e8d0faffff      call    GS!ILT+150(_strcpy) (0041109b)
    8 004115cb 83c408          add     esp,8
   10 004115ce 8d45f0          lea     eax,[ebp-10h]
   10 004115d1 50              push    eax
   10 004115d2 68305b4100      push    offset GS!`string' (00415b30)
   10 004115d7 e88bfcffff      call    GS!ILT+610(_printf) (00411267)
   10 004115dc 83c408          add     esp,8
   11 004115df 33c0            xor     eax,eax
   12 004115e1 5f              pop     edi
   12 004115e2 5e              pop     esi
   12 004115e3 5b              pop     ebx
   12 004115e4 8b4dfc          mov     ecx,dword ptr [ebp-4]
   12 004115e7 33cd            xor     ecx,ebp
   12 004115e9 e8f7fbffff      call    GS!ILT+480(__security_check_cookie (004111e5)
   12 004115ee 8be5            mov     esp,ebp
   12 004115f0 5d              pop     ebp
   12 004115f1 c3              ret

GS를 적용하기 전과 동일하게 'A’를 대량 전달하여 반응을 살펴보자

eax=00000000 ebx=7efde000 ecx=00000000 edx=00000000 esi=00000000 edi=00000000
eip=77acfcc2 esp=0018fb64 ebp=0018fb74 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!ZwTerminateProcess+0x12:
77acfcc2 83c404          add     esp,4
*** WARNING: Unable to verify checksum for C:\Users\nabab\Desktop\8일차\vs_GS\enable_gs\GS.exe
0:000> uf GS!main

eip\x41로 덮어써졌던 이전과 달리 스택 쿠키 체크섬 경고와 함께 프로세스를 종료시킨 것을 볼 수 있다. 이로 인해 함수 프롤로그 시 생성한 GS 쿠키를 함수 에필로그 시 비교하여 불일치하면 오버플로우가 발생한 것으로 판단하고 프로세스를 종료 시키기는 것을 알 수 있다.

0:000> u 004111e5
GS!ILT+480(__security_check_cookie:
004111e5 e9061c0000      jmp     GS!__security_check_cookie (00412df0)
GS!ILT+485(___scrt_get_dyn_tls_init_callback):
004111ea e9b1130000      jmp     GS!__scrt_get_dyn_tls_init_callback (004125a0)
GS!ILT+490(__register_onexit_function):
004111ef e9e8200000      jmp     GS!register_onexit_function (004132dc)
GS!ILT+495(___scrt_initialize_crt):
004111f4 e9770c0000      jmp     GS!__scrt_initialize_crt (00411e70)
GS!ILT+500(_guard_check_icall_nop:
004111f9 e9b21b0000      jmp     GS!_guard_check_icall_nop (00412db0)
GS!ILT+505(___scrt_get_show_window_mode):
004111fe e94d150000      jmp     GS!__scrt_get_show_window_mode (00412750)
GS!ILT+510(_IsDebuggerPresent:
00411203 e916210000      jmp     GS!IsDebuggerPresent (0041331e)
GS!ILT+515(___acrt_thread_attach):
00411208 e953210000      jmp     GS!__scrt_stub_for_acrt_thread_attach (00413360)
0:000> u 00412df0
GS!__security_check_cookie:
00412df0 3b0d0c704100    cmp     ecx,dword ptr [GS!__security_cookie (0041700c)]
00412df6 f27502          bnd jne GS!__security_check_cookie+0xb (00412dfb)
00412df9 f2c3            bnd ret
00412dfb f2e925e4ffff    bnd jmp GS!ILT+545(___report_gsfailure) (00411226)
00412e01 cc              int     3
00412e02 cc              int     3
00412e03 cc              int     3
00412e04 cc              int     3

이 블로그의 인기 게시물

데일 카네기 인간관계론 정리

Remove-Server-Header

응답 메시지 내 서버 버전 정보 제거 1. Apache 1) 조치 방법 “/etc/htpd/conf/httpd.conf” 파일 안에서 1. ServerTokens OS → ServerTokens Prod 2. ServerSignature On → ServerSignature Off 로 변경한 후 아파치를 재시작하면 헤더 값의 아파치 버전 정보 및 OS 정보를 제거할 수 있다. 2) 참고 URL http://zetawiki.com/wiki/CentOS_ 아파치_보안권장설정_ServerTokens_Prod,_ServerSignature_Off 2. IIS 1) 조치 방법 IIS 6.0 urlscan_setup 실행. 설치. \windows\system32\inetsrv\urlscan\urlscan.ini 파일을 열어 다음 수정(RemoveServerHeader=0 을 RemoveServerHeader=1 로 변경) 서비스에서 IIS Admin Service 재시작. IIS 7.0 IIS 관리자를 열고 관리하려는 수준으로 이동합니다. 기능 보기에서 HTTP 응답 헤더를 두 번 클릭합니다. HTTP 응답 헤더 페이지에서 제거할 헤더를 선택합니다. 작업 창에서 제거를 클릭하고 예를 클릭합니다. 2) 참고 URL IIS 6.0 : http://gonnie.tistory.com/entry/iis6- 응답헤더-감추기 IIS 7.0 : https://technet.microsoft.com/ko-kr/library/cc733102(v=ws.10).aspx 3. jetty 1) 조치 방법 “jetty.xml” 파일에서 jetty.send.server.version=false 설정 2) 참고 URL http://attenuated-perspicacity.blogspot.kr/2009/09/jetty-61x-hardening.html 4. Nginx ...

American Fuzzy Lop And Address Sanitizer

American Fuzzy Lop And Address Sanitizer Address Sanitizer(ASAN) 단지 gcc/clang에 -fsanitize=address 옵션을 추가하는 것으로 간단히 사용할 수 있지만 그 효과는 충분하다. Example Out Of Bounds Read #include <stdio.h> int main() { int a[ 2 ] = { 3 , 1 }; int i = 2 ; printf ( "%i\n" , a[i]); } 예제 파일을 OutOfBoundsRead.c 로 생성하고 ASAN 옵션을 지정하여 clang 으로 컴파일하자. clang -g -fsanitize = address -fno -omit -frame -pointer OutOfBoundsRead . c -o OutOfBoundsRead 생성된 OutBoundsRead 파일을 실행하면 다음과 같은 결과를 볼 수 있다. ================================================================= ==3678==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffc0ba87428 at pc 0x47b7db bp 0x7ffc0ba87390 sp 0x7ffc0ba87388 READ of size 4 at 0x7ffc0ba87428 thread T0 ==3678==WARNING: Trying to symbolize code, but external symbolizer is not initialized! #0 0x47b7da (/root/ASAN/OutOfBoundsRead+0x47b7da) #1 0x7faba0260f44 (/lib/x86_64-linux-gnu/libc.so.6+0x21f44) #2 0x...