SSH 키 설정과 보안 강화



SSH 키 기반 인증을 설정하면 비밀번호 없이 안전하게 서버에 접속할 수 있습니다.



SSH 키 생성


# RSA 키 생성 (기본)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Ed25519 키 생성 (권장, 더 안전하고 빠름)
ssh-keygen -t ed25519 -C "your_email@example.com"

# 파일 위치
# 개인키: ~/.ssh/id_ed25519
# 공개키: ~/.ssh/id_ed25519.pub


공개키 서버에 등록


# 자동 복사
ssh-copy-id user@server

# 수동 복사
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# 또는 직접 서버에서
echo "공개키내용" >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys


SSH 설정 파일 (~/.ssh/config)


# 호스트별 설정
Host myserver
HostName 192.168.1.100
User admin
Port 22
IdentityFile ~/.ssh/id_ed25519

Host prod-*
User deploy
IdentityFile ~/.ssh/prod_key

# 사용
ssh myserver
ssh prod-web1


서버 보안 강화 (/etc/ssh/sshd_config)


# 비밀번호 인증 비활성화
PasswordAuthentication no
ChallengeResponseAuthentication no

# root 로그인 비활성화
PermitRootLogin no

# 특정 사용자만 허용
AllowUsers admin deploy

# 포트 변경
Port 2222

# 유휴 연결 타임아웃
ClientAliveInterval 300
ClientAliveCountMax 2

# 설정 적용
sudo systemctl restart sshd


SSH Agent (키 관리)


# Agent 시작
eval "SSH_AUTH_SOCK=/var/folders/ng/2w9kg7m53sgbl7b361ddtvf00000gn/T//ssh-ylv5zfqJXySb/agent.68983; export SSH_AUTH_SOCK;
SSH_AGENT_PID=68984; export SSH_AGENT_PID;
echo Agent pid 68984;"

# 키 추가
ssh-add ~/.ssh/id_ed25519

# 등록된 키 확인
ssh-add -l

# macOS Keychain 연동
ssh-add --apple-use-keychain ~/.ssh/id_ed25519


포트 포워딩


# 로컬 포워딩 (로컬 8080 → 원격 80)
ssh -L 8080:localhost:80 user@server

# 원격 포워딩 (원격 8080 → 로컬 3000)
ssh -R 8080:localhost:3000 user@server

# 동적 포워딩 (SOCKS 프록시)
ssh -D 1080 user@server


2단계 인증 (Google Authenticator)


# 설치
sudo apt install libpam-google-authenticator
google-authenticator

# /etc/pam.d/sshd 추가
auth required pam_google_authenticator.so

# /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive


문제 해결


# 권한 문제
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_*
chmod 644 ~/.ssh/*.pub
chmod 600 ~/.ssh/authorized_keys

# 디버그 모드
ssh -vvv user@server