본문 바로가기

Wargame/Bandit

[ Docker ] Bandit Wargame 만들기 ( 1 / 33 )

워게임 중 하나인 Bandit 문제를 직접 생성하는 방법을 기술한다

Bandit은 사용자가 ssh를 통하여 서버에 접속하여 문제의 힌트를 통해 다음 문제에 대한 정답을 찾아내어
다음 문제로 접속하는 방식의 게임이다.
사용자는 bandit0 유저로 주어진 패스워드를 통해 접속하여 bandit1 부터 순차적으로 bandit2, bandit3 등의 유저의 패스워드를

구하여 다음 레벨로 진입한다.

1. Bandit 이미지 및 실행 파일 설치 ( cmd 실행 )

:: docker toolbox 로 이용하여 도커 사용시 아래 명령어를 이용하여 docker toolbox 실행
:: docker-machine start

:: centos 이미지 확인
:: [ https://hub.docker.com/ ] 에서 태그(버전) 확인
docker search centos

:: centos8 이미지 다운로드
docker pull centos:8

:: centos8 이미지 다운로드 확인
docker images

:: centos8 bandit 이라는 이름으로 설치
:: -d : background 로 실행
:: -p : 포트 포워딩
:: -it : 터미널 입력모드 사용
:: --privileged ~ init : systemctl 명령을 사용할 수 있도록 함
:: --cap-add : docker를 실행하는 OS 파라미터에 해당하는 내역을 동기화
docker run --privileged --cap-add=SYS_TIME -d -it -p 2220:2220 --name bandit centos:8 init

:: 설치 내역 확인
docker ps -a

:: 설치한 bandit  bash 쉘로 접속 접속
docker exec -it bandit /bin/bash

 

2. Bandit 접속 SSH 설치 ( bash 접속 상태 )

sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-Linux-*

sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-Linux-*

# ssh 설치
# bzip2 : 압축해제 bzip2 설치
# openssh-clients : 원격접속프로그램 ssh 설치
# gcc : c컴파일러 gcc 설치
# nmap-ncat : 포트 접속 프로그램 nc 설치
# openssl : SSL 연결 프로그램 openssl 설치
# openssl-devel : SSL 개발 라이브러리 gcc 로 컴파일 할 때 -lssl -lcrypto 를 링크할 때 사용
# nmap : 서버 포트 스캔 툴 nmap 설치
# diffutils : diff 명령어 설치
yum install -y openssh-server passwd file vim-common bzip2 openssh-clients gcc nmap-ncat openssl openssl-devel nmap diffutils

# EPEL 저장소 추가
yum install -y epel-release

# dash 쉘 설치
yum install -y dash

# 기본 쉘을 dash 쉘로 변경
ln -sf /usr/bin/dash /bin/sh

# screen : 가상 터미널 관리 프로그램 screen 설치
yum install -y screen

# cron : 잡 스케줄러 crond 설치
yum install -y cronie

# crond 실행
systemctl start crond

# crond 재부팅 시 실행되도록 서비스 등록
systemctl enable crond

# git : 형상관리 git 설치
yum install -y git

# util-linux-user : 로그인 쉘 변경 툴 chsh 설치
yum install util-linux-user

sed -i 's/^Port.*//g' /etc/ssh/sshd_config
sed -i 's/^#Port.*//g' /etc/ssh/sshd_config

echo "Port 2220" >> /etc/ssh/sshd_config

sed -i 's/^#PasswordAuthentication.*//g' /etc/ssh/sshd_config
sed -i 's/^PasswordAuthentication.*//g' /etc/ssh/sshd_config

echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config

# root 비밀번호 설정
echo -e "root\nroot" | passwd

systemctl restart sshd

systemctl enable sshd

 

3. Bandit 접속 SSH 접속 ( cmd 실행 )

:: docker-toolbox로 실행시 docker-toolbox 에 해당하는 ip로 접속해야함
:: 일반 도커 사용시 pc 아이피로 진행
:: docker-toolbox ip 확인
docker-machine ip

ssh root@192.168.99.101 -p 2220

 

4. bandit 환경 셋팅

# hostname 영구적 변경
echo -e "bandit.otw.local" > /etc/hostname

# 원본과 동일하게 hostname 파일의 개행문자 삭제후 임시 파일에 저장
tr -d "\n" < /etc/hostname > /tmp/hostname

# 임시파일 내용 덮어쓰기 후 임시파일 삭제
cat /tmp/hostname > /etc/hostname && rm -rf /tmp/hostname

# hostname 일시적 변경
hostname bandit.otw.local

# 기본 생성 파일 변경
# .profile      : bash가 아닌 다를 쉘로 로그인을 하여도 로드된다. [ 1순위 실행 ]
# .bash_profile : bash를 이용하여 로그인할 때 로드된다. [ 2순위 실행 ]
# .bashrc       : bash가 실행될 때마다 로드된다. (ex. su) [ 3순위 실행 ]
# .bash_logout  : bash에서 logout 할 때 로드된다.
# .bash_history : 유저가 접속해서 입력한 명령어들이 저장이된다.
mv /etc/skel/.bash_profile /etc/skel/.profile

# 모든 사용자에게 히스토리 파일 생성을 비활성화 한다.
echo "unset HISTFILE" >> /etc/profile

# profile 내용 적용
source /etc/profile

# 쉘 접속 후 실행 내역 적용
cat > /etc/skel/.bashrc <<"BASHRC"
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
	# We have color support; assume it's compliant with Ecma-48
	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
	# a case would tend to support setf rather than setaf.)
	color_prompt=yes
    else
	color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi
BASHRC

# 로그인 성공후 보여줄 메세지를 작성
cat > /etc/motd <<"MOTD"

      ,----..            ,----,          .---.
     /   /   \         ,/   .`|         /. ./|
    /   .     :      ,`   .'  :     .--'.  ' ;
   .   /   ;.  \   ;    ;     /    /__./ \ : |
  .   ;   /  ` ; .'___,/    ,' .--'.  '   \' .
  ;   |  ; \ ; | |    :     | /___/ \ |    ' '
  |   :  | ; | ' ;    |.';  ; ;   \  \;      :
  .   |  ' ' ' : `----'  |  |  \   ;  `      |
  '   ;  \; /  |     '   :  ;   .   \    .\  ;
   \   \  ',  /      |   |  '    \   \   ' \ |
    ;   :    /       '   :  |     :   '  |--"
     \   \ .'        ;   |.'       \   \ ;
  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!


MOTD

# 원격접속 시도시 보여줄 메세지를 작성
cat <<ISSUE_NET > /etc/issue.net
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames


ISSUE_NET

# 콘솔 접속 시도시 보여줄 메시지를 작성
cat <<ISSUE > /etc/issue
Devuan GNU/Linux ascii \n \l


ISSUE

# Banner 보여주도록 변경
sed -i "s/^#Banner.*/Banner \/etc\/issue.net/g" /etc/ssh/sshd_config

sed -i "s/^Banner.*/Banner \/etc\/issue.net/g" /etc/ssh/sshd_config

# last login 표시하지 않도록 변경
sed -i "s/^#PrintLastLog.*/PrintLastLog no/g" /etc/ssh/sshd_config

sed -i "s/^PrintLastLog.*/PrintLastLog no/g" /etc/ssh/sshd_config

# default vi set number
echo set nu >> /etc/virc

# su 명령어를 root만 사용 가능하도록 수정
# [ auth		required	pam_wheel.so use_uid ] 문장이 있으면 삭제(재추가를 위해)
sed -i '/^auth[[:space:]]\+required[[:space:]]\+pam_wheel\.so[[:space:]]\+use_uid[[:space:]]*$/d' /etc/pam.d/su

# [ auth       required     pam_deny.so ] 문장이 있으면 삭제(재추가를 위해)
sed -i '/^auth[[:space:]]\+required[[:space:]]\+pam_deny\.so[[:space:]]*$/d' /etc/pam.d/su

# [ auth		required	pam_wheel.so use_uid ] 를 추가하여 su 명령어를 제한된 사용자만 사용하도록 함
echo -e "auth\t\trequired\tpam_wheel.so use_uid" >> /etc/pam.d/su

# [ auth       required     pam_deny.so ] 를 추가하여 su 명령어를 제한된 사용자만 사용하도록 함
echo -e "auth\t\trequired\tpam_deny.so" >> /etc/pam.d/su

# wheel 그룹에 root 사용자가 있는지 확인
grep wheel /etc/group

# wheel 그룹에 root 사용자 추가
usermod -aG wheel root

# 패스워드 저장 기본 폴더 생성
mkdir -p /etc/bandit_pass

# 터미널 종료
exit

 

# 참조사이트

https://overthewire.org/wargames/bandit/