- 论坛徽章:
- 1
|
redhat9.0 限制IP 登陆的困惑?
剛好, 前幾天弄了個小玩意, 給有興趣的朋友參考一下.
* 需求:
某一多人管理的 server (假設為 www.server.name) 原本並沒有限制 ssh 的來源.
現想加入特定來源控制讓某些管理員能夠遠端登錄, 其餘一蓋不允許.
* 難點:
由於個別管理員使用撥接方式上網, ip 不固定. 因此清單難以掌握.
* 構思:
1) 開發一個 php 網頁, 密碼以 ssl 連線保護, 以即時加入 client 端 IP 進 allow list 裡.
2) 再執行 firewall script , 開啟 ssh 連線.
3) 然後定期清理清單.
* 實作:
1) 寫一個 getip.php 至於某一網頁目錄底下(如 getip), 用來收集 client 端 browser ip 記錄於 allow_ssh.txt (單一記錄, 每次蓋寫). 內容如下:
- <?
- //Set dir path for ip list
- $dir_path=".";
- //Set filename for ip list
- $ip_list="allow_ssh.txt";
- //Get client ip
- $user_ip = getenv ("REMOTE_ADDR");
- //Put client ip to a file
- if(@!($file = fopen("$dir_path/$ip_list","w+")))
- {
- echo "Permission denied!!.......Pls Check your rights to dir $dir_path o
- r file $ip_list";
- }
- else
- {
- fputs($file,"$user_ip");
- fclose($file);
- echo "client ip($user_ip) has put into $dir_path/$ip_list";
- }
- ?>;
复制代码
[注意]: ssl 及 htpasswd 網頁密碼部份這裡從略. 請另行參考 web server 文件.
2) 修改 /etc/services , 增加項目:
3) 用 xinetd 監聽 port 222 , 並啟動 /root/iptables/sshadd.sh.
可新編 /etc/xinetd.d/myssh , 內容如下:
- service myssh
- {
- socket_type = stream
- protocol = tcp
- wait = no
- user = root
- server = /root/iptables/sshadd.sh
- disable = no
- }
复制代码
4) sshadd.sh 會設定 iptables , 打開 allow_ssh.txt 清單的 ssh 連線.
編輯 /root/iptables/sshadd.sh, 內容如下:
- #!/bin/bash
- list_dir=/var/www/html/getip
- list_file=$list_dir/allow_ssh.txt
- chain_name=ssh_rules
- mail_to=root
- # clear chain if exits, or create chain.
- /sbin/iptables -L -n | /bin/grep -q "^Chain $chain_name" && {
- /sbin/iptables -F $chain_name
- true
- } || {
- /sbin/iptables -N $chain_name
- /sbin/iptables -I INPUT -j $chain_name
- }
- # clear chain on demand
- [ "$1" = clear ] && {
- /sbin/iptables -F $chain_name
- exit 0
- }
- # do nothing while list is empty
- [ -s $list_file ] || exit 1
- # add rule
- /sbin/iptables -A $chain_name -p TCP --dport 22 -s $(cat $list_file) -j ACCEPT && \
- echo "ssh opened to $(cat $list_file) on $(date)" | mail -s "sshadd" $mail_to
复制代码
5) 寫 crontab 每 3 分中清理 iptables 關於 ssh 連線的規則.
- */3 * * * * root /study-area/iptables/sshadd.sh clear
复制代码
這並不影響既有連線, 若逾時則再連.
* 操作步驟:
1) 用 browser 開啟 http://www.server.name/getip/getip.php
2) 用 terminal 執行 telnet www.server.name 222
3) 最後用管理員自己的帳戶連接登錄 ssh www.server.name
* 注意:
1) iptables 預設規則並沒開啟任何 ssh 連線, 若有固定 ip 可用, 可另行配置預設規則.
2) tcpwraper 不可設定 deny 規則, 否則上述無效. |
|