Computer Security

#10 Wargame bandit 8 (Level15 ~ Level17), openssl,nmap명령어, 하트블리드 취약점 본문

Wargame:Bandit

#10 Wargame bandit 8 (Level15 ~ Level17), openssl,nmap명령어, 하트블리드 취약점

쿠리 Kuri 2022. 7. 16. 18:30

Level15 -> Level16

Level15

SSL 암호화를 사용하여 localhost의 포트 30001에 현재 수준의 암호를 제출하여 다음 수준의 암호를 검색할 수 있습니다.
유용한 참고 사항: "HEARTBEATING" 및 "Read R BLOCK"이 필요하십니까? -ign_eof를 사용하고 맨페이지의 "CONNECTED COMMANDS" 섹션을 읽으십시오. 
'R' 및 'Q' 옆에 'B' 명령은 해당 명령의 이 버전에서도 작동합니다.

위 조건을 이용해 다음 비밀번호를 알아내보자!

 

일단 SSL암호화를 사용하라 하니 SSL에 대해 알아보자.

SSL이란 무엇이며 인증서란 무엇인가?

  • SSL(Secure Socket Layer) 프로토콜은 처음에 Netscape사에서 웹서버와 브라우저 사이의 보안을 위해 만들었다.
  • SSL은 Certificate Authority(CA)라 불리는 서드파티로부터 서버와 클라이언트의 인증을 하는데 사용된다.
  • SSL이 어떻게 작동하는지에 대한 간단한 과정은 아래와 같다.
  • [웹브라우저] SSL로 암호화된 페이지 요청 (https:// 로 시작하는 주소요청).
    [웹서버] Public Key를 인증서와 함께 전송
    [웹브라우저] 인증서가 자신이 신용한다고 판단한 CA(일반적으로 trusted root CA라고 불리움)로부터 서명된 것인지 확인
    [웹브라우저] Public Key를 사용해서 랜덤대칭암호화키(Random symmetric encryption key)를 비롯한 URL, http 데이터들을 암호화해서 전송
    [웹서버] Private Key를 이용해서 랜덤 대칭 암호화키와 URL, http 데이터를 복호화
    [웹서버] 요청받은 URL에 대한 응답을 웹브라우저로부터 받은 랜덤 대칭 암호화키를 이용하여 암호화해서 브라우저로 전송
    [웹브라우저] 대칭키를 이용해서 http 데이터와 html 문서를 복호화하고, 화면에 정보를 뿌려준다.

SSL 통신원리

1. 클라이언트가 서버로 접속함

1-1. 클라이언트가 랜덤값을 생성하고 서버로 전달함

1-2. 클라이언트는 자신이 사용할 수 있는 암호화 방식을 전달함

1-3. 세션값을 전달함(처음 연결때는 빈값, 재접속일때는 기존 세션ID)

 

2. 서버가 클라이언트에게 응답함.

2-1. 서버도 랜덤값을 생성하고 전달함.

2-2. 클라이언트가 보내온 암호화 방식 중 하나를 선택해서 클라이언트에게 전달함

2-3. 인증서를 전달함.

 

3-1. 클라이언트는 자신이 보유한 CA 리스트에서 서버 인증서를 발급한 것인지를 확인함

  (해당하지 않으면 <그림1> 의 메세지가 발생)

 

3-2. 클라이언트는 인증서가 CA 에서 발급한게 맞는지 확인하기 위해 CA 공개키로 복화화함

      복호화가 성공했다면 CA가 보증하는 문서가 맞고, 해당 인증서를 전송한 서버를 신뢰할 수 있다고 판단함.

 

4. 클라이언트는 자신의 랜덤값과 서버로부터 받은 랜덤값을 조합해서 pre-master secret 값을 생성함

   pre-master secret 값은 추후 데이터 전송시 대칭키 값으로 사용하게 됨

 

5. pre-master secret 값을 안전하게 전달하기 위해 비대칭키 방식으로 상호 전송

5-1. 클라이언트는 서버 공개키로 pre-master secret 를 암호화해서 서버로 전송

5-2. 서버 공개키는 이미 전달받은 인증서에 포함되어 있음.

 

6. 서버와 클라이언트는 pre-master secret 값을 공유하게 되었음.

   서버와 클라이언트는 이를 master secret 값으로 변환함.

 

7. master secret 을 이용해 세션키를 생성하고 이를 대칭키로 활용하여 데이터를 전송함

 

8. 세션이 끝나면 통신에서 사용한 대칭키를 폐기함.


 

1.일단 접속방법이 ssl을 이용하는거니, 우리는 openssl을 이용한다.

  명령어

1. openssl s_client -connect 도메인:포트

2. openssl s_client -connect 아이피:포트

3. openssl s_client -connect 도메인:포트 -tls1_2

4. openssl s_client -connect 도메인:포트 -tls1_1

5. openssl s_client -connect 도메인:포트 -tls1

bandit15@bandit:~$ openssl s_client -connect localhost:30001
CONNECTED(00000003)
depth=0 CN = localhost
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = localhost
verify return:1
---
Certificate chain
 0 s:/CN=localhost
   i:/CN=localhost
---
Server certificate
-----BEGIN CERTIFICATE-----
MIICBjCCAW+gAwIBAgIEXcVbPTANBgkqhkiG9w0BAQUFADAUMRIwEAYDVQQDDAls
b2NhbGhvc3QwHhcNMjIwMzA5MTk0NzQyWhcNMjMwMzA5MTk0NzQyWjAUMRIwEAYD
VQQDDAlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALDCas6k
DHxTRoxVISHtXOeCwJ8Sax5BZN76Hle8AH6pYTAdv9/FRssWL1xppFAtiGnFvglu
95FJvHEQirY4F0oPBTbtGU2xhzZzkWRL5Yj2C3Q2c99cyh+uWQT7sXPtB8W1osPc
YIo83YkXiArpt28474ZYdl+ohbPtP1oQHBv3AgMBAAGjZTBjMBQGA1UdEQQNMAuC
CWxvY2FsaG9zdDBLBglghkgBhvhCAQ0EPhY8QXV0b21hdGljYWxseSBnZW5lcmF0
ZWQgYnkgTmNhdC4gU2VlIGh0dHBzOi8vbm1hcC5vcmcvbmNhdC8uMA0GCSqGSIb3
DQEBBQUAA4GBAC2693WiK/kXMCauf1fEg5DwuxIfm0saYKiLSceyZo1G4IggqOBO
9JCtvMIV/xRAmYEnPvJmf0JtYv+2fsicaPh9E1GRmU0vGoYDZzA7NTZOgRmHlRKe
ihh/XSGrY7tE1qU+EfizmhcB35iZ7W5INIKlu7oyBWcvk3rI4jtPQeZp
-----END CERTIFICATE-----
subject=/CN=localhost
issuer=/CN=localhost
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 1019 bytes and written 269 bytes
Verification error: self signed certificate
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 7B48BA97EAE3B5ADB2F9BAB0DB12DBA05AA3FC3E2658F8D03A8E7B83116402E5
    Session-ID-ctx:
    Master-Key: 1AAA8E8F630E331F139CF148D0FC06A07B5B78B2721FBD54EE4AE9CE2870F6373925280E5B6C274194CC88291B5A5907
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 7200 (seconds)
    TLS session ticket:
    0000 - d3 53 01 d9 4c 2e 82 50-ef 16 38 c5 d8 1b dd f2   .S..L..P..8.....
    0010 - 53 d8 56 9e 7c a8 c6 d3-4d 0e a2 a8 b6 42 22 23   S.V.|...M....B"#
    0020 - d5 75 8a 18 d4 4a b5 b5-d3 ea ac 3c 85 1c 00 1e   .u...J.....<....
    0030 - 79 21 9d 26 18 00 d8 ea-e1 24 31 ee a7 e6 19 cf   y!.&.....$1.....
    0040 - 05 73 1c 8f 2f 76 77 cc-b8 ae 09 65 38 bd 79 01   .s../vw....e8.y.
    0050 - 00 fc 20 e3 0f db a2 41-6c 19 a7 93 81 2e fa 9e   .. ....Al.......
    0060 - b8 e7 27 a4 53 12 7f 98-c8 d7 cd 21 9f f4 91 b0   ..'.S......!....
    0070 - 83 b8 53 7c e7 8f f0 e2-1b d6 e5 f6 3a bd 10 b6   ..S|........:...
    0080 - df 69 95 c6 ae fd 93 23-b3 af 5d b6 2b 24 1a 19   .i.....#..].+$..
    0090 - f2 ac f8 90 fe b9 28 da-32 18 53 5a fd 24 eb 9d   ......(.2.SZ.$..

    Start Time: 1657638602
    Timeout   : 7200 (sec)
    Verify return code: 18 (self signed certificate)
    Extended master secret: yes
---

2. 접속한 상태에서 bandit15의 비밀번호인 BfMYroe26WYalil77FoDi9qh59eK5xNr를 대입해주면 bandit16의 비밀번호가 나온다!

BfMYroe26WYalil77FoDi9qh59eK5xNr
Correct!
cluFn7wTiGryunymYOu4RcffSxQluehd

 

3. 위 비밀번호를 이용해 bandit16에 접속하면 성공!

--[ Tips ]--

  This machine has a 64bit processor and many security-features enabled
  by default, although ASLR has been switched off.  The following
  compiler flags might be interesting:

    -m32                    compile for 32bit
    -fno-stack-protector    disable ProPolice
    -Wl,-z,norelro          disable relro

  In addition, the execstack tool can be used to flag the stack as
  executable on ELF binaries.

  Finally, network-access is limited for most levels by a local
  firewall.

--[ Tools ]--

 For your convenience we have installed a few usefull tools which you can find
 in the following locations:

    * gef (https://github.com/hugsy/gef) in /usr/local/gef/
    * pwndbg (https://github.com/pwndbg/pwndbg) in /usr/local/pwndbg/
    * peda (https://github.com/longld/peda.git) in /usr/local/peda/
    * gdbinit (https://github.com/gdbinit/Gdbinit) in /usr/local/gdbinit/
    * pwntools (https://github.com/Gallopsled/pwntools)
    * radare2 (http://www.radare.org/)
    * checksec.sh (http://www.trapkit.de/tools/checksec.html) in /usr/local/bin/checksec.sh

--[ More information ]--

  For more information regarding individual wargames, visit
  http://www.overthewire.org/wargames/

  For support, questions or comments, contact us through IRC on
  irc.overthewire.org #wargames.

  Enjoy your stay!

bandit16@bandit:~$

Level16 -> Level17

bandit16

다음 수준의 자격 증명은 현재 수준의 암호를 31000 ~ 32000 범위의 localhost에 있는 포트에 제출하여 검색할 수 있습니다. 
먼저 이러한 포트 중 어떤 포트에서 수신 대기하는 서버가 있는지 확인합니다. 
그런 다음 SSL을 사용하는 것과 그렇지 않은 것을 찾으십시오. 
다음 자격 증명을 제공할 서버는 1개뿐이며 나머지 서버는 귀하가 보내는 모든 것을 다시 귀하에게 보낼 것입니다.

위 조건을 이용하여 비밀번호를 알아내보자!

 

31000이랑 32000사이의 열려있는 포트를 찾아서 들어가라 하니,  nmap 명령어를 이용하겠다.


nmap이란?

  • nmap은 network mapper의 줄임말로 네트워크 탐색과 보안감사를 하는 오픈소스 툴이다.
  • 이 툴은 거대한 네트워크를 반복적으로 스캔할 수 있도록 디자인 되었지만 단일 호스트에서도 잘 작동한다.
  • nmap은 네트워크상의 어떤 호스트가 작동중인지, 그 호스트가 어떤 서비스를 하는지, 운영체제가 무엇인지, 어떤 패킷필터나 방화벽을 쓰는지 등을 알아내기 위해 raw ip 패킷을 사용한다.
  • 이는 보통 보안감사용으로 쓰이지만 네트워크 목록관리 같은 정례적인 작업, 서비스 업그레이드 스케줄 관리, 호스트나 가동중인 서비스의 모니터링에도 유용하다. 

1.nmap 명령어를 이용해 31000-32000사이의 포트를 스캔한다.

bandit16@bandit:~$ nmap -sT -p 31000-32000 localhost

Starting Nmap 7.40 ( https://nmap.org ) at 2022-07-13 08:22 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00032s latency).
Not shown: 996 closed ports
PORT      STATE    SERVICE
31046/tcp open     unknown
31518/tcp filtered unknown
31691/tcp open     unknown
31790/tcp open     unknown
31960/tcp open     unknown

5개중에서 전부 시도해보니 31790포트가 private key를 주는 것을 알았다.

 

 

2.이제 RSA ket 부분을 기록해주자.

bandit16@bandit:~$ mkdir /tmp/ggg
bandit16@bandit:~$ cd /tmp/ggg
bandit16@bandit:/tmp/ggg$ cat > sshkey.private
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0VUYbW
JGTi65CxbCnzc/w4+mqQyvmzpWtMAzJTzAzQxNbkR2MBGySxDLrjg0LWN6sK7wNX
x0YVztz/zbIkPjfkU1jHS+9EbVNj+D1XFOJuaQIDAQABAoIBABagpxpM1aoLWfvD
KHcj10nqcoBc4oE11aFYQwik7xfW+24pRNuDE6SFthOar69jp5RlLwD1NhPx3iBl
J9nOM8OJ0VToum43UOS8YxF8WwhXriYGnc1sskbwpXOUDc9uX4+UESzH22P29ovd
d8WErY0gPxun8pbJLmxkAtWNhpMvfe0050vk9TL5wqb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

 

 

3.ssh로 bandit17에 접속시도를 해보자.

bandit16@bandit:/tmp/ggg$ chmod 600 sshkey.private
bandit16@bandit:/tmp/ggg$ ssh -i sshkey.private bandit17@localhost
Could not create directory '/home/bandit16/.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
Failed to add the host to the list of known hosts (/home/bandit16/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames

Linux bandit.otw.local 5.4.8 x86_64 GNU/Linux

      ,----..            ,----,          .---.
     /   /   \         ,/   .`|         /. ./|
    /   .     :      ,`   .'  :     .--'.  ' ;
   .   /   ;.  \   ;    ;     /    /__./ \ : |
  .   ;   /  ` ; .'___,/    ,' .--'.  '   \' .
  ;   |  ; \ ; | |    :     | /___/ \ |    ' '
  |   :  | ; | ' ;    |.';  ; ;   \  \;      :
  .   |  ' ' ' : `----'  |  |  \   ;  `      |
  '   ;  \; /  |     '   :  ;   .   \    .\  ;
   \   \  ',  /      |   |  '    \   \   ' \ |
    ;   :    /       '   :  |     :   '  |--"
     \   \ .'        ;   |.'       \   \ ;
  www. `---` ver     '---' he       '---" ire.org


Welcome to OverTheWire!

If you find any problems, please report them to Steven or morla on
irc.overthewire.org.

--[ Playing the games ]--

  This machine might hold several wargames.
  If you are playing "somegame", then:

    * USERNAMES are somegame0, somegame1, ...
    * Most LEVELS are stored in /somegame/.
    * PASSWORDS for each level are stored in /etc/somegame_pass/.

  Write-access to homedirectories is disabled. It is advised to create a
  working directory with a hard-to-guess name in /tmp/.  You can use the
  command "mktemp -d" in order to generate a random and hard to guess
  directory in /tmp/.  Read-access to both /tmp/ and /proc/ is disabled
  so that users can not snoop on eachother. Files and directories with
  easily guessable or short names will be periodically deleted!

  Please play nice:

    * don't leave orphan processes running
    * don't leave exploit-files laying around
    * don't annoy other players
    * don't post passwords or spoilers
    * again, DONT POST SPOILERS!
      This includes writeups of your solution on your blog or website!

--[ Tips ]--

  This machine has a 64bit processor and many security-features enabled
  by default, although ASLR has been switched off.  The following
  compiler flags might be interesting:

    -m32                    compile for 32bit
    -fno-stack-protector    disable ProPolice
    -Wl,-z,norelro          disable relro

  In addition, the execstack tool can be used to flag the stack as
  executable on ELF binaries.

  Finally, network-access is limited for most levels by a local
  firewall.

--[ Tools ]--

 For your convenience we have installed a few usefull tools which you can find
 in the following locations:

    * gef (https://github.com/hugsy/gef) in /usr/local/gef/
    * pwndbg (https://github.com/pwndbg/pwndbg) in /usr/local/pwndbg/
    * peda (https://github.com/longld/peda.git) in /usr/local/peda/
    * gdbinit (https://github.com/gdbinit/Gdbinit) in /usr/local/gdbinit/
    * pwntools (https://github.com/Gallopsled/pwntools)
    * radare2 (http://www.radare.org/)
    * checksec.sh (http://www.trapkit.de/tools/checksec.html) in /usr/local/bin/checksec.sh

--[ More information ]--

  For more information regarding individual wargames, visit
  http://www.overthewire.org/wargames/

  For support, questions or comments, contact us through IRC on
  irc.overthewire.org #wargames.

  Enjoy your stay!

bandit17@bandit:~$

 

 

4.cat  /etc/bandit_pass/bandit17을 이용해 비밀번호를 알아내면 성공!

bandit17@bandit:~$ cat /etc/bandit_pass/bandit17
xLYVMN9WE5zQ5vHacb0sZEVqbrp7nBTn

 

 

5. bandit17에 접속해 알아낸 비밀번호로 접속하면 성공!

bandit17

 

 


이 문제에서 port31790에서 rsa private ket를 출력시킨 이유는 바로 하트블리드 취약점 때문이다.

하트블리드(HeartBleed)취약점이란?

  • HeartBleed란 OpenSSL 1.0.1 버전에서 발견된 매우 위험한 취약점 이다.
  • OpenSSL을 구성하고 있는 TLS/DTLS의 HeartBeat 확장규격에서 발견된 취약점으로, 해당 취약점을 이용하면 서버와 클라이언트 사이에 주고받는 정보들을 탈취할 수 있다.
  • * OpenSSL은 정해진 규격의 네트워크 보안 프로토콜을 범용 라이브러리로 구현하기 위한 목적으로 만들어졌으며, SSL이나 TLS를 이용한 암호화를 구현할 수 있다.
  • 강력한 암호화 기능을 제공하기 때문에, 보안이 중요한 대형 포털서비스, 이메일 서비스, 금융권 등에서 데이터 통신 시 OpenSSL을 사용하고 있다.
  • HeartBleed 취약점은 OpenSSL 라이브러리의 구조적인 취약점이다.
  • OpenSSL의 확장규격 중 하나인 HeartBeat는 서버와 클라이언트 사이에 무슨 문제는 없는지 또는 안정적인 연결을 유지하기 위한 목적으로 일정 신호를 주고 받을 때 사용하는 확장규격이다.
  • 클라이언트는 HeartBeat 확장프로토콜을 이용하여 임의의 정보를 그 정보의 길이와 함께 서버에 전송한다.
  • 그 후 서버는 전달받은 정보를 다시 클라이언트에 전달해 주는 과정을 통해 자신의 존재 사실을 알려준다. 
  • 이 때 클라이언트로부터 전달받은 정보와 그 정보의 길이가 일치하지 않는다면, 클라이언트의 요청에 서버는 응답을 하지 않는 것이 정상적인 동작이다.
  • 이번에 발견된 HeartBleed 취약점은 서버가 클라이언트로부터 전달받은 정보의 내용과 그 정보의 길이의 일치 여부를 검증하지 않은 채 정보를 보내주면서 문제가 발생된 것이다. 

 

Comments