본문 바로가기
Linux

[Linux] AWS EC2에 ssh 접속 시 Google OTP authenticator 사용하여 인증 추가하기

by 서어켜엉 2024. 5. 7.

1. Google OTP authenticator 설치

 1-1. yum update (amazonlinux 2023에서는 yum 대신 dnf 사용)

sudo yum update

 1-2. google-authenticator 설치

sudo yum install google-authenticator -y

 1-3 Google authenticator 어플리케이션 설치

    - 모바일 app

 

2. Linux 사용자 생성

 2-1. 사용자 및 홈디렉토리 생성

sudo useradd -m [username]

  -m 옵션이 사용자 홈 디렉토리 생성 옵션

 

 2-2. 생성된 사용자 비밀번호 설정

sudo passwd [username]

 2-3. 사용자 sudo 권한 부여

# sudoers 파일 확인
ls -al /etc/sudoers

# sudoers 파일 권한 변경
chmod +w /etc/sudoers

# root 아래에 사용자 추가
root ALL=(ALL) ALL
[username] ALL=(ALL) ALL

# sudoers 파일 w 권한 원상복구
chmod -w /etc/sudoers

 

3. Google OTP 생성

 3-1. google authenticator 실행

  위에서 생성한 사용자로 변경한 후에 아래 과정을 시도할 것.

google-authenticator

   - 실행 시 나오는 QR코드를 어플로 스캔하면 등록된다.

   - 가끔 Failed to use libqrencode to show QR code visually for scanning. 이런 에러로 인해 QR 코드가 안 나올수도 있다.
      당황하지 말고, Your new secret key is: [SECRET_KEY] 여기 있는 secret_key를 입력하면 된다.

 3-2. 세부 옵션 설정

홈디렉토리에 있는 .google_authenticator 파일을 업데이트 할 것인가? yes

 

하나의 토큰으로 여러번 로그인이 가능하도록 할 것인가? no
시차로 인해 토큰이 만료되어 로그인이 불가능한 상황을 막기 위해 이전 토큰과 그 다음 토큰으로도 접근가능하게 할 것인가? yes
30초 안에 3번이상의 로그인 시도를 할 수 없도록 할 것인가? yes

 

 

4. PAM 모듈 수정

 4-1. /etc/pam.d/sshd 수정

sudo vim /etc/pam.d/sshd

 4-2. auth 항목에 아래 옵션 추가

auth required pam_google_authenticator.so nullok

뒤에 붙는 nullok 는 google authenticator 설정이 안된 사용자는 otp 인증이 없어도 된다는 의미이다.

auth required pam_google_authenticator.so debug

debug 옵션을 키면 에러가 발행했을 때 자세한 로그를 확인할 수 있다

journalctl -u sshd 이 커맨드로 로그를 확인했다.

5. sshd_config 옵션 수정

 5-1. 

sudo vi /etc/ssh/sshd_config

# 위 파일에서 아래 옵션 수정 (no --> yes)
ChallengeResponseAuthentication yes
# 아래 옵션 추가
AuthenticationMethods keyboard-interactive

# 아래 옵션도 확인할 것.
UsePAM yes

 5-2. sshd 재시작

sudo systemctl restart sshd

 

6. 보안그룹 수정

 6-1 접속하고자 하는 외부 컴퓨터의 IP 확인

hostname -I

 6-2. 인스턴스 보안그룹 인바운드 규칙에 해당 IP 추가

유형은 SSH, 프로토콜은 TCP, 포트는 22, 소스는 내 IP

 

7. ssh 접속

인스턴스 public IP로 ssh 접속

 7-1. Verification code 에 otp 토큰 입력