【Linux】特定ユーザーグループにて公開鍵認証+Google Authenticator認証の2FAを行う

group01グループのユーザーがssh接続する際、公開鍵認証+Google Authenticator認証を行うように指定する

1.Google Authenticatorインストール

apt install libpam-google-authenticator

2.ユーザー作成

root@ubuntu:~# groupadd group01
root@ubuntu:~# useradd user01 -g group01 -m
root@ubuntu:~#
root@ubuntu:~# id user01
uid=1001(user01) gid=1001(group01) groups=1001(group01)

3.ユーザーのログイン用設定

$ google-authenticator -t -e 0 -i "HomeLab" -l "user01"
$ mkdir .ssh
$ vi .ssh/authorized_keys ※クライアントの公開鍵を入力
$ chmod 700 .ssh
$ chmod 600 .ssh/authorized_keys

※user01にてコマンド実行

4.ssh設定

root@ubuntu:~# vi /etc/ssh/sshd_config
以下を最下部に追加し、group01のユーザーに対しては公開鍵認証+Google Authenticator認証とする
Match Group group01
    AuthenticationMethods publickey,keyboard-interactive
root@ubuntu:~# vi /etc/pam.d/sshd

以下をコメントアウト
#@include common-password

以下を最下部に追加
auth [success=1 default=ignore] pam_succeed_if.so user ingroup group01 ※group01のユーザーである場合、1行スキップ
auth [success=done default=die] pam_unix.so※group01以外のユーザーについて行われ、パスワード認証でログイン
auth required pam_google_authenticator.so※Google Authenticator認証

5.ログイン確認

①user01(group01グループ)の場合

> ssh user01@192.168.11.204
Password:
Verification code:
Welcome to Ubuntu 22.04.1 LTS (GNU/Linux 5.15.0-56-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

This system has been minimized by removing packages and content that are
not required on a system that users do not log into.

To restore this content, you can run the 'unminimize' command.
Last login: Sat Apr 27 15:24:04 2024 from 192.168.11.20
$

パスワードとGoogle Authenticatorコードを聞かれる

②root(group01グループ以外)の場合

> ssh root@192.168.11.204
Password:
Welcome to Ubuntu 22.04.1 LTS (GNU/Linux 5.15.0-56-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

This system has been minimized by removing packages and content that are
not required on a system that users do not log into.

To restore this content, you can run the 'unminimize' command.
Last login: Sat Apr 27 15:24:13 2024 from 192.168.11.20
root@ubuntu:~#

パスワード認証のみ