对几次输入ssh密码错误的IP进行iptables drop

来源:互联网 发布:淘宝详情排版神器软件 编辑:程序博客网 时间:2024/04/30 01:35

对几次输入ssh密码错误的IP进行iptables drop

把下面脚本放入/etc/crontab

  • 扫描ssh密码猜测次数超过5次的记录

* * * * * root /home/cnscn/sh/ssh_scan_crontab.sh >/dev/null 2>&1

$ cat /home/cnscn/sh/ssh_scan_crontab.sh

  1. #!/bin/bash
  2. # Author http://jabin.cublog.cn
  3. # Modify cnscn http://cnscn2008.cublog.cn
  4. # Modify xinyv
  5. #设置时区
  6. export LC_ALL=UTC
  7. # 获取前 1 分钟内的 secure 记录,统计 ssh 认证失败的 IP 和其 失败次数, 并用Iptables阻止之
  8. SCANNER=$(awk 'BEGIN{ tm=strftime("%b %e %H:%M",systime()-60);} $0 ~ tm && /Failed password/ && /ssh2/ {print $(NF-3)}' /var/log/secure |sort|uniq -c |awk '{print $1"="$2;}')
  9. for i in $SCANNER
  10. do
  11. echo $i
  12. # 取认证失败次数
  13. NUM=`echo $i|awk -F= '{print $1}'`
  14. # 取其 IP 地址
  15. IP=`echo $i|awk -F= '{print $2}'`
  16. # 若其在失败次数超过 5 次且之前没有被阻断过,那么添加一条策略将其阻断,并记录日志
  17. if [ $NUM -gt 5 ] && [ -z "`/sbin/iptables -vnL INPUT|grep $IP`" ]
  18. then
  19. /sbin/iptables -I INPUT -s $IP -j DROP
  20. echo "/sbin/iptables -I INPUT -s $IP -j DROP" >> /home/cnscn/sh/ssh_scan_iptables.sh
  21. logger -i -t "ssh_scan_crontab" -f /var/log/messages "$IP($NUM)..."
  22. fi
  23. done
  24. #End of Script
  25. 把脚本/home/cnscn/sh/ssh_scan_iptables.sh加入到开机启动的myiptables.sh防火墙脚本
  26. $ cat myiptables.sh
  27. #!/bin/bash
  28. #chkconfig: 345 85 15
  29. #description: my iptables rules, which can auto run when system start
  30. # This is a script
  31. # Edit by liwei, cnscn
  32. # establish a static firewall
  33. #网络接口
  34. interdevice="eth0"
  35. #端口
  36. #21 ftp
  37. #15022 sshd
  38. #25 smtp
  39. #53 named
  40. #80 http
  41. #110 pop3
  42. #外界可以访问的端口
  43. Open_ports="21 20 22 80"
  44. #可以外出的端口,其它端口都可以外出
  45. Allow_ports="21 20 80 "
  46. #清除所有以前设置的规则
  47. iptables -F
  48. iptables -X
  49. iptables -t nat -F
  50. iptables -t nat -X
  51. #执行非法IP阻止规则
  52. /home/cnscn/sh/ssh_scan_iptables.sh
  53. #允许211.167.xxx.xxx, 防止自己输入错误而导致的IP被封锁
  54. /sbin/iptables -I INPUT -s 211.167.xxx.xxx -j ACCEPT
  55. #定义每一个网络接口规则
  56. for eths in $interdevice ; do
  57. #接受所有的,来源不是网络接口$interdevice的数据(对不是eths端口则放行)
  58. #iptables -A INPUT -i ! $eths -j ACCEPT
  59. #定义外界可以访问的端口规则(--dport)
  60. for Port in $Open_ports ; do
  61. iptables -A INPUT -i $eths -p tcp --dport $Port -j ACCEPT
  62. iptables -A INPUT -i $eths -p udp --dport $Port -j ACCEPT
  63. done
  64. #给不应该进入我们机器的数据,一个欺骗性的回答
  65. iptables -A INPUT -i $eths -p tcp -j REJECT --reject-with tcp-reset
  66. iptables -A INPUT -i $eths -p udp -j REJECT --reject-with icmp-port-unreachable
  67. done
  68. #forbidden ping
  69. echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all
  70. #End of Script

参考

  • SSH 的一些安全小技巧
  • iptables 入门

  • http://linux.vbird.org/linux_server/0250simple_firewall.php

From: http://sebug.net/node/t-43

0 0
原创粉丝点击