GitLabへのSSH接続時のOSユーザとGitLab上のMWユーザについて

作業メモとして記載している為、不適切な内容が含まれる可能性がございます。

# 概要

GitLabへのSSH接続時のユーザ認証について、動作確認を実施する。

# 実施内容
1. AmazonLinux2上に、GitLab-CEを構築
2. GitLabにログインしSSH接続用のユーザを作成
3. git clone を行うサーバを準備し、SSH接続設定を実施
4. クライアント環境からSSHにてgit cloneコマンドを実行
5. SSH接続時のユーザ認証についての実機確認を実施(OSユーザ/MWユーザ)

# 1. AmazonLinux2上に、Gitlab-CEを構築

- 前提環境（Amazon Linux 2 AMI : GitLab構築サーバ/クライアントサーバ共通）

```console
[root@git-master ~]# cat /etc/os-release 
NAME="Amazon Linux"
VERSION="2"
ID="amzn"
ID_LIKE="centos rhel fedora"
VERSION_ID="2"
PRETTY_NAME="Amazon Linux 2"
ANSI_COLOR="0;33"
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
HOME_URL="https://amazonlinux.com/"
[root@git-master ~]# 
```
- t2.micro(1vCPU/1Gib)では「gitlab-ctl reconfigure」コマンドの途中でハングして処理が止まる為、t2.medium(2vCPU/4Gib)を選択
- GitLab System Requirement
https://github.com/jimmidyson/gitlab-ce/blob/master/doc/install/requirements.md

**Gitlab構築**

公式サイトの手順（CentOS）ベースで構築する
https://about.gitlab.com/install/#centos-7

- 依存関係あるRPM群をインストール&sshdの起動設定&メール転送モジュールpostfixのインストール

```console:git-master-server
[root@git-master ~]# yum install -y curl policycoreutils-python openssh-server
[root@git-master ~]# systemctl enable sshd
[root@git-master ~]# systemctl start sshd
[root@git-master ~]# yum install postfix
[root@git-master ~]# systemctl enable postfix
[root@git-master ~]# systemctl start postfix
```
`AmazonLinux2ではfirewalldは標準導入されていない為、手順のfirewall部分は不要。`



- GitLab CE(Community Edition)のセットアップシェルダウンロード及びリポジトリのセットアップ

```console:git-master-server
[root@git-master ~]# curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  6564    0  6564    0     0   6564      0 --:--:-- --:--:-- --:--:-- 19137
Detected operating system as amzn/2.
Checking for curl...
Detected curl...
Downloading repository file: https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/config_file.repo?os=amzn&dist=2&source=script
done.
Installing pygpgme to verify GPG signatures...
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
gitlab_gitlab-ce-source/signature                                                                     |  836 B  00:00:00     
Retrieving key from https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey
Importing GPG key 0xE15E78F4:
 Userid     : "GitLab B.V. (package repository signing key) <packages@gitlab.com>"
 Fingerprint: 1a4c xxxx b987 xxxx 9396 xxxx 1421 xxxx e15e xxxx
 From       : https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey
Retrieving key from https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey/gitlab-gitlab-ce-3D645A26AB9FBD22.pub.gpg
gitlab_gitlab-ce-source/signature                                                                     |  951 B  00:00:00 !!! 
gitlab_gitlab-ce-source/primary                                                                       |  175 B  00:00:00     
Package pygpgme-0.3-9.amzn2.0.2.x86_64 already installed and latest version
Nothing to do
Installing yum-utils...
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Package yum-utils-1.1.31-46.amzn2.0.1.noarch already installed and latest version
Nothing to do
Generating yum cache for gitlab_gitlab-ce...
Importing GPG key 0xE15E78F4:
 Userid     : "GitLab B.V. (package repository signing key) <packages@gitlab.com>"
 Fingerprint: 1a4c 919d b987 d435 9396 38b9 1421 9a96 e15e 78f4
 From       : https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey

The repository is setup! You can now install packages.
[root@git-master ~]#
```

- GitLab CEのインストール
- 以下で指定するURLはGitLabにアクセスする際に使用するURLとなる。（GitLabサーバのドメイン名）

```console:git-master-server
[root@git-master ~]# EXTERNAL_URL="http://gitlab.example.com" yum install -y gitlab-ce
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Resolving Dependencies
--> Running transaction check
---> Package gitlab-ce.x86_64 0:11.7.3-ce.0.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================
 Package                    Arch                    Version                          Repository                         Size
=============================================================================================================================
Installing:
 gitlab-ce                  x86_64                  11.7.3-ce.0.el6                  gitlab_gitlab-ce                  457 M

Transaction Summary
=============================================================================================================================
Install  1 Package

Total download size: 457 M
Installed size: 1.3 G
Downloading packages:
warning: /var/cache/yum/x86_64/2/gitlab_gitlab-ce/packages/gitlab-ce-11.7.3-ce.0.el6.x86_64.rpm: Header V4 RSA/SHA1 Signature, key ID f27eab47: NOKEY
Public key for gitlab-ce-11.7.3-ce.0.el6.x86_64.rpm is not installed
gitlab-ce-11.7.3-ce.0.el6.x86_64.rpm                                                                  | 457 MB  00:00:14     
Retrieving key from https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey
Importing GPG key 0xE15E78F4:
 Userid     : "GitLab B.V. (package repository signing key) <packages@gitlab.com>"
 Fingerprint: 1a4c 919d b987 d435 9396 38b9 1421 9a96 e15e 78f4
 From       : https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey
Retrieving key from https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey/gitlab-gitlab-ce-3D645A26AB9FBD22.pub.gpg
Importing GPG key 0xF27EAB47:
 Userid     : "GitLab, Inc. <support@gitlab.com>"
 Fingerprint: dbef 8977 4ddb 9eb3 7d9f c3a0 3cfc f9ba f27e ab47
 From       : https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey/gitlab-gitlab-ce-3D645A26AB9FBD22.pub.gpg
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : gitlab-ce-11.7.3-ce.0.el6.x86_64                                                                          1/1 
It looks like GitLab has not been configured yet; skipping the upgrade script.

       *.                  *.
      ***                 ***
     *****               *****
    .******             *******
    ********            ********
   ,,,,,,,,,***********,,,,,,,,,
  ,,,,,,,,,,,*********,,,,,,,,,,,
  .,,,,,,,,,,,*******,,,,,,,,,,,,
      ,,,,,,,,,*****,,,,,,,,,.
         ,,,,,,,****,,,,,,
            .,,,***,,,,
                ,*,.
  


     _______ __  __          __
    / ____(_) /_/ /   ____ _/ /_
   / / __/ / __/ /   / __ `/ __ \
  / /_/ / / /_/ /___/ /_/ / /_/ /
  \____/_/\__/_____/\__,_/_.___/
  

Thank you for installing GitLab!
GitLab was unable to detect a valid hostname for your instance.
Please configure a URL for your GitLab instance by setting `external_url`
configuration in /etc/gitlab/gitlab.rb file.
Then, you can start your GitLab instance by running the following command:
  sudo gitlab-ctl reconfigure

For a comprehensive list of configuration options please see the Omnibus GitLab readme
https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md

  Verifying  : gitlab-ce-11.7.3-ce.0.el6.x86_64                                                                          1/1 

Installed:
  gitlab-ce.x86_64 0:11.7.3-ce.0.el6                                                                                         

Complete!
[root@git-master ~]#
```

- 実行時に正しいURLを指定しなかった場合は、以下ファイルを修正する。

```console:/etc/gitlab/gitlab.rb
external_url 'http://xxx.xxx.xxx.xxx'
```

- GitLabの変更を反映

```console:git-master-server
[root@git-master ~]# gitlab-ctl reconfigure
```

# 2. GitLabにログインしSSH接続用のユーザを作成

- AWSコンソールよりセキュリティグループのインバウンド設定でHTTPを許可しコンソールにアクセスできる事を確認
![スクリーンショット 2019-02-03 17.38.32.png](https://qiita-image-store.s3.amazonaws.com/0/142483/13d238ee-d24c-da1a-af89-931dc0f377ce.png)

Change your password 欄にて初期パスワードを設定
設定後、root / 設定したパスワード でログインできる事を確認

- ユーザの追加（Guest_User_1(guest_user_1) / Guest_User_2(guest_user_2)）
![スクリーンショット 2019-02-03 17.56.29.png](https://qiita-image-store.s3.amazonaws.com/0/142483/50718852-6937-e5d6-19b3-7f0ba596263f.png)
`この時点でOS上にユーザは作成されていない為、GitLab上のユーザとなる`

`今回の検証では、sample-projectは使用せず、それぞれのユーザで作成するプロジェクト（test/test_2）を利用する`


# 3. git clone を行うサーバを準備し、SSH接続設定を実施する

- GitLabに接続する元となるサーバ(git-guest-1-server)を構築し接続用ユーザ(guest-user)およびSSH鍵を生成する

```console:git-guest-1-server

[root@git-guest-1 ~]# useradd git-guest
[root@git-guest-1 ~]# su - git-guest
[git-guest@git-guest-1 ~]$
[git-guest@git-guest-1 ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/git-guest/.ssh/id_rsa): 
Created directory '/home/git-guest/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/git-guest/.ssh/id_rsa.
Your public key has been saved in /home/git-guest/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx git-guest@git-guest-1
The key's randomart image is:
+---[RSA 2048]----+
|+                |
|.+     .         |
|. o = . o .      |
xxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx
|+BoB+o   . .     |
|O*X==oE ...      |
+----[SHA256]-----+
[git-guest@git-guest-1 ~]$ 
```

- GitLabにGuest_User_1でログインし、SSH鍵を設定する
![スクリーンショット 2019-02-03 18.22.56.png](https://qiita-image-store.s3.amazonaws.com/0/142483/3b479705-d41b-bbda-e72b-8b3842837952.png)

- git-guest-1-serverからgit-master-server上のGitLabへの接続確認

```console:git-guest-1-server
[git-guest@git-guest-1 ~]$ ssh -T git@ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com
Welcome to GitLab, @guest_user_1!
[git-guest@git-guest-1 ~]$ 
```
`セキュリティグループにてgit-masterのインバウンド許可にgit-guestのIPを追加`

# 4. SSHにて git clone コマンドを実行

- gitコマンドのインストール

```console:git-guest-1-server
[root@git-guest-1 ~]# yum install git
[root@git-guest-1 ~]# git --version 
git version 2.17.2
[root@git-guest-1 ~]# 
```

- GitLab上でguest_user_1でログインし、新規プロジェクト(test)を作成(GUI操作)
- test.txtファイルをcommit(GUI操作)
- git-guest-1-server上でgit-guest に su し git clone を実行

```console:git-guest-1-server
[git-guest@git-guest-1 ~]$ git clone git@ec2-xxx.xxx.xxx.xxx.amazonaws.com:guest_user_1/test.git
Cloning into 'test'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
[git-guest@git-guest-1 ~]$ 
[git-guest@git-guest-1 ~]$ ls -ltr 
total 0
drwxrwxr-x 3 git-guest git-guest 34 Feb  3 13:50 test
[git-guest@git-guest-1 ~]$
```

- gitコマンドでgit pull 実行


```console:git-guest-1-server
[git-guest@git-guest-1 ~]$ git pull git@ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com:guest_user_1/test.git
From ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com:guest_user_1/test
 * branch            HEAD       -> FETCH_HEAD
Already up to date.
[git-guest@git-guest-1 ~]$
```

# 5. SSH接続時のユーザ認証についての実機確認(OSユーザ/MWユーザ)

- git pull コマンド実行時のユーザ認証

```console:git-guest-1-server
[git-guest@git-guest-1 ~]$ git pull git@ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com:guest_user_1/test.git
From ec2-xxx-xxx-xxxx-xxx.us-east-2.compute.amazonaws.com:guest_user_1/test
 * branch            HEAD       -> FETCH_HEAD
Already up to date.
[git-guest@git-guest-1 ~]$ 
```

- GitLab側のsecureログを確認

```console:git-master-server
Feb  9 06:34:11 git-master sshd[6325]: Accepted publickey for git from xxx.xxx.xxx.xxx port 59222 ssh2: RSA SHA256:Y0/I8vsRyCWDomW2wMDo8+5l4aJsz79iKTqbNvLJz80
Feb  9 06:34:11 git-master sshd[6325]: pam_unix(sshd:session): session opened for user git by (uid=0)
Feb  9 06:34:11 git-master sshd[6343]: Received disconnect from xxx.xxx.xxx.xxx port 59222:11: disconnected by user
Feb  9 06:34:11 git-master sshd[6343]: Disconnected from xxx.xxx.xxx.xxx port 59222
Feb  9 06:34:11 git-master sshd[6325]: pam_unix(sshd:session): session closed for user git
```

<font color="Red"></font>

`/var/log/secureより、git-guest@git-guest-1-server ---> git@git-master-serverでSSHの公開鍵認証が実施されている事を確認`

- GitLab上でGUI操作で登録した、guest_user_1ユーザの公開鍵は以下のファイルに保存されている事を確認。

```console:git-master-server：/var/opt/gitlab/.ssh/authorized_keys
[root@git-master ~]# cat /var/opt/gitlab/.ssh/authorized_keys
#######################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
command="/opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell key-2",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuEUO4uaOGALD0Jcf24h4XItxOAxvyZRKonR0nIcfOhP+Zb6GXxH0criUdD/uFcP2c9iWhbIzzxsFvAnSuh0yula78YB7ImQWaXX14h7gRRLDd++/Tq00UrDhCVYOKO+i6tFEthV+5ZRNvGuQ9Y4BLGMG/Aj1IpKR6kksd4qJm6jPQ4KGmIP/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[root@git-master ~]#
```

`/var/opt/gitlabディレクトリは、gitユーザのhomeディレクトリの為、通常のSSH鍵認証と同様の仕組みである事を確認。`


- GitLabへの接続元として新規にサーバ（git-guest-2-server）およびユーザ（guest_user_2）を作成し、SSH接続の設定を実施
- GitLab上でGuest_User_2でログインし、新規プロジェクト(test_2)を作成
- test_2.txtファイルをcommit(GUI操作)
- git-guest-2-server上でユーザ作成(git-guest)/鍵作成/GitLab上に鍵登録
- git-guest-2-server上でgit-guest に su し git clone を実行

`上記手順は3.と同様の内容のため、詳細は割愛`

```console:git-guest-2-server
[git-guest@git-guest-2 ~]$ git clone git@ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com:guest_user_2/test_2.git
Cloning into 'test_2'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
[git-guest@git-guest-2 ~]$
```

- git pullを実行

```console:git-guest-2-server
[git-guest@git-guest-2 ~]$ git init
Initialized empty Git repository in /home/git-guest/.git/
[git-guest@git-guest-2 ~]$
[git-guest@git-guest-2 ~]$ git pull git@ec2-xxx-xxx-xxx-xxx-us-east-2.compute.amazonaws.com:guest_user_2/test_2.git
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com:guest_user_2/test_2
 * branch            HEAD       -> FETCH_HEAD
[git-guest@git-guest-2 ~]$
```

```console:git-master-server
Feb  9 07:11:46 git-master sshd[11058]: Accepted publickey for git from xxx.xxx.xxx.xxx port 45628 ssh2: RSA SHA256:nHO+V5mEBVlx6MC+zTIBv35hraqZRa3+cuMN0/4U6Sk
Feb  9 07:11:46 git-master sshd[11058]: pam_unix(sshd:session): session opened for user git by (uid=0)
Feb  9 07:11:46 git-master sshd[11076]: Received disconnect from 172.31.21.29 port 45628:11: disconnected by user
Feb  9 07:11:46 git-master sshd[11076]: Disconnected from xxx.xxx.xxx.xxx port 45628
Feb  9 07:11:46 git-master sshd[11058]: pam_unix(sshd:session): session closed for user git
```

- GitlabのGUI上で登録した、guest_user_2ユーザの公開鍵は以下のファイルに保存されている事を確認。

```console:git-master-server
[root@git-master ~]# cat /var/opt/gitlab/.ssh/authorized_keys
#######################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
command="/opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell key-2",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuEUO4uaOGALD0Jcf24h4XItxOAxvyZRKonR0nIcfOhP/puh0yula78YB7ImQWaXX14h7gRRLDd++/Tq00UrDhCVYOKO+i6tFEthV+5ZRNvGuQ9Y4BLGMG/Aj1IpKR6kksd4qJm6jPQ4KGmIP/cA9abvraweg2mbeNx05gaVc6N577C9mBSViKQjShUlRt
command="/opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell key-3",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDPnlxTvk2EAe18pTbovGpCeRfhHgVUBl5knBVkiQJSUs5MWck6Wj/W9lGtwpUhlfFjDEons+uCb3kxbVq3mQFTNPoxZQ3TWdHtye5GcRoXf+WornLbKqylKCA5gArho7cRLVE79GvtxSxyB+JXWi+hDYN4gdw1tafCTMqYqoQEefDmoHXFQh3wLUIyQuOh
[root@git-master ~]#
```

- git-guest-2-serverから、guest_user_1が作成したリポジトリにアクセスできない事を確認

```console:git-guest-2-server
[git-guest@git-guest-2 ~]$ git pull git@ec2-18-222-109-66.us-east-2.compute.amazonaws.com:guest_user_1/test.git
GitLab: The project you were looking for could not be found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
[git-guest@git-guest-2 ~]$
```

**SSH接続時のユーザ認証の結論としては、以下である事を確認**
![スクリーンショット 2019-02-09 17.06.50.png](https://qiita-image-store.s3.amazonaws.com/0/142483/b5fb60e6-1867-48a3-4860-893d1c85996d.png)



# 参考

- GitLab起動/停止/再起動コマンド

```console
[root@git-master ~]# gitlab-ctl start
[root@git-master ~]# gitlab-ctl stop
[root@git-master ~]# gitlab-ctl restart
```

- git-guest-serverからGitLabにSSHログインできてしまうか？(セキュリティ観点)

```console
[git-guest@git-guest-1 ~]$ ssh -T git@ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com
Welcome to GitLab, @guest_user_1!
[git-guest@git-guest-1 ~]$
[git-guest@git-guest-1 ~]$ echo $?
0
[git-guest@git-guest-1 ~]$ 
[git-guest@git-guest-1 ~]$ ssh -T git@ec2-xxx-xxx-xxx-xxx.us-east-2.compute.amazonaws.com "echo test"
GitLab: Disallowed command
[git-guest@git-guest-1 ~]$ 
```
sshコマンドはRC=0で返されるが、対話型ログインやコマンド実行はできない模様。