Computer Security

#9 Wargame bandit 7 (Level13 ~ Level15), ssh,리눅스 디렉토리,nc명령어 본문

Wargame:Bandit

#9 Wargame bandit 7 (Level13 ~ Level15), ssh,리눅스 디렉토리,nc명령어

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

Level13 -> Level14

Level13

다음 레벨의 비밀번호는 /etc/bandit_pass/bandit14에 저장되며 bandit14 사용자만 읽을 수 있습니다. 
이 수준의 경우 다음 암호를 얻지 못하지만 다음 수준에 로그인하는 데 사용할 수 있는 개인 SSH 키를 얻습니다. 
참고: localhost는 작업 중인 시스템을 나타내는 호스트 이름입니다.

위 문제를 해결하려면, ssh 개념에 대해 알고 있어야 한다.


SSH 기본개념

SSH는 무엇이고 어떻게 사용하며 어떤 부분이 편리한지에 대해 알아본다.

 

SSH 소개

  • SSH(Secure Shell)는 원격지 호스트 컴퓨터에 접속하기 위해 사용되는 인터넷 프로토콜이다.
  • 뜻 그대로 보안 셸이다.
  • 기존의 유닉스 시스템 셸에 원격 접속하기 위해 사용하던 텔넷은 암호화가 이루어지지 않아 계정 정보가 탈취될 위험이 높으므로, 여기에 암호화 기능을 추가하여 1995년에 나온 프로토콜이다.(SSH는 암호화 기법을 사용하기 때문에, 통신이 노출된다고 하더라도 이해할 수 없는 암호화된 문자로 보인다.)
  • 셸로 원격 접속을 하는 것이므로 기본적으로 CLI 상에서 작업을 하게 된다.
  • 기본 포트는 22번이다.

SSH 키(key)

서버에 접속할때 비밀번호 대신 key를 제출하는 방식이다. 비밀번호보다 높은 수준의 보안요건을 필요로 할때 사용된다.

동작하는 방식

  • SSH 키(Key)는 공개키(public key)와 비공개키(private key)로 이루어지는데 이 두개의 관계를 이해하는 것이 SSH Key를 이해하는데 핵심이다.
  • 키를 생성하면 공개키와 비공개키가 만들어진다.
  • 이 중에 비공개키는 로컬 머신에 위치해야 하고, 공개키는 리모트 머신에 위치해야 한다.(로컬 머신은 SSH Client, 원격 머신은 SSH Server가 설치된 컴퓨터를 의미한다)
  • SSH 접속을 시도하면 SSH Client가 로컬 머신의 비공개키와 원격 머신의 비공개키를 비교해서 둘이 일치하는지를 확인한다.

주요 기능

SSH의 주요 기능은 다음과 같다.

  • 보안 접속을 통한 rsh, rcp, rlogin, rexec, telnet, ftp 등을 제공.
  • IP spoofing (IP스푸핑, 아이피 위/변조 기법중 하나)을 방지하기 위한 기능을 제공.
  • X11 패킷 포워딩 및 일반적인 TCP/IP 패킷 포워딩을 제공.

사용방법

SSH Key 만들기

Generating public/private rsa key pair.
Enter file in which to save the key (기본경로):

다음은 ssh를 사용할때 비밀번호를 사용할지를 묻는다.

당연히 비밀번호를 설정하면 설정하지 않는것 보단 더 안전하다.

이 과정이 끝나면 key가 생성된다.

Created directory '경로'
Enter passphrase (empty for no passphrase):

key를 확인하고 싶다면 저장한 경로로 이동하면 된다.

$ ls -al /경로/

total 16
drwx------   4 user  staff   128  6  7 15:07 .
drwxr-xr-x+ 31 user  staff   992  6  7 15:05 ..
-rw-------   1 user  staff  1876  6  7 15:07 id_rsa
-rw-r--r--   1 user  staff   403  6  7 15:07 id_rsa.pub

이떄 id_rsa가 개인키 id_rsa.pub가 공개키이다.

권한을 보면 개인키는 사용자만이 읽고 쓸 수 있고(600), 공개키는 다른 사용자도 읽을 수 있는 권한(644)을 가지고있다.

접속하고자 하는 컴퓨터에 공개키을 등록해 놓으면, 이후 SSH로 접근할때 개인키와 비교하여 인증한다.

# scp를 통해 원격컴퓨터에 공개키를 전송(다른방법도 상관없다)
$ scp [경로]/id_rsa.pub user@sever_ip:id_rsa.pub

macOS는 기본적으로 SSH Server가 설치되어있다. macOS를 서버로 사용하고싶다면 시스템환경 > 공유 에서 원격로그인을 체크하면 외부에서 SSH를 통해 접근 가능하다.

이제 원격컴퓨터에서는 전달받은 id_rsa.pub를 authorized_keys파일에 등록한다. 만약 .ssh폴더가 없다면 새로 만들고 chmod 700로 설정해준다. (중요한 정보가 저장되어있기 때문에 소유자 외에 접근이 불가능하게 해줘야한다)

# 원격컴퓨터에 authorized_keys에 리다이렉션(추가) 해준다.
$ cat $HOME/id_rsa.pub >> $HOME/.ssh/authorized_keys

이제 SSH를 통해 접속 가능하다.

$ ssh user@sever_ip
# -v 옵션을 사용하면 디버그 모드로 접속과정의 로그를 확인할 수 있다. 

-p 옵션을 사용하면 포트번호를 지정할 수 있다.

$ ssh -p [포트] user@server_ip
# 예
$ ssh -p 2220 bandit0@bandit.labs.overthewire.org

만약 개인키(id_rsa)의 위치를 변경한다면, -i 옵션으로 접속하면 된다.

$ ssh -i [변경된 경로] user@sever_ip

1.자, 위에 ssh를 이용하면 아주 간단히 문제가 풀린다.  ssh의 -i 옵션을 이용해 bandit14 에 접근할 수 있다.

bandit13@bandit:~$ ls
sshkey.private
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

2. 이런식으로 bandit14에 접속하면 성공!

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!

bandit14@bandit:~$

 

Level14 -> Level15

Level14

다음 수준의 암호는 현재 수준의 암호를 localhost의 포트 30000에 제출하여 검색할 수 있습니다.

위 조건을 활용하여 문제를 풀어보자.

 

이 문제를 풀기 위해서, 일단 리눅스 디렉토리와 리눅스 nc명령어 부터 알아보자.


* 리눅스 디렉토리 목록

 

/ : 최상위 디렉토리(루트 디렉토리)

 

/bin : binary의 약자로 실행파일 모음. 일반적으로 사용하는 mv, cat등 명령어 프로그램들이 있음

 

/boot : 부팅과 관련된 파일들이 모여있음

 

/dev : device의 약자로 물리적인 장치들이 파일화 되어 있다.

 

/etc : 각종 환경 설정 파일들이 모여 있음

 

/home : 개인사용자들 디렉토리

 

/lib : 각종 라이브러리 저장 디렉토리

 

/mnt : CD-ROM, 네트워크 파일 시스템 등을 마운트 할때 사용되는 디렉토리

 

/proc : 현재 실행되고 있는 프로세스들이 파일화 되어서 저장되는 디렉토리

 

/root : root계정의 홈 디렉토리

 

/sbin : System-binary의 약자로, 주로 시스템 관리자가 쓰는 시스템 관련 명령어 프로그램들이 모여있다.

 

/tmp : 임시 저장 디렉토리. 일반적으로 모든 사용자들에게 열려 있음

 

/usr : 주로 새로 설치되는 프로그램들이 저장된다. '명령어' 보다는 '프로그램'이라고 부르는게 더 익숙한 놈

들이 저장된다. 윈도우의 Program Files같은 폴더

 

/var : 시스템 로그, 스풀링 파일 들이 저장된다. 메일 서버로 운영될 경우 메일이 여기 저장된다.

 


리눅스 nc 명령어

nc [옵션] [호스트네임] [포트[s]]

-4 : IPv4를 이용한다.
-6 : IPv6를 이용한다.
-D : 디버그 소켓 옵션을 활성화한다.
-h : 사용법을 출력한다.
-i interval : 포트 스캔시 지정한 초(interval)만큼 지연 시간을 둔다.
-l : 듣기 모드로 실행한다.
-n : 호스트명과 포트를 이름이 아닌 숫자로 받는다.
-P proxyuser : 프록시 인증을 위한 사용자명을 지정한다.
-p port : 원격 접속을 위한 로컬의 포트를 지정한다.
-q secs : 표준입력이 끝난 후에 지정한 초(secs)만큼 기다린 후에 종료한다(-1은 대기 상태에서 빠져나오지 않는다).
-r : 원격 포트를 랜덤으로 한다.
-s source_ip_address : 패킷을 보내는 인터페이스의 IP 주소를 지정한다.
-T ToS : ToS(Type of Service)를 지정한다.
-C : 라인의 끝을 CRLF로 처리한다.
-U : 유닉스 도메인 소켓을 이용한다.
-u : UDP 모드로 지정한다.
-v : 상세한 정보를 출력한다.
-w timeout : 접속이나 표준입력이 지정한 시간(timeout) 동안 대기(idle) 상태라면 종료한다.
-x addr[:port] : 프록시 주소와 포트를 지정한다.
-z : 아무 데이터도 전송하지 않고 단지 리스닝 상태의 데몬을 스캔한다.


 

 

1.cat /etc/bandit_pass/bandit14 명령어를 이용해  bandit14의 비밀번호를 확인한다.

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

 

 

 

2. nc 로 30000포트에 비밀번호를 제출해 bandit15의 비밀번호를 확인한다!

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

 

 

 

 

3. 해당 비밀번호를 통해 bandit15에 접속하면 성공!

 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!

bandit15@bandit:~$

 

Comments