Write-up

[bandit] bandit13 ~ bandit19

ch4rli3kop 2019. 2. 27. 10:20
반응형

bandit13 -> bandit14

The password for the next level is stored in /etc/bandit_pass/bandit14 and can only be read by user bandit14. For this level, you don’t get the next password, but you get a private SSH key that can be used to log into the next level. Note: localhost is a hostname that refers to the machine you are working on

bandit13@bandit:~$ ssh -i sshkey.private bandit14@localhost
Could not create directory '/home/bandit13/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
...
bandit14@bandit:~$ cat /etc/bandit_pass/bandit14
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e

개인키 파일이 있다면 가뿐하게 인증이 가능하다. -i 옵션을 이용하여 키 파일을 적용한다.


[+]

ssh 명령어 옵션

-i identity_file
Selects a file from which the identity (private key) for public key authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_dsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ed25519 and ~/.ssh/id_rsa for protocol version 2. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in configuration files). If no certificates have been explicitly specified by the CertificateFile directive, ssh will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames.

bandit14 -> bandit15

The password for the next level can be retrieved by submitting the password of the current level to port 30000 on localhost.

bandit14@bandit:~$ cat /etc/bandit_pass/bandit14
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e

bandit14@bandit:~$ nc localhost 30000
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e
Correct!
BfMYroe26WYalil77FoDi9qh59eK5xNr

bandit15 -> bandit16

The password for the next level can be retrieved by submitting the password of the current level to port 30001 on localhost using SSL encryption.

Helpful note: Getting “HEARTBEATING” and “Read R BLOCK”? Use -ign_eof and read the “CONNECTED COMMANDS” section in the manpage. Next to ‘R’ and ‘Q’, the ‘B’ command also works in this version of that command…

bandit15@bandit:~$ echo "BfMYroe26WYalil77FoDi9qh59eK5xNr" | openssl s_client -connect localhost:30001 -quiet
depth=0 CN = localhost
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = localhost
verify return:1
Correct!
cluFn7wTiGryunymYOu4RcffSxQluehd

SSL protocol을 사용해야하니, openssl을 사용하여 연결해줄 수 있다. s_client는 SSL server에 연결하는 ssl client 프로그램을 실행시키는 명령어이다. echo 명령어로 문자열을 넘겨주기 위해서는 -ign-eof , 혹은 quiet를 붙어야하는데, 이는 문자열을 파이프라인을 통해 다 보낼 때까지 세션을 유지하기 위함이다. -quiet 옵션은 해당 기능에, 인증서 정보까지 출력하지 않는다.


[+]

openssl

DESCRIPTION
OpenSSL is a cryptography toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) network protocols and related cryptography standards required by them.

s_client
This implements a generic SSL/TLS client which can establish a transparent connection to a remote server speaking SSL/TLS. It's intended for testing purposes only and provides only rudimentary interface functionality but internally uses mostly all functionality of the OpenSSL ssl library.

s_server
This implements a generic SSL/TLS server which accepts connections from remote clients speaking SSL/TLS. It's intended for testing purposes only and provides only rudimentary interface functionality but internally uses mostly all functionality of the OpenSSL ssl library. It provides both an own command line oriented protocol for testing SSL functions and a simple HTTP response facility to emulate an SSL/TLS-aware webserver.

s_client 명령어 옵션

-connect host:port
This specifies the host and optional port to connect to. If not specified then an attempt is made to connect to the local host on port 4433.

-ign_eof
inhibit shutting down the connection when end of file is reached in the input.

-quiet
inhibit printing of session and certificate information. This implicitly turns on -ign_eof as well.

bandit16 -> bandit17

The credentials for the next level can be retrieved by submitting the password of the current level to a port on localhost in the range 31000 to 32000. First find out which of these ports have a server listening on them. Then find out which of those speak SSL and which don’t. There is only 1 server that will give the next credentials, the others will simply send back to you whatever you send to it.

1 step

nmap을 이용하여 열린 포트를 스캔한다.

bandit16@bandit:~$ nmap localhost -p31000-32000

Starting Nmap 7.40 ( https://nmap.org ) at 2019-02-26 21:50 CET
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00022s latency).
Not shown: 996 closed ports
PORT     STATE SERVICE
31046/tcp open unknown
31518/tcp open unknown
31691/tcp open unknown
31790/tcp open unknown
31960/tcp open unknown

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

위와 같이 5개의 포트가 열려있음을 확인할 수 있다.

포트 지정과 관련된 정보는 man page에서 얻을 수 있다.

-p <port ranges>: Only scan specified ports
  Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
   --exclude-ports <port ranges>: Exclude the specified ports from scanning


2 step

SSL 포트가 열려있는지 확인하기.

bandit16@bandit:~$ nmap --script ssl-enum-ciphers localhost -p31000-32000

Starting Nmap 7.40 ( https://nmap.org ) at 2019-02-26 22:03 CET
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00021s latency).
Not shown: 996 closed ports
PORT     STATE SERVICE
31046/tcp open unknown
31518/tcp open unknown
| ssl-enum-ciphers:
|   TLSv1.0:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (rsa 1024) - A
| (중략)
|       TLS_RSA_WITH_SEED_CBC_SHA (rsa 1024) - A
|     compressors:
|       NULL
|     cipher preference: client
|     warnings:
|       Weak certificate signature: SHA1
|_ least strength: A
31691/tcp open unknown
31790/tcp open unknown
| ssl-enum-ciphers:
|   TLSv1.0:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (rsa 1024) - A
| (중략)
|       TLS_RSA_WITH_CAMELLIA_256_CBC_SHA (rsa 1024) - A
|     cipher preference: client
|     warnings:
|       Weak certificate signature: SHA1
|_ least strength: A
31960/tcp open unknown

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

ssl-enum-ciphers 스크립트를 활용하면 사용된 cipher를 알 수 있다. 이를 이용하여 SSL 프로토콜을 사용하고 있는지 확인이 가능하다. 31518 포트와 31790 포트에서 SSL 프로토콜이 사용됨을 알 수 있다.

NMAP script의 종류는 다음 링크에서 확인이 가능하다.

https://nmap.org/nsedoc/index.html

NMAP SCRIPTING ENGINE (NSE)

The Nmap Scripting Engine (NSE) is one of Nmap's most powerful and flexible features. It allows users to write (and share) simple scripts (using the Lua programming language[11] ) to automate a wide variety of networking tasks. Those scripts are executed in parallel with the speed and efficiency you expect from Nmap. Users can rely on the growing and diverse set of scripts distributed with Nmap, or write their own to meet custom needs.
...

--script filename|category|directory|expression[,...]
Runs a script scan using the comma-separated list of filenames, script categories, and directories. Each element in the list may also be a Boolean expression describing a more complex set of scripts. Each element is interpreted first as an expression, then as a category, and finally as a file or directory name.

ssl-enum-ciphers

This script repeatedly initiates SSLv3/TLS connections, each time trying a new cipher or compressor while recording whether a host accepts or rejects it. The end result is a list of all the ciphersuites and compressors that a server accepts.


3 step

localhost:31518 에 접속해보면, 입력한 값을 그대로 돌려주는 반면, localhost:31790은 개인 키 값을 돌려준다. 이 개인 키가 bandit17의 개인 키 임을 유추할 수 있으며, 이를 이용하여 bandit17에 접속한 뒤 키 값을 알아낼 수 있다.

localhost:31518
bandit16@bandit:~$ openssl s_client -connect localhost:31518
CONNECTED(00000003)
depth=0 CN = localhost
...
cluFn7wTiGryunymYOu4RcffSxQluehd
cluFn7wTiGryunymYOu4RcffSxQluehd
localhost:31790
bandit16@bandit:~$ echo "cluFn7wTiGryunymYOu4RcffSxQluehd" | openssl s_client -connect localhost:31790 -quiet
depth=0 CN = localhost
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = localhost
verify return:1
Correct!
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0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7YfzOKU4ZxEnabvXnvWkU
YOdjHdSOoKvDQNWu6ucyLRAWFuISeXw9a/9p7ftpxm0TSgyvmfLF2MIAEwyzRqaM
77pBAoGAMmjmIJdjp+Ez8duyn3ieo36yrttF5NSsJLAbxFpdlc1gvtGCWW+9Cq0b
dxviW8+TFVEBl1O4f7HVm6EpTscdDxU+bCXWkfjuRb7Dy9GOtt9JPsX8MBTakzh3
vBgsyi/sN3RqRBcGU40fOoZyfAMT8s1m/uYv52O6IgeuZ/ujbjY=
-----END RSA PRIVATE KEY-----
connect bandit17@localhost
bandit16@bandit:~$ echo "cluFn7wTiGryunymYOu4RcffSxQluehd" | openssl s_client -connect localhost:31790 -quiet > /tmp/TT.cert
depth=0 CN = localhost
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = localhost
verify return:1
bandit16@bandit:~$ ls -al /tmp/TT.cert
-rw-r--r-- 1 bandit16 root 1685 Feb 26 22:27 /tmp/TT.cert

bandit16@bandit:~$ ssh -i /tmp/TT.cert bandit17@localhost
...
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!         @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/tmp/TT.cert' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "/tmp/TT.cert": bad permissions
...

cert 파일을 만든 뒤, 바로 접속하려고 했으나 권한이 너무 열려있어서 접속이 안된다.

chmod 명령어를 이용하여 only user만 rw권한이 있도록 만들어준 뒤 접속한다.

bandit16@bandit:~$ chmod 600 /tmp/TT.cert
bandit16@bandit:~$ ls -al /tmp/TT.cert
-rw------- 1 bandit16 root 1685 Feb 26 22:27 /tmp/TT.cert
bandit16@bandit:~$ ssh -i /tmp/TT.cert bandit17@localhost
...
bandit17@bandit:~$ cat /etc/bandit_pass/bandit17
xLYVMN9WE5zQ5vHacb0sZEVqbrp7nBTn

bandit17 -> bandit18

There are 2 files in the homedirectory: passwords.old and passwords.new. The password for the next level is in passwords.new and is the only line that has been changed between passwords.old and passwords.new

NOTE: if you have solved this level and see ‘Byebye!’ when trying to log into bandit18, this is related to the next level, bandit19

diff 명령어를 사용하여 두 파일의 차이점을 발견할 수 있다. -r 옵션을 줘도 되지만, 디폴트로도 차이점을 제공한다.

bandit17@bandit:~$ diff passwords.new passwords.old 
42c42
< kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
---
> hlbSBPAWJmL6WFDb06gpTx1pPButblOA

bandit18의 key는 "kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd" 이다.

diff

NAME
  diff - compare files line by line
-r, --recursive
    recursively compare any subdirectories found


bandit18 -> bandit19

The password for the next level is stored in a file readme in the homedirectory. Unfortunately, someone has modified .bashrc to log you out when you log in with SSH.

.bashrc는 bash shell에서 환경설정을 위해 로드하는 파일들 중 하나이다. 사용자가 로그인을 시도하면 인증 과정을 거친 뒤, login shell을 띄워주게 되는데, 이 과정에서 profile, bashrc, .bashrc, .bash_profile... 이런 파일들을 로드한다. login shell을 실행하면서 .profile을 로드하게 되는데, 이걸 실행하면서 .bashrc가 불리게 됨. (login-shell은 우리가 아이디, 패스워드를 입력하고 난 뒤, 뜨는 shell을 말한다.)

본 문제에서는 bandit18 계정으로 접속해도 바로 byebye하며 종료되는데, 뭐 이건 문제를 다 푼 뒤에 확인한 거지만, .bashrc 파일의 마지막 2줄에 다음과 같은 명령어가 추가되어서 그렇다.

echo 'Byebye !'
exit 0


이를 우회할 수 있는 방법에 대해서는 여러가지가 있을 수 있겠다. 그 중에 하나로 내가 바로 사용한 방법은 ssh 뒤에 command를 줘서 login shell을 띄워주지 않는 것이다. 저 아래에 있는 ssh man page를 참고하자면, ssh에 명령어를 줄 경우 login shell을 실행하지 않으므로 .bashrc가 실행될 염려가 없다.

다른 방법으로는 bash shell을 실행시키지 않는 법도 있다. profile과 .profile은 bash shell이 아니더라도 로그인할 경우 모두 적용이 되지만, .bashrc .bash_login .bash_profile의 경우 bash shell이 아닌 경우 적용이 되지 않는다. 따라서, /bin/sh shell을 사용하면 .bashrc가 실행되는 것을 우회할 수 있다.

마지막 방법으로는 ssh는 interactive session을 pseudo-terminal (pty)로 받는데, 이걸 tele-type-writer (tty)로 변경하여 .bashrc 스크립트를 적용하지 않는 것이다. -T 옵션을 이용하여 pty를 끄고 tty로 바꿀 수 있다.

bandit17@bandit:~$ ssh bandit18@localhost ls -al
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit17/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!         @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0640 for '/home/bandit17/.ssh/id_rsa' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "/home/bandit17/.ssh/id_rsa": bad permissions
bandit18@localhost's password:
total 24
drwxr-xr-x  2 root     root     4096 Oct 16 14:00 .
drwxr-xr-x 41 root     root     4096 Oct 16 14:00 ..
-rw-r--r--  1 root     root      220 May 15  2017 .bash_logout
-rw-r-----  1 bandit19 bandit18 3549 Oct 16 14:00 .bashrc
-rw-r--r--  1 root     root      675 May 15  2017 .profile
-rw-r-----  1 bandit19 bandit18   33 Oct 16 14:00 readme

bandit17@bandit:~$ ssh bandit18@localhost cat readme
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit17/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!         @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0640 for '/home/bandit17/.ssh/id_rsa' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "/home/bandit17/.ssh/id_rsa": bad permissions
bandit18@localhost's password:
IueksS7Ubh8G3DCwVzrTd8rAVOwq3M5x


If command is specified, it is executed on the remote host instead of a login shell. 를 보면 login shell을 실행하지 않고 명령어를 실행함을 알 수 있다.

DESCRIPTION
ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and UNIX-domain sockets can also be forwarded over the secure channel.

ssh connects and logs into the specified hostname (with optional user name). The user must prove his/her identity to the remote machine using one of several methods (see below).

If command is specified, it is executed on the remote host instead of a login shell.

If an interactive session is requested ssh by default will only request a pseudo-terminal (pty) for interactive sessions when the client has one. The flags -T and -t can be used to override this behaviour.

If a pseudo-terminal has been allocated the user may use the escape characters noted below.

If no pseudo-terminal has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to “none” will also make the session transparent even if a tty is used.
ssh 명령어 옵션
 -T      Disable pseudo-terminal allocation.

-t     Force pseudo-terminal allocation. This can be used to execute
        arbitrary screen-based programs on a remote machine, which can
        be very useful, e.g. when implementing menu services. Multiple
        -t options force tty allocation, even if ssh has no local tty.


그 밖의 다양한 풀이들

bandit17@bandit:~$ ssh bandit18@localhost /bin/sh
bandit17@bandit:~$ ssh bandit18@localhost -t /bin/sh
bandit17@bandit:~$ ssh bandit18@localhost -T
bandit17@bandit:~$ scp bandit18@localhost:readme /tmp/readme
bandit17@bandit:~$ ssh bandit18@localhost "bash --noprofile"

scp는 사실상 그냥 명령어 실행시키는거랑 똑같고, bash --noprofile은 profile을 적용시키지 않고 bash shell을 실행시키는 것이다.


참고: tty pts pty
https://mug896.github.io/bash-shell/tty.html
https://unix.stackexchange.com/questions/4126/what-is-the-exact-difference-between-a-terminal-a-shell-a-tty-and-a-con


반응형

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

[bandit] bandit27 ~ bandit33 (CLEAR)  (0) 2019.02.28
[bandit] bandit19 ~ bandit27  (0) 2019.02.28
[bandit] bandit0 ~ bandit13  (0) 2019.02.27
[CODEGATE2019] god-the-reum writeup  (0) 2019.02.09
[CODEGATE 2019] KingMaker writeup  (0) 2019.02.02