0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Linux CentOS】SSH 公開鍵・秘密鍵を用いた接続 Docker編

Posted at

はじめに

Dockerをもちいて、SSH公開鍵認証について検証しました。

SSH接続とは

管理目的で対象のサーバーへ安全に接続し、操作する手段のひとつ。
SSH接続時の認証方式には、パスワード認証と公開鍵認証の2種類ある。

image.png

~/.ssh/known_hosts: 一度もssh接続をしていないサーバにssh接続した際に接続したサーバの情報が保存さ
れるファイル
~/.ssh/authorized_keys: 公開鍵認証でクライアントの公開鍵を登録するファイル
~/.ssh/id_rsa: 公開鍵認証で利用する秘密鍵
~/.ssh/id_rsa.pub: 公開鍵認証で利用する公開鍵

image.png

Dockerによるサーバ構築

CentOSにdockerをインストール

[test@localhost ~]$ su -
パスワード:
[root@localhost ~]# yum install -y yum-utils
メタデータの期限切れの最終確認: 0:01:40 時間前の 2022年01月06日 23時21分08秒  実施しました
依存関係が解決しました
================================================================================
 パッケージ                    Arch        バージョン         Repo        サイズ
================================================================================
インストール:
 yum-utils                     noarch      4.0.21-3.el8       baseos       73 k
アップグレード:
 dnf-plugins-core              noarch      4.0.21-3.el8       baseos       70 k
 python3-dnf-plugins-core      noarch      4.0.21-3.el8       baseos      234 k
...
完了しました!
[root@localhost ~]# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
repo の追加: https://download.docker.com/linux/centos/docker-ce.repo
[root@localhost ~]# yum-config-manager --enable docker-ce-nightly
[root@localhost ~]# yum install -y docker-ce docker-ce-cli containerd.io
メタデータの期限切れの最終確認: 0:00:44 時間前の 2022年01月06日 23時28分27秒  実施しました
依存関係が解決しました
================================================================================
 パッケージ                   Arch   バージョン          リポジトリー     サイズ
================================================================================
インストール:
 containerd.io                x86_64 1.4.12-3.1.el8      docker-ce-stable  28 M
 docker-ce                    x86_64 3:20.10.12-3.el8    docker-ce-stable  22 M
 docker-ce-cli                x86_64 1:20.10.12-3.el8    docker-ce-stable  30 M
...
完了しました!
[root@localhost ~]# systemctl start docker
[root@localhost ~]# systemctl status docker
 docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor pre>
   Active: active (running) since Thu 2022-01-06 23:31:21 EST; 18s ago
     Docs: https://docs.docker.com
 Main PID: 12640 (dockerd)
    Tasks: 7
   Memory: 127.6M
   CGroup: /system.slice/docker.service
           mq12640 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/conta>
...
[root@localhost ~]# yum-config-manager --disable docker-ce-nightly
[root@localhost ~]# docker version
Client: Docker Engine - Community
 Version:           20.10.12
 API version:       1.41
 Go version:        go1.16.12
 Git commit:        e91ed57
 Built:             Mon Dec 13 11:45:22 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true
...

コンテナ作成

自身のローカルPCでDockerを用いて、サーバー(CentOS)を構築する。
以下のDocker hubから、コンテナを取得。ただし、systemdを実行する必要があるのでDockerfileを編集する必要あり。

ここから、ローカル(Bash)での操作を以下に記述します。

[root@localhost ~]# mkdir ssh-centos
[root@localhost ~]# pwd
/root
[root@localhost ~]# cd ssh-centos/
[root@localhost ssh-centos]# vi Dockerfile
[root@localhost ssh-centos]# cat Dockerfile
FROM centos:7
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]
[root@localhost ssh-centos]# docker build -t ssh-centos .
Sending build context to Docker daemon   2.56kB
Step 1/5 : FROM centos:7
...
Successfully built ed1aaec81d11
Successfully tagged ssh-centos:latest
[root@localhost ssh-centos]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
ssh-centos   latest    ed1aaec81d11   33 seconds ago   204MB
centos       7         eeb6ee3f44bd   3 months ago     204MB
[root@localhost ssh-centos]# docker run -d --privileged ssh-centos /sbin/init #--privilegedはコンテナからホストへ接続できるための権限を付与するオプション
a4a6439dcb006149616f1ec18fc4958dd05142909b2945b40c094a382f951d2e
[root@localhost ssh-centos]# docker exec -it a4a6439dcb006149616f1ec18fc4958dd05142909b2945b40c094a382f951d2e bash
[root@a4a6439dcb00 /]#
[root@a4a6439dcb00 /]#
[root@a4a6439dcb00 /]#
[root@a4a6439dcb00 /]# ls
anaconda-post.log  dev  home  lib64  mnt  proc  run   srv  tmp  var
bin                etc  lib   media  opt  root  sbin  sys  usr

編集したDockerfile

FROM centos:7
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]

これで、無事にコンテナを起動することができました。

コンテナの設定

ssh接続をするために色々インストールします。

[root@a4a6439dcb00 /]# yum install openssh-server -y
Loaded plugins: fastestmirror, ovl
Determining fastest mirrors
...
Complete!
[root@a4a6439dcb00 /]# systemctl start sshd
[root@a4a6439dcb00 /]# systemctl status sshd
 sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2022-01-07 04:44:58 UTC; 16s ago
     Docs: man:sshd(8)
           man:sshd_config(5)
 Main PID: 133 (sshd)
   CGroup: /docker/a4a6439dcb006149616f1ec18fc4958dd05142909b2945b40c094a382f951d2e/system.slice/sshd.service
           mq133 /usr/sbin/sshd -D

Jan 07 04:44:58 a4a6439dcb00 systemd[1]: Starting OpenSSH server daemon...
Jan 07 04:44:58 a4a6439dcb00 sshd[133]: Server listening on 0.0.0.0 port 22.
Jan 07 04:44:58 a4a6439dcb00 sshd[133]: Server listening on :: port 22.
Jan 07 04:44:58 a4a6439dcb00 systemd[1]: Started OpenSSH server daemon.
[root@a4a6439dcb00 /]# passwd
Changing password for user root.
New password: ssh-centos
Retype new password: ssh-centos
passwd: all authentication tokens updated successfully.

SSH接続

パスワード認証

teratermで別ターミナルを立ち上げる。
上記のコンテナに接続してみる。

[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE        COMMAND        CREATED          STATUS          PORTS     NAMES
a4a6439dcb00   ssh-centos   "/sbin/init"   31 minutes ago   Up 31 minutes             dazzling_pasteur
[root@localhost ~]# docker inspect a4a6439dcb00
[
    {
        "Id": "a4a6439dcb006149616f1ec18fc4958dd05142909b2945b40c094a382f951d2e",
        "Created": "2022-01-07T04:42:38.533371553Z",
        "Path": "/sbin/init",
...
           "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2", #ssh-centosのIPアドレス
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
...
[root@localhost ~]# ssh root@172.17.0.2
The authenticity of host '172.17.0.2 (172.17.0.2)' cant be established.
ECDSA key fingerprint is SHA256:R2nJBYNDVG4OID5GBJjiD9qlve84j9i0gvVau8aQxHc.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.17.0.2' (ECDSA) to the list of known hosts.
root@172.17.0.2's password:
System is booting up. See pam_nologin(8)
[root@a4a6439dcb00 ~]# ls
anaconda-ks.cfg

無事に、パスワード認証でSSH接続できた。

公開鍵認証

再掲
image.png

[root@a4a6439dcb00 ~]# vi /etc/ssh/sshd_config
...
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication no # PasswordAuthenticationをnoにする
...
[root@a4a6439dcb00 ~]# systemctl restart sshd
[root@a4a6439dcb00 ~]# exit
logout
Connection to 172.17.0.2 closed.
[root@localhost ~]# ssh root@172.17.0.2
root@172.17.0.2: Permission denied (publickey,gssapi-keyex,gssapi-with-mic). # PasswordAuthenticationをnoにしたからエラー出た。

ログインできないことを確認できたら、PasswordAuthenticationをyesに戻しておこう。

鍵の作成

[root@localhost ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gEaArKMx+NWFltv/LDpM7J3Qk5swuHWm72Oou7qzjsk root@localhost.localdomain
The keys randomart image is:
+---[RSA 3072]----+
|.....  o         |
|.. . .+ .        |
|o   oo.+         |
|*  .. o..        |
|.= .   oSo .     |
|. .   . B B      |
|       * X B     |
| . o. . * O o    |
|  E.==++.*oo     |
+----[SHA256]-----+
[root@localhost ~]# ls ~/.ssh/
id_rsa  id_rsa.pub  known_hosts
[root@localhost ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.17.0.2 #公開鍵をコピーした
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@172.17.0.2s password: ssh-centos
Number of key(s) added: 1
Now try logging into the machine, with:   "ssh 'root@172.17.0.2'"
and check to make sure that only the key(s) you wanted were added.
[root@localhost ~]# ssh root@172.17.0.2
System is booting up. See pam_nologin(8)
Last login: Fri Jan  7 05:19:06 2022 from gateway
[root@a4a6439dcb00 ~]# ls
anaconda-ks.cfg
[root@a4a6439dcb00 ~]# ls ~/.ssh/
authorized_keys # これが公開鍵

パスワードを聞かれずにログインできた。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?