之前有介绍Iptables模块recent通过暗语来开启SSH端口,knockd也可实现此功能。
knockd监听3个自定义端口,如果收到客户端请求符合要求即执行设置的指令,让iptables开启SSH端口允许客户IP连接。
安装所需组件,不然编译会提示错误。
yum install libpcap-devel
knockd源码编译安装:
wget http://www.zeroflux.org/proj/knock/files/knock-0.5.tar.gz
tar zxvf knock-0.5.tar.gz
cd knock-0.5
./configure
make
make install
或下载knock rpm包安装:
wget http://pkgs.repoforge.org/knock/knock-0.5-1.el5.rf.i386.rpm
rpm -ivh knock-0.5-1.el5.rf.i386.rpm
knockd配置:
cat /etc/knockd.conf
[options]
logfile = /var/log/knockd.log #日志记录目录
interface = eth0 #监听网卡
[opencloseSSH]
sequence = 6000:udp,5000:tcp,4000:udp #knock侦听端口协议
seq_timeout = 15 #单位时间内连续触发上面的端口规则
tcpflags = syn #封包标志,syn/ack/fin
start_command = iptables -I INPUT -s %IP% -p tcp --syn --dport 22 -j ACCEPT
#如果触发规则执行的iptables操作
cmd_timeout = 10 #规则触发后未连接超时时间
stop_command = iptables -D INPUT -s %IP% -p tcp --syn --dport 22 -j ACCEPT
#如超时未连接或断开连接执行iptalbes操作
knock init启动管理脚本:
#!/bin/sh
# chkconfig: - 99 00
# description: Start and stop knockd
# Check that config file exist
[ -f /etc/knockd.conf ] || exit 0
# Source function library
. /etc/rc.d/init.d/functions
# Source networking configuration
. /etc/sysconfig/network
# Check that networking is up
[ "$NETWORKING" = "no" ] && exit 0
start() {
echo "Starting knockd ..."
/usr/local/sbin/knockd -d
}
stop() {
echo "Shutting down knockd ..."
pkill knockd
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
;;
esac
exit 0
客户端连接SSH需先使用telnet依次连接knock设定端口,或使用knock客户端连接。
knock -v www.haiyun.me 6000:udp 5000:tcp 4000:udp
查看knock日志:
cat /var/log/knockd.log
[2012-08-31 10:41] 192.168.1.16: opencloseSSH: Stage 1
[2012-08-31 10:41] 192.168.1.16: opencloseSSH: Stage 2
[2012-08-31 10:41] 192.168.1.16: opencloseSSH: Stage 3
[2012-08-31 10:41] 192.168.1.16: opencloseSSH: OPEN SESAME
[2012-08-31 10:41] opencloseSSH: running command: iptables -I INPUT -s 192.168.1.16 -p tcp --syn --dport 22 -j ACCEPT
[2012-08-31 10:41] 192.168.1.16: opencloseSSH: command timeout
[2012-08-31 10:41] opencloseSSH: running command: iptables -D INPUT -s 192.168.1.16 -p tcp --syn --dport 22 -j ACCEPT
备注:如果网络较差,且同时使用tcp和udp进行验证可能会导致数据包到达顺序不一致或某个包丢失导致验证失败。
标签:ssh, 网络安全, ssh安全设置, knockd, 用knock管理ssh端口