Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Unix知識 >> 關於Unix

Linux SSH 的幾個實用安全技巧

前言

SSH 的好處不必多說:過去 rcp、telnet 能做的事,現在幾乎都能用 SSH 取代。常見用法包括:

# 遠端登入
ssh user@remote.machine

# 遠端執行指令
ssh user@remote.machine 'command ...'

# 檔案傳輸
scp user@remote.machine:/remote/path /local/path
scp /local/path user@remote.machine:/remote/path

# X11 轉送
ssh -X user@remote.machine

# 通道/埠轉送
ssh -L 1234:remote.machine:4321 user@remote.machine
ssh -R 1234:local.machine:4321 user@remote.machine

更細的用法這裡不展開,讀者可以自行研究。以下要談的是伺服器端 SSH 服務的幾個加固技巧,示範環境為 Red Hat 9。

1. 禁止 root 直接登入

# vi /etc/ssh/sshd_config
PermitRootLogin no

2. 關掉密碼登入,強制使用 RSA 金鑰

伺服器端:

# vi /etc/ssh/sshd_config
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
# service sshd restart

# su - user1
$ mkdir ~/.ssh 2>/dev/null
$ chmod 700 ~/.ssh
$ touch ~/.ssh/authorized_keys
$ chmod 644 ~/.ssh/authorized_keys

用戶端產生金鑰並把公鑰送過去:

$ ssh-keygen -t rsa      # 連續按三次 Enter;除非你會用 ssh-agent,否則不必設 passphrase
$ scp ~/.ssh/id_rsa.pub user1@server.machine:id_rsa.pub

Windows 用戶端可用 puttygen.exe 產生公鑰,複製到伺服器後再整理成單行。回到伺服器端收尾:

$ cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
$ rm ~/id_rsa.pub
$ exit

3. 限制 su/sudo 名單

# vi /etc/pam.d/su
auth required /lib/security/$ISA/pam_wheel.so use_uid
# visudo
%wheel  ALL=(ALL)  ALL
# gpasswd -a user1 wheel

4. 限制可 SSH 登入的帳號

# vi /etc/pam.d/sshd
auth required pam_listfile.so item=user sense=allow file=/etc/ssh_users onerr=fail
# echo user1 >> /etc/ssh_users

5. 封鎖 22 埠,改由網頁白名單放行

先用 iptables 把 22 埠關掉:

# iptables -I INPUT -p tcp --dport 22 -j DROP

接著建立一個受 Basic 認證保護的目錄 /var/www/html/ssh_open,寫入 .htaccess(AuthName、AuthUserFile、AuthType basic、require valid-user),再用 htpasswd -c 建立帳號。建議再搭配 SSL,只允許 https 存取;若要限制來源,可補上 Allow/Deny 設定。

然後在該目錄放一支名為 ssh_open.php 的小程式,它做的事很單純:取得 client IP(可用 GET 參數 myip 覆寫),檢查格式是否合法,若合法就把該 IP 寫進同目錄的 ssh_open.txt,並回報結果;格式錯誤則提示未修改。

權限設定是這類做法的成敗關鍵,順序別搞錯:

# touch /var/www/html/ssh_open/ssh_open.txt
# chmod 640 /var/www/html/ssh_open/*
# chgrp apache /var/www/html/ssh_open/*
# chmod g+w /var/www/html/ssh_open/ssh_open.txt
# chmod o+t /var/www/html/ssh_open
# service httpd restart

最後寫一支 /etc/iptables/sshopen.sh 腳本(記得設好 PATH 並加上執行權限),由 cron 定期呼叫:它讀取 ssh_open.txt 裡的 IP,動態把該來源加進放行規則、同時移除過期項目,於是「上網頁按一下、開一段時間的 SSH 通道」就成立了。

這套組合的價值在於:對外只暴露 443,22 埠完全不出現在連接埠掃描結果裡,而權限授予有明確的起訖時間,不必把 SSH 長期敞在公網上。

Copyright © Linux教程網 All Rights Reserved