CentoOS에서 SSH 키 인증 설정 및 비밀번호 로그인 비활성화

SSH 설정 파일 백업

먼저 SSH 설정 파일을 안전하게 백업합니다.

cd /etc/ssh/
cp sshd_config sshd_config.backup

SSH 키 쌍 생성

RSA 알고리즘을 사용하여 공개키와 개인키를 생성합니다. 모든 프롬프트에서 엔터 키를 누르면 기본 설정으로 생성됩니다.

[root@server ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:mK3a5JdFvLqPcXnRtYzWuIo9HgEjKlMnOpQrStUvWxY root@server
The key's randomart image is:
+---[RSA 2048]----+
|      .++.       |
|     . o..       |
|      o . .      |
|     . + o .     |
|    S = + .      |
|   . B = .       |
|  . * O .        |
|   = *o= .       |
|  .o+=*oE        |
+----[SHA256]-----+

[root@server ~]# ls -la /root/.ssh/
total 8
-rw------- 1 root root 1679 Dec 15 14:23 id_rsa
-rw-r--r-- 1 root root  414 Dec 15 14:23 id_rsa.pub

인증 키 파일 구성

생성된 공개키를 인증 키 파일에 추가하고 적절한 권한을 설정합니다.

[root@server ~]# cd /root/.ssh/
[root@server .ssh]# cat id_rsa.pub > authorized_keys
[root@server .ssh]# chmod 600 authorized_keys
[root@server .ssh]# chmod 700 ~/.ssh
[root@server .ssh]# ls -la
total 12
-rw------- 1 root root  414 Dec 15 14:25 authorized_keys
-rw------- 1 root root 1679 Dec 15 14:23 id_rsa
-rw-r--r-- 1 root root  414 Dec 15 14:23 id_rsa.pub

SSH 서버 설정 수정

기존의 관련 설정 항목을 제거하고 새로운 설정 값을 추가합니다.

# 기존 설정 항목 삭제
sed -i '/PasswordAuthentication.*/d' /etc/ssh/sshd_config
sed -i '/PubkeyAuthentication.*/d' /etc/ssh/sshd_config
sed -i '/RSAAuthentication.*/d' /etc/ssh/sshd_config
sed -i '/AuthorizedKeysFile.*/d' /etc/ssh/sshd_config

# 새로운 설정 항목 추가
cat >>/etc/ssh/sshd_config<<EOF
PasswordAuthentication no
PubkeyAuthentication yes
RSAAuthentication yes
AuthorizedKeysFile /root/.ssh/authorized_keys
EOF

SSH 서비스 재시작

변경된 설정을 적용하기 위해 SSH 서비스를 다시 시작합니다.

[root@server .ssh]# systemctl restart sshd

키 기반 인증 테스트

로컬 시스템으로 개인키 파일(id_rsa)을 다운로드하여 저장합니다.

[root@server .ssh]# ls -la
total 12
-rw------- 1 root root  414 Dec 15 14:25 authorized_keys
-rw------- 1 root root 1679 Dec 15 14:23 id_rsa
-rw-r--r-- 1 root root  414 Dec 15 14:23 id_rsa.pub

Xshell 또는 다른 SSH 클라이언트를 사용하여 키 인증 방식으로 서버에 접속합니다. 비밀번호 입력 없이 키 파일을 통해 인증이 완료되어야 합니다.

태그: CentOS SSH key-authentication Security server-configuration

5월 25일 21:40에 게시됨