기본 콘텐츠로 건너뛰기

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 0x47b42c (/root/ASAN/OutOfBoundsRead+0x47b42c)

Address 0x7ffc0ba87428 is located in stack of thread T0 at offset 40 in frame
#0 0x47b4ff (/root/ASAN/OutOfBoundsRead+0x47b4ff)

This frame has 2 object(s):
[32, 40) ‘a’ <== Memory access at offset 40 overflows this variable
[96, 100) ‘i’
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
(longjmp and C++ exceptions are supported)
SUMMARY: AddressSanitizer: stack-buffer-overflow ??:0 ??
Shadow bytes around the buggy address:
0x100001748e30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748e40: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748e50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748e60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748e70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x100001748e80: f1 f1 f1 f1 00[f4]f4 f4 f2 f2 f2 f2 04 f4 f4 f4
0x100001748e90: f3 f3 f3 f3 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748ea0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748eb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748ec0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100001748ed0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Heap right redzone: fb
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack partial redzone: f4
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
ASan internal: fe
==3678==ABORTING

User After Free

#include <stdio.h>
#include <stdlib.h>
int main() {
  char *c = calloc(10, 1);
  printf("%i\n", c[0]);
  free(c);
  printf("%i\n", c[1]);
}

예제 파일을 UserAfterFree.c로 생성하고 ASAN 옵션을 지정하여 clang으로 컴파일하자.

clang -g -fsanitize=address -fno-omit-frame-pointer UserAfterFree.c -o UserAgentFree

생성된 UserAgentFree 파일을 실행하면 다음과 같은 결과를 볼 수 있다.

=================================================================
==3563==ERROR: AddressSanitizer: heap-use-after-free on address 0x60200000eff1 at pc 0x47b57c bp 0x7ffc2a357b60 sp 0x7ffc2a357b58
READ of size 1 at 0x60200000eff1 thread T0
==3563==WARNING: Trying to symbolize code, but external symbolizer is not initialized!
#0 0x47b57b (/root/ASAN/UserAgentFree+0x47b57b)
#1 0x7ff1c77def44 (/lib/x86_64-linux-gnu/libc.so.6+0x21f44)
#2 0x47b42c (/root/ASAN/UserAgentFree+0x47b42c)

0x60200000eff1 is located 1 bytes inside of 10-byte region [0x60200000eff0,0x60200000effa)
freed by thread T0 here:
#0 0x4651c9 (/root/ASAN/UserAgentFree+0x4651c9)
#1 0x47b535 (/root/ASAN/UserAgentFree+0x47b535)
#2 0x7ff1c77def44 (/lib/x86_64-linux-gnu/libc.so.6+0x21f44)

previously allocated by thread T0 here:
#0 0x465419 (/root/ASAN/UserAgentFree+0x465419)
#1 0x47b504 (/root/ASAN/UserAgentFree+0x47b504)
#2 0x7ff1c77def44 (/lib/x86_64-linux-gnu/libc.so.6+0x21f44)

SUMMARY: AddressSanitizer: heap-use-after-free ??:0 ??
Shadow bytes around the buggy address:
0x0c047fff9da0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9db0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9dc0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9dd0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9de0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
=>0x0c047fff9df0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa[fd]fd
0x0c047fff9e00: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9e10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9e20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9e30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9e40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Heap right redzone: fb
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack partial redzone: f4
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
ASan internal: fe
==3563==ABORTING

참고 : Clang 6 documentation - AddressSanitizer

American Fuzzy Lop

가장 인기있는 퍼징 도구 중 하나로 American Fuzzy Lop을 이용하여 발견한 다양한 취약점들이 존재한다. American Fuzzy Lop 사용 시에 ASAN을 설정하면 (Set AFL_USE_ASAN=1 and add "-m none")더 강력한 퍼징을 수행할 수 있다.

AFL을 설치 시 포함된 test-instr.c 파일을 이용하여 테스트를 진행하자.

Example

test-instr.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char** argv) {

  char buf[8];

  if (read(0, buf, 8) < 1) {
    printf("Hum?\n");
    exit(1);
  }

  if (buf[0] == '0')
    printf("Looks like a zero to me!\n");
  else
    printf("A non-zero value? How quaint!\n");

  exit(0);

}

먼저 afl-gcc를 이용하여 컴파일을 한다. (C++인 경우 afl-g++를 사용한다.)

afl-gcc -o test-instr test-instr.c

이제 퍼징 테스트를 수행해야 하는 데, 입력 값에 따라 명령어를 다르게 설정해야한다.

  • Standard input
afl-fuzz -i "Testcase 디렉토리" -o "결과를 저장할 디렉토리" "Fuzzing 바이너리" "파라미터"
afl-fuzz -i testcase_dir -o findings_dir /path/to/program [...params...]
  • File
afl-fuzz -i "Testcase 디렉토리" -o "결과를 저장할 디렉토리" "Fuzzing 바이너리" @@
afl-fuzz -i testcase_dir -o findings_dir /path/to/program @@

테스트에 사용할 test-instr의 경우 Standard input 형태로 명령어를 구성하면 된다.

afl-fuzz -i ./testcases/others/text/ -o ./afl-out/ ./test-instr

Truble Shooting

afl-fuzz 2.44b by lcamtuf@google.com
[+] You have 1 CPU core and 6 runnable tasks (utilization: 600%).
[*] Checking core_pattern…

[-] Hmm, your system is configured to send core dump notifications to >an
external utility. This will cause issues: there will be an >extended delay
between stumbling upon a crash and having this information >relayed to the
fuzzer via the standard waitpid() API.

To avoid having crashes misinterpreted as timeouts, please log in >as root
and temporarily modify /proc/sys/kernel/core_pattern, like so:

echo core >/proc/sys/kernel/core_pattern

[-] PROGRAM ABORT : Pipe at the beginning of ‘core_pattern’
Location : check_crash_handling(), afl-fuzz.c:7246

위와 같은 에러가 발생 시 에러 구문에서 출력된 명령어를 수행하면 정상적으로 사용이 가능하다.

echo core >/proc/sys/kernel/core_pattern

참고 : AFL fuzz(american fuzzy lop) Fuzzing Tool 사용하기

LIBFUZZER

LIBFUZZER는 매우 유용한 퍼징 도구로 American Fuzzy Lop과 함께 활용하면 좋다. American Fuzzy Lop와 차이점으로 American Fuzzy Lop는 실행 형태인 반면 LIBFUZZER는 함수 형태로 퍼징 테스트를 위해서 초기 작업이 필요하다. (HeartBleed 취약점을 찾을 때 까지 AFL은 최대 6시간이 소요되지만, LIBFUZZER를 이용하면 5분이면 가능하다.)

Install

Local & VM

# git 설치 및 튜토리얼 다운로드
sudo apt-get --yes install git
git clone https://github.com/google/fuzzer-test-suite.git FTS
./FTS/tutorial/install-deps.sh  # Get deps
./FTS/tutorial/install-clang.sh # Get fresh clang binaries
# libFuzzer sources 빌드
svn co https://llvm.org/svn/llvm-project/llvm/trunk/lib/Fuzzer
Fuzzer/build.sh

Docker

install docker
docker run --cap-add SYS_PTRACE -ti libfuzzertutorial/base

Example

fuzz_me.cc

튜토리얼에 포함된 fuzz_me.cc 소스코드를 이용하여 LIBFUZZER 이용 방법을 살펴보자.

#include <stdint.h>
#include <stddef.h>

bool FuzzMe(const uint8_t *Data,
            size_t DataSize) {
  return DataSize >= 3 &&
      Data[0] == 'F' &&
      Data[1] == 'U' &&
      Data[2] == 'Z' &&
      Data[3] == 'Z';  // :‑<
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  FuzzMe(Data, Size);
  return 0;
}

LIBFUZZER를 이용하여 퍼징 테스트를 진행해보자.

clang++ -g -fsanitize=address -fsanitize-coverage=trace-pc-guard FTS/tutorial/fuzz_me.cc libFuzzer.a 
./a.out

동작에 성공했다면 a.out 파일 실행 시 다음과 같은 정보를 출력하는 것을 확인할 수 있다. (clang++ 옵션에 지정한 ASAN 결과도 함께 포함되어 있다.)

INFO: Seed: 85630000
INFO: Loaded 1 modules (7 guards): [0x743e10, 0x743e2c),
INFO: -max_len is not provided, using 64
INFO: A corpus is not provided, starting from an empty corpus
#0 READ units: 1
#1 INITED cov: 3 ft: 3 corp: 1/1b exec/s: 0 rss: 14Mb
#3 NEW cov: 4 ft: 4 corp: 2/6b exec/s: 0 rss: 15Mb L: 5 MS: 2 ChangeBit-CMP- DE: “\x01\x00\x00\x00”-
#3736 NEW cov: 5 ft: 5 corp: 3/34b exec/s: 0 rss: 15Mb L: 28 MS: 5 InsertByte-CopyPart-EraseBytes-EraseBytes-InsertRepeatedBytes-
#85472 NEW cov: 6 ft: 6 corp: 4/62b exec/s: 0 rss: 21Mb L: 28 MS: 1 ChangeByte-
#166628 NEW cov: 7 ft: 7 corp: 5/104b exec/s: 0 rss: 26Mb L: 42 MS: 2 PersAutoDict-InsertRepeatedBytes- DE: “\x01\x00\x00\x00”-

=================================================================

==116:116==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020001bb8f3 at pc 0x0000004eb623 bp 0x7ffcafdae280 sp 0x7ffcafdae278
READ of size 1 at 0x6020001bb8f3 thread T0
#0 0x4eb622 in FuzzMe(unsigned char const*, unsigned long) /root/FTS/tutorial/fuzz_me.cc:10:7
#1 0x4eb68e in LLVMFuzzerTestOneInput /root/FTS/tutorial/fuzz_me.cc:14:3
#2 0x4f4d83 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /root/Fuzzer/FuzzerLoop.cpp:493:13
#3 0x4f4fb0 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long) /root/Fuzzer/FuzzerLoop.cpp:450:3
#4 0x4f631b in fuzzer::Fuzzer::MutateAndTestOne() /root/Fuzzer/FuzzerLoop.cpp:700:30
#5 0x4f6587 in fuzzer::Fuzzer::Loop() /root/Fuzzer/FuzzerLoop.cpp:732:5
#6 0x4edba8 in fuzzer::FuzzerDriver(int*, char***, int ()(unsigned char const, unsigned long)) /root/Fuzzer/FuzzerDriver.cpp:567:6
#7 0x4eb700 in main /root/Fuzzer/FuzzerMain.cpp:20:10
#8 0x7f6049f7982f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
#9 0x41c5e8 in _start (/root/a.out+0x41c5e8)

0x6020001bb8f3 is located 0 bytes to the right of 3-byte region [0x6020001bb8f0,0x6020001bb8f3)
allocated by thread T0 here:
#0 0x4e8752 in operator new[](unsigned long) (/root/a.out+0x4e8752)
#1 0x4f4cc9 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /root/Fuzzer/FuzzerLoop.cpp:484:23
#2 0x4f4fb0 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long) /root/Fuzzer/FuzzerLoop.cpp:450:3
#3 0x4f631b in fuzzer::Fuzzer::MutateAndTestOne() /root/Fuzzer/FuzzerLoop.cpp:700:30
#4 0x4f6587 in fuzzer::Fuzzer::Loop() /root/Fuzzer/FuzzerLoop.cpp:732:5
#5 0x4edba8 in fuzzer::FuzzerDriver(int*, char***, int ()(unsigned char const, unsigned long)) /root/Fuzzer/FuzzerDriver.cpp:567:6
#6 0x4eb700 in main /root/Fuzzer/FuzzerMain.cpp:20:10
#7 0x7f6049f7982f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)

SUMMARY: AddressSanitizer: heap-buffer-overflow /root/FTS/tutorial/fuzz_me.cc:10:7 in FuzzMe(unsigned char const*, unsigned long)
Shadow bytes around the buggy address:
0x0c048002f6c0: fa fa fd fd fa fa fd fd fa fa fd fa fa fa fd fa
0x0c048002f6d0: fa fa fd fa fa fa fd fa fa fa fd fa fa fa fd fa
0x0c048002f6e0: fa fa fd fa fa fa fd fa fa fa fd fa fa fa fd fa
0x0c048002f6f0: fa fa fd fa fa fa fd fa fa fa fd fa fa fa fd fa
0x0c048002f700: fa fa fd fa fa fa fd fd fa fa fd fa fa fa fd fa
=>0x0c048002f710: fa fa fd fa fa fa fd fa fa fa fd fa fa fa[03]fa
0x0c048002f720: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c048002f730: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c048002f740: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c048002f750: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c048002f760: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
==116:116==ABORTING
MS: 4 EraseBytes-InsertByte-ChangeBinInt-CrossOver-; base unit: 3a54258a942e4f29a7d84ceb41471a56cc36609a
0x46,0x55,0x5a,
FUZ
artifact_prefix=’./’; Test unit written to ./crash-0eb8e4ed029b774d80f2b66408203801cb982a60
Base64: RlVa

Other Sanitizers

  • UBSAN (Undefined Behavior Sanitizer) : 쉽게 사용 가능하지만, 찾아내는 취약점의 대부분이 유효하지 않다.
  • MSAN (Memory Sanitizer) : 초기화되지 않은 메모리를 찾는 데 사용한다.
  • TSAN (Thread Sanitizer) : C++로 개발된 큰 프로젝트에서 사용한다.

이 블로그의 인기 게시물

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

X-Frame-Options-Test

X-Frame-Options 테스트하기 X-Frame-Options 페이지 구성 시 삽입된 프레임의 출처를 검증하여 허용하지 않는 페이지 URL일 경우 해당 프레임을 포함하지 않는 확장 응답 헤더이다. 보안 목적으로 사용되는 확장 헤더로 아직 적용되지 않은 사이트들이 많지만 앞으로 점차 적용될 것으로 보인다. X-Frame OptionsDENY, SAMEORIGIN, ALLOW-FROM 옵션을 이용하여 세부 정책을 설정한다. 옵션 설명 DENY Frame 비허용 SAMEORIGIN 동일한 ORIGIN에 해당하는 Frame만 허용 ALLOW-FROM 지정된 ORIGIN에 해당하는 Frame만 허용 크롬 4.1 , IE 8 , 오페라 10.5 , 사파리 4.0 , 파이어폭스 3.6.9 이상에서는 DENY , SAMEORIGIN 이 적용되며, ALLOW-FROM 은 각 브라우저 마다 지원 현황이 다르다. https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/X-Frame-Options 해당 확장헤더는 브라우저에서 처리하는 응답 헤더이므로 미지원 브라우저 사용 시 설정과 무관하게 페이지 내 포함된 모든 Frame을 출력한다. (검증 테스트: Opera 5.0.0) 테스트 코드 DENY <!DOCTYPE html> < html lang = "en" > < head > < meta http-equiv = "X-Frame-Options" content = "deny" /> < title > Deny option Test </ title > </ head > < bod

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