LoginSignup
4
3

More than 1 year has passed since last update.

Docker コンテナで特定のコマンドしか実行できないユーザーを作成したい

Posted at

目的

Docker コンテナで特定のコマンドしか実行できないユーザーを作成したい。
Docker のデフォルト設定では、コンテナ内のプロセスはroot権限で実行される。
これをまず、root 以外のユーザーで実行させるようにしたい。
更にそのユーザが使えるコマンドを制限したい。
はじめから使えるコマンドが少ない軽量な Docker Image を使えばよいのかもしれない。
取りあえず、centos:7 の Docker Image を元に、使えるコマンドを awk に制限してみます。

1.ユーザー作成

awk コマンドは許可される awker という名前のユーザにします。
※awk 使えるといろいろと出来てしまいますが

// コンテナに入って
$ docker run -it centos:7 bash

// ユーザーを作成
# useradd awker

// パスワードも設定しておく
# passwd awker

// rbash(制限付きbash) を登録
# ln -s /bin/bash /bin/rbash
# echo "/bin/rbash" >> /etc/shells && cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash
/bin/rbash

2.ユーザディレクトリを作成

一回、作成したユーザで bash 起動し、ユーザディレクトリを作成する。
そのために、まずコンテナからイメージ作成する。

// コンテナからイメージ作成
$ docker commit [container_id] awk_base

// 作成したイメージを元に、制限したいユーザー(awker)で bash 起動する
$ docker run -u awker -it awk_base bash

// シェルを rbash に変更する
$ chsh
Changing shell for awker.
New shell [/bin/bash]: /bin/rbash
Password: {ユーザ作成時に設定したパスワード}
Shell changed.

3. ~/.bash_profile の所有者・グループを root にする

awker 自身では変更できないようにするため。

// コンテナからイメージ作成
$ docker commit [container_id] awk_base2

// 作成したイメージを元に root で bash 起動する
$ docker run -u root -it awk_base2 bash

// .bash_profile の所有者・グループを root にする
# cd /home/awker/
# chown root .bash_profile
# chgrp root .bash_profile
# chmod 755 .bash_profile
# ls -al .bash_profile
-rwxr-xr-x 1 root root 193 Apr  1  2020 .bash_profile

4. 使えるコマンドを設定する

// PATH を定義(/home/awker 以外でも構わない)
# echo "export PATH=/home/awker" >> .bash_profile

// PATHで定義した場所に、使いたいコマンド(awk)へのリンクを付ける
# ln -s /bin/awk /home/awker/awk

// コンテナからイメージ作成
$ docker commit [container_id] awk_img

これで awker ユーザーは、awk しか使えないイメージが作成できたはず。

5. そのコンテナを使ってみる

$ docker run -u awker -it awk_img bash --login
// ls 実行できない
$ ls
bash: ls: command not found

// 恐ろしいコマンドも実行できない
$ rm -rf /
bash: rm: command not found

cat ではファイルの中身が見れないですが

$ cat .bash_profile
bash: cat: command not found

awk では確認ができる。

$ awk '{print}' .bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/.local/bin:$HOME/bin

export PATH
export PATH=/home/awker

あと、bash の組み込みコマンドである cd, help, echo などは実行できる。

需要はあるのか?

コンテナ上でアドホックにコマンドを実行できるような仕組みを用意したけど、出来る限り余計なコマンドを実行させないようにしたい(など)

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3