본문 바로가기

Wargame/Leviathan

[ Docker ] Leviathan Wargame 만들기 ( 1 / 8 )

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

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

패스워드를 구하여 다음 레벨로 진입한다.

1. Leviathan 이미지 및 실행 파일 설치

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

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

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

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

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

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

 

2. Leviathan 접속 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

# 라이브러리 호출 추적 프로그램 설치
yum install -y ltrace

# perl 명령어 설치
yum install -y perl

# gdb 명령어 설치
yum install -y gdb

# 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

cat <<EOF > /etc/ssh/sshd_config
PasswordAuthentication no
Port 2221

Match LocalPort 2221 User root,behemoth?* Address 127.0.0.1,10.0.0.0/8
    Banner /etc/issue.behemoth.localhost
    AllowUsers root behemoth?*
    PasswordAuthentication no

Match LocalPort 2221 User root,behemoth?*
    Banner /etc/issue.behemoth
    AllowUsers root behemoth?*

Match LocalPort 2221
    Banner /etc/issue.behemoth.fail
    AllowUsers root behemoth?*

Match all
Port 22
Match User root,ubuntu LocalPort 22
    AllowUsers root ubuntu
    PasswordAuthentication no
Match LocalPort 22
    Banner /etc/issue.net
    AllowUsers root ubuntu
    PasswordAuthentication no
Match all

ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding no
PrintMotd yes
AcceptEnv LANG LC_* WECHALL* OTW*
Subsystem    sftp    /usr/lib/openssh/sftp-server
PrintLastLog no

Port 2223

Match LocalPort 2223 User root,leviathan?* Address 127.0.0.1,10.0.0.0/8
    Banner /etc/issue.leviathan.localhost
    AllowUsers root leviathan?*
    PasswordAuthentication no
    PermitRootLogin yes

Match LocalPort 2223 User root,leviathan?*
    Banner /etc/issue.leviathan
    AllowUsers root leviathan?*
    PermitRootLogin yes

Match LocalPort 2223
    Banner /etc/issue.leviathan.fail
    AllowUsers root leviathan?*

Match all
Port 2224

Match LocalPort 2224 User root,manpage?* Address 127.0.0.1,10.0.0.0/8
    Banner /etc/issue.manpage.localhost
    AllowUsers root manpage?*
    PasswordAuthentication no

Match LocalPort 2224 User root,manpage?*
    Banner /etc/issue.manpage
    AllowUsers root manpage?*

Match LocalPort 2224
    Banner /etc/issue.manpage.fail
    AllowUsers root manpage?*

Match all
Port 2225

Match LocalPort 2225 User root,maze?* Address 127.0.0.1,10.0.0.0/8
    Banner /etc/issue.maze.localhost
    AllowUsers root maze?*
    PasswordAuthentication no

Match LocalPort 2225 User root,maze?*
    Banner /etc/issue.maze
    AllowUsers root maze?*

Match LocalPort 2225
    Banner /etc/issue.maze.fail
    AllowUsers root maze?*

Match all
Port 2226

Match LocalPort 2226 User root,narnia?* Address 127.0.0.1,10.0.0.0/8
    Banner /etc/issue.narnia.localhost
    AllowUsers root narnia?*
    PasswordAuthentication no

Match LocalPort 2226 User root,narnia?*
    Banner /etc/issue.narnia
    AllowUsers root narnia?*

Match LocalPort 2226
    Banner /etc/issue.narnia.fail
    AllowUsers root narnia?*

Match all
PasswordAuthentication yes
Port 2227

Match LocalPort 2227 User root,utumno?* Address 127.0.0.1,10.0.0.0/8
    Banner /etc/issue.utumno.localhost
    AllowUsers root utumno?*
    PasswordAuthentication no

Match LocalPort 2227 User root,utumno?*
    Banner /etc/issue.utumno
    AllowUsers root utumno?*

Match LocalPort 2227
    Banner /etc/issue.utumno.fail
    AllowUsers root utumno?*

Match all
Port 2228

Match LocalPort 2228 User root,vortex?* Address 127.0.0.1,10.0.0.0/8
    Banner /etc/issue.vortex.localhost
    AllowUsers root vortex?*
    PasswordAuthentication no

Match LocalPort 2228 User root,vortex?*
    Banner /etc/issue.vortex
    AllowUsers root vortex?*

Match LocalPort 2228
    Banner /etc/issue.vortex.fail
    AllowUsers root vortex?*

Match all
EOF

# sysctl fs.protected_symlinks
# 위 명령어를 통해 심볼릭 링크가 보호 상태인지 확인
# 해당 명령어 결과가 1일 경우 심볼릭 링크로 인한 파일 접근이 제한됨
# 아래 명령어를 통해 일시적으로 보호 상태를 해제할 수 있음
sysctl -w fs.protected_symlinks=0

sed -i "s/^fs\.protected_symlinks\s*.*$//g" /etc/sysctl.conf

# 영구적으로 보호 기능 해제
echo fs.protected_symlinks = 0 >> /etc/sysctl.conf

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

systemctl restart sshd

systemctl enable sshd

 

3. Leviathan 환경 셋팅

# hostname 영구적 변경
echo -e "gibson" > /etc/hostname

# hostname 일시적 변경
hostname "gibson"

# 기본 POSIX 쉘을 비로그인 형태로 실행항 경우 실행되는 파일 지정
# ENV 환경 변수에 지정하면 되므로 기존 ENV 환경 변수 삭제
sed -i "s/^export\s*ENV=.*$//g" /etc/profile

# 비로그인 형태로 쉘을 로그인 할 경우 /etc/shrc 를 실행하도록 수정
echo "export ENV=/etc/shrc" >> /etc/profile

# 기본 시스템 언어 설정 변경을 위해 LC_ALL 환경 변수 삭제
sed -i "s/^export\s*LC_ALL=.*$//g" /etc/profile

echo "export LC_ALL=en_US" >> /etc/profile

# 기본 시스템 언어 설정 변경을 위해 LANGUAGE 환경 변수 삭제
sed -i "s/^export\s*LANGUAGE=.*$//g" /etc/profile

echo "export LANGUAGE=en_US" >> /etc/profile

# 기본 프롬프트가 [ $ ~ ] 형태로 표시되도록 수정
echo "export PS1='$ '" > /etc/shrc

chmod +x /etc/shrc

# 기본 생성 파일 변경
# .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

mv /root/.bash_profile /root/.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 an OverTheWire game server.
            More information on http://www.overthewire.org/wargames

!!! You are trying to log into this SSH server on port 22, which is not intended.

ISSUE_NET

# 콘솔 접속 시도시 보여줄 메시지를 작성
cat <<ISSUE > /etc/issue
Ubuntu 24.04 LTS \n \l

ISSUE

cat <<'ISSUE' > /etc/issue.leviathan.localhost
                   _            _       _   _
                  | | _____   _(_) __ _| |_| |__   __ _ _ __
                  | |/ _ \ \ / / |/ _` | __| '_ \ / _` | '_ \
                  | |  __/\ V /| | (_| | |_| | | | (_| | | | |
                  |_|\___| \_/ |_|\__,_|\__|_| |_|\__,_|_| |_|


                      This is an OverTheWire game server.
            More information on http://www.overthewire.org/wargames

!!! You are trying to log into this SSH server with a password on port 2223 from localhost.
!!! Connecting from localhost is blocked to conserve resources.
!!! Please log out and log in again.

ISSUE

cat <<'ISSUE' > /etc/issue.leviathan
                   _            _       _   _
                  | | _____   _(_) __ _| |_| |__   __ _ _ __
                  | |/ _ \ \ / / |/ _` | __| '_ \ / _` | '_ \
                  | |  __/\ V /| | (_| | |_| | | | (_| | | | |
                  |_|\___| \_/ |_|\__,_|\__|_| |_|\__,_|_| |_|


                      This is an OverTheWire game server.
            More information on http://www.overthewire.org/wargames

ISSUE

cat <<'ISSUE' > /etc/issue.leviathan.fail
                   _            _       _   _
                  | | _____   _(_) __ _| |_| |__   __ _ _ __
                  | |/ _ \ \ / / |/ _` | __| '_ \ / _` | '_ \
                  | |  __/\ V /| | (_| | |_| | | | (_| | | | |
                  |_|\___| \_/ |_|\__,_|\__|_| |_|\__,_|_| |_|


                      This is an OverTheWire game server.
            More information on http://www.overthewire.org/wargames

!!! You are trying to log into this SSH server on port 2223 with a username
!!! that does not match the leviathan game.

ISSUE

# 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/leviathan_pass

# 터미널 종료
exit