(SSH)OpenSSH + PAM + Google OTP 인증 추가하기

agnusdei·2025년 4월 25일

OpenSSH와 PAM으로 SSH 로그인 시 OTP 인증 추가하기 🔐

서버 보안을 강화하려면 다단계 인증(MFA)을 적용하는 것이 좋습니다. 특히, PEM 키 인증OTP 인증을 요구하는 방법은 매우 강력합니다.
이 글에서는 OpenSSHPAM(Pluggable Authentication Modules)을 사용해 Google Authenticator를 통한 OTP 인증 추가 방법을 안내합니다. 🚀


1. OpenSSH 설치 및 확인 🔍

OpenSSH 버전 확인

ssh -V

예시 출력:

OpenSSH_8.9p1 Ubuntu-3ubuntu0.3, OpenSSL 3.0.2 15 Mar 2022

OpenSSH 설치

sudo apt-get update
sudo apt-get install openssh-server

2. Google Authenticator 설치 📦

PAM을 통해 OTP를 추가하려면 libpam-google-authenticator 패키지가 필요합니다.

sudo apt-get update
sudo apt-get install libpam-google-authenticator

3. 사용자별 Google Authenticator 설정 🛠️

각 사용자는 자신의 계정에서 다음 명령어를 실행하여 OTP를 설정해야 합니다.

google-authenticator

설정 과정에서는 다음을 진행합니다:

  • QR 코드 제공 (앱으로 스캔)
  • 비밀 키 및 백업 코드 생성
  • OTP 재사용 여부, 시간 허용 여부 설정

구글 OTP 앱(또는 Authy)으로 QR 코드를 스캔하세요. 📱


4. PAM 설정 🛡️

SSH 로그인 시 OTP 인증을 추가하려면 PAM 설정 파일을 수정해야 합니다.

sudo nano /etc/pam.d/sshd

파일 최상단에 다음 라인을 추가합니다:

auth required pam_google_authenticator.so

4-1. Pam 에서 비밀번호까지 요구하므로 공통 로그인은 패스하도록 주석

# PAM configuration for the Secure Shell service
auth required pam_google_authenticator.so
# Standard Un*x authentication.
# 주석
# @include common-auth

# Disallow non-root logins when /etc/nologin exists.
# 주석
# account    required     pam_nologin.so

# Uncomment and edit /etc/security/access.conf if you need to set complex
# access limits that are hard to express in sshd_config.
# account  required     pam_access.so

# Standard Un*x authorization.
@include common-account

# SELinux needs to be the first session rule.  This ensures that any
# lingering context has been cleared.  Without this it is possible that a
# module could execute code in the wrong domain.
session [success=ok ignore=ignore module_unknown=ignore default=bad]        pam_selinux.so close

# Set the loginuid process attribute.
session    required     pam_loginuid.so

# Create a new session keyring.
session    optional     pam_keyinit.so force revoke

# Standard Un*x session setup and teardown.
@include common-session

# Print the message of the day upon successful login.
# This includes a dynamically generated part from /run/motd.dynamic
# and a static (admin-editable) part from /etc/motd.
session    optional     pam_motd.so  motd=/run/motd.dynamic
session    optional     pam_motd.so noupdate

# Print the status of the user's mailbox upon successful login.
session    optional     pam_mail.so standard noenv # [1]

# Set up user limits from /etc/security/limits.conf.
session    required     pam_limits.so

# Read environment variables from /etc/environment and
# /etc/security/pam_env.conf.
session    required     pam_env.so # [1]
# In Debian 4.0 (etch), locale-related environment variables were moved to
# /etc/default/locale, so read that as well.
session    required     pam_env.so user_readenv=1 envfile=/etc/default/locale

# SELinux needs to intervene at login time to ensure that the process starts
# in the proper default security context.  Only sessions which are intended
# to run in the user's context should be run after this.
session [success=ok ignore=ignore module_unknown=ignore default=bad]        pam_selinux.so open

# Standard Un*x password updating.
@include common-password

5. SSH 설정 ⚙️

SSH가 PAM과 OTP를 사용하도록 설정을 수정합니다.

sudo nano /etc/ssh/sshd_config

다음 항목을 수정하거나 추가합니다:

PasswordAuthentication no
ChallengeResponseAuthentication yes
KbdInteractiveAuthentication yes
UsePAM yes

그리고 추가로, PEM 키 인증 후 OTP 입력을 요구하는 설정을 추가합니다:

AuthenticationMethods publickey,keyboard-interactive

🔹 AuthenticationMethods는 파일 맨 끝쪽(Subsystem sftp 정의 아래 등)에 추가하는 것을 추천합니다.


6. SSH 서비스 재시작 준비 🔧

sshd 설정 테스트 및 필수 디렉토리 생성

sudo sshd -t

만약 다음 오류가 나온다면:

Missing privilege separation directory: /run/sshd

폴더를 만들어줍니다:

sudo mkdir -p /run/sshd
sudo chmod 755 /run/sshd

그 후 SSH 서비스를 재시작합니다:

sudo systemctl restart ssh

🔹 sudo sshd -t로 반드시 설정 체크 후 재시작하세요.


7. SSH 로그인 흐름 📝

이제 SSH 접속을 하면 다음 순서로 인증이 진행됩니다:

ssh -i ssh_.pem ubuntu@your_server_ip
  • 1단계: PEM 키 인증
  • 2단계: Google Authenticator 앱에서 생성한 OTP 코드 입력

8. 문제 해결 팁 🧠

만약 OTP 입력 없이 바로 로그인 된다면:

  • /etc/ssh/sshd_config 파일에 AuthenticationMethods publickey,keyboard-interactive 설정이 적용됐는지 확인
  • UsePAM yes, ChallengeResponseAuthentication yes 설정 확인
  • /etc/pam.d/sshd 파일에 auth required pam_google_authenticator.so 추가됐는지 확인
  • ssh-agent 키 등록 문제를 피하려면 다음처럼 접속:
ssh -o IdentitiesOnly=yes ubuntu@your_server_ip

9. 비밀번호 설정 (필요 시) 🔐

비밀번호 인증이 활성화되었으므로, 비밀번호가 없으면 설정해야 할 수 있습니다:

sudo passwd ubuntu

🔹 다만, 가능하면 비밀번호는 쓰지 말고 PEM + OTP만 사용하는 게 좋습니다.


10. 비상용 백업 코드 (Emergency Scratch Codes) 🆘

Google Authenticator 설정 시 생성된 백업 코드입니다.
문제가 생겼을 때 다음 코드를 사용하여 로그인할 수 있습니다:

비상용 코드 (1회용):

  • 37798823
  • 90685137
  • 33898980
  • 33528234
  • 26058195

🔹 각 코드는 한 번만 사용할 수 있습니다.


✅ 최종 요약

단계설명명령어
1OpenSSH 설치/확인sudo apt-get install openssh-server, ssh -V
2Google Authenticator 설치sudo apt-get install libpam-google-authenticator
3사용자 OTP 설정google-authenticator
4PAM 설정sudo nano /etc/pam.d/sshd + auth required pam_google_authenticator.so
5SSH 설정 수정sudo nano /etc/ssh/sshd_config 수정
6설정 테스트 및 SSH 재시작sudo sshd -t, sudo mkdir -p /run/sshd, sudo systemctl restart ssh
7접속 테스트ssh -i ssh_.pem ubuntu@your_server_ip

profile
DevSecOps Pentest🚩

0개의 댓글