openwrt使用fail2ban 防止ssh暴力破解  

fail2ban防ssh暴力破解

fail2ban 出现主要针对 暴力访问linux服务器而设计

原理是通过linux 服务器上的访问日志,通过正则表达式,获取访问信息

如ssh登录防暴力破解,通过正则ssh访问日志记录,获取暴利访问ip,家ip 通过防火墙隔离。

 

 

fail2ban是基于读取分析系统日志的,由于openwrt的日志文件都保存在内存内。第一步通过系统设置,日志文件保存到文件,这个日志文件建议以后用定时任务定时清空。

fail2ban在openwrt的软件中心可以直接安装,安装后需要进行配置才能正常运行,openwrt相对复杂一点:

第一步,配置保存日志文件:编辑/etc/config/system,添加一行option:

vim  etc/config/system

system部分增加:

option log_file '/var/log/auth.log'

定时清空办法,在定时任务内写入下面代码,每天5:00会清空日志文件,防止日志文件太大导致卡顿。

0 5 * * * echo "" >  /var/log/auth.log 

 

 

由于openwrt 和uniq的SSH服务都是用dropbear实现的,需要配置一个dropbear的日志分析过滤文件

第二步:

vim /etc/fail2ban/filter.d/dropbear.local

文件内容填写:

[INCLUDES]

before = common.conf

[Definition]

_daemon = dropbear

failregex = ^%(__prefix_line)s[Ll]ogin attempt for nonexistent user ('.*' )?from <HOST>:\d+$
            ^%(__prefix_line)s[Bb]ad (PAM )?password attempt for .+ from <HOST>(:\d+)?$
            ^%(__prefix_line)s[Ee]xit before auth \(user '.+', \d+ fails\): Max auth tries reached - user '.+' from <HOST>:\d+\s*$
            ^%(__prefix_line)s[Ee]xit before auth from <<HOST>:\d+>:\s.*$
            ^%(__prefix_line)s[Ee]xit before auth \(user '.+', \d+ fails\): Max auth tries reached - user '.+' from <HOST>:\d+\s*$
            ^%(__prefix_line)s[Bb]ad (PAM )?password attempt for .+ from <HOST>(:\d+)?$

ignoreregex =

  代码内的__prefix_line 是通过include部分引用common.conf的,这个是日志的日期软件名等句头,后面的正则表达式可以写多条匹配,可以查看实际日志进行微调,我测试的是openwrt 21 可以正常分析匹配日志文件,测试了有半天,总结出了上面的几条,具体不知道哪条生效了。

 

第三部:  创建定义fail2ban的jail文件,调用上面的日志过滤器

vim /etc/fail2ban/jail.d/dropbear.local

填写一下内容:

[dropbear]
enabled = true
port= ssh
logpath = /var/log/auth.log
findtime = 5h
bantime = 1d
maxretry = 2

 如果要封禁全部端口,把上面的port=ssh 更换为:

action   = iptables-allports[name=fail2ban]

bantime 后面为时间,封365天就是 365d,封10分钟就是10m

最后重启fail2ban

fail2ban-client restart
查看fail2ban的黑名单状态:

fail2ban-client status dropbear

 

 

 1 root@HuaWeiRouter:~# fail2ban-client status dropbear
 2 Status for the jail: dropbear
 3 |- Filter
 4 |  |- Currently failed: 0
 5 |  |- Total failed:     0
 6 |  `- File list:        /var/log/auth.log
 7 `- Actions
 8    |- Currently banned: 4
 9    |- Total banned:     4
10    `- Banned IP list:   121.186.179.1 185.246.130.20 188.152.176.42 201.92.174.105