Jost Do It.

그냥 IT해.

서버 및 환경/OS

[Ubuntu] ssh 접속 허용하고 OTP 접속 설정하기

그냥하Jo. 2024. 1. 29. 00:27
반응형

 

[개요]

외부 ip에서 집 데스크톱으로 접근하다보니 보안설정이 필요했다.

여러 설정 방법들이 있겠지만 관리하는 코스트는 줄이면서 최대한 간단하게 설정하고 싶었다.

그 중 사이트에 접속할 때마다 사용하는 OTP를 우분투에서 사용하는 방법이 있어 OTP로 보안을 적용하였다.

 

 

[ssh 설정하기]

먼저 ssh 관련 패키지를 설치해준다.

sudo apt-get install openssh-server

 

설치 후 ssh 상태가 정상적인지 확인한다.

sudo systemctl status ssh

 

 

정상적이라면 아래와 같은 결과가 나온다.

● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2024-01-28 23:37:52 KST; 1min 29s ago
       Docs: man:sshd(8)
             man:sshd_config(5)
   Main PID: 70519 (sshd)
      Tasks: 1 (limit: 76627)
     Memory: 1.7M
        CPU: 11ms
     CGroup: /system.slice/ssh.service
             └─70519 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"

 1월 28 23:37:52 heenj-B650-AORUS-ELITE-AX-ICE systemd[1]: Starting OpenBSD Secure Shell server...
 1월 28 23:37:52 heenj-B650-AORUS-ELITE-AX-ICE sshd[70519]: Server listening on 0.0.0.0 port 22.
 1월 28 23:37:52 heenj-B650-AORUS-ELITE-AX-ICE sshd[70519]: Server listening on :: port 22.
 1월 28 23:37:52 heenj-B650-AORUS-ELITE-AX-ICE systemd[1]: Started OpenBSD Secure Shell server.

 

 

[ssh 포트 열어주기]

ssh 포트는 기본적으로 22번을 사용한다.

외부에서 ssh를 통해 접속하기 위해서는 해당 포트를 방화벽에서 열어줘야 한다.

sudo ufw allow ssh

 

 

정상적으로 ssh 접속이 되는지 확인한다.

# ssh {계정명}@{호스트명}

ssh test@10.1.1.1 # 예제
  • 명령은 ssh {계정명}@{호스트명} 으로 할 수 있다.

 

 

 

[OTP 설정하기]

가장 범용적으로 사용하는 google-authenticator를 다운받는다.

sudo apt-get install libpam-google-authenticator

 

 

ssh 설정 파일 백업 후 파일 수정

sudo cp /etc/pam.d/sshd /etc/pam.d/sshd.backup # 파일 backup
sudo vi /etc/pam.d/sshd # 파일 수정

 

 

ssh 파일 맨 마지막에 아래 라인을 추가

auth required pam_google_authenticator.so nullok
  • nullok가 있으면 secret 파일이 없어도 인증 후 접속을 허용하는 옵션이다.

 

ssh 데몬 관련 파일도 수정해준다.

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
sudo vi /etc/ssh/sshd_config

 

 

파일에서 아래 파라미터들을 다음과 같이 변경해준다.

PasswordAuthentication no
PermitEmptyPassword no
UsePAM yes
ChallengeResponseAuthentication yes
  • 주석처리된 경우 주석을 해제한다.
  • 찾기힘들면 vi editor 기능을 이용하자 (/ 후 찾는 문자열 입력)

 

ssh 데몬을 재시작한다.

sudo systemctl restart sshd

 

 

[Google authenticator OTP 실행]

google-authenticator

 

 

그럼 아래와 같은 질문들이 나온다.

 

1. 토큰이 시간에 따라 변경될지 여부

 Do you want authentication tokens to be time-based (y/n) y

 

2. 다음으로 다음과 같이 메시지와 함께 거대한 QR코드가 나온다...

QR코드를 휴대폰 google authenticator로 찍어서 코드 등록해주자.

메시지에 URL로 들어가도 QR코드를 확인할 수 있다.

 

3. 코드 등록하고 토큰 정보를 커맨드에 입력해 정상적으로 워킹하는지 확인할 수 있다. 완료되면 Code confirmed 메시지와 함께 비상 상황에 쓸 수 있는 코드들도 제공된다.

Enter code from app (-1 to skip): 471778
Code confirmed
Your emergency scratch codes are:
  567151##
  259992##
  381872##
  866647##
  927110##

 

 

4. 업데이트에 따른 파일 수정 가능 여부

Do you want me to update your "/home/heenj/.google_authenticator" file? y

 

 

5. 토큰 재사용 허용 여부

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y

 

 

6. 토큰 시간차 입력 가능 여부

By default, a new token is generated every 30 seconds by the mobile app.
In order to compensate for possible time-skew between the client and the server,
we allow an extra token before and after the current time. This allows for a
time skew of up to 30 seconds between authentication server and client. If you
experience problems with poor time synchronization, you can increase the window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the current
code, and the 8 next codes). This will permit for a time skew of up to 4 minutes
between client and server.
Do you want to do so? (y/n) y
  • 이거는 개인 취향이지만 기존 OTP 이용 사이트들에서 시간이 조금 남아서 토큰 인증이 안되는 경우들이 있어서 y로 설정

 

7. 무작위 로그인을 하려는 시도들 차단 (30초에 3번 이상 로그인 시도 불가)

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting? (y/n) y

 

 

[이후 작업]

세팅 후 아래 명령어를 통해 정상적으로 토큰(Verification code)을 묻고, 로그인이 되는지 확인한다.

ssh test@10.1.1.1 

(test@10.1.1.1) Password:
(test@10.1.1.1) Verification code:
Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 6.5.0-15-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/pro
 [...]

 

 

 

정상적으로 세팅됐다면 백업 파일들을 제거한다.

udo rm /etc/ssh/sshd_config.backup
sudo rm /etc/pam.d/sshd.backup

 

Reference

반응형