安全小记 – 使用 fail2ban 来防止数据库被爆破

写在前面

虽然最近把服务器的数据库 docker 化了,但因为历史遗留因素,我还是得把 3306 端口开放出来供 host 上的 Web app 访问。(老猪实在不想浪费时间把它们 docker 化了,又不是不能用)

如此一来,就又同过去一样,给了蟊贼光顾的机会,这我怎么能答应?

解决方案

  1. 安装 fail2ban

    sudo apt install fail2ban
  2. 在主机创建 /var/log/mysql 目录,然后添加好目录映射

  3. 修改 MariaDB 的配置文件,配置好错误日志的路径

    log_error = /var/log/mysql/error.log
  4. 重启 MariaDB

    sudo docker restart [MariaDB 容器名称]
  5. 修改 fail2ban 配置

    sudo vi /etc/fail2ban/jail.conf
  6. 找到 ignoreip 那行,取消注释并加入 docker 的网络范围 172.16.0.1/12

    ignoreip = 127.0.0.1/8 172.16.0.1/12 ::1
  7. 找到 [mysql-auth],作如下修改

    [mysqld-auth] 
    enabled  = true 
    port     = 3306 
    filter   = mysqld-auth              # fail2ban 自带过滤规则
    logpath  = /var/log/mysql/error.log # 上面定义的错误日志路径
    findtime = 10m                      # 访问时间 10 分钟内
    maxretry = 5                        # 错误重试 5 次
    bantime  = 1d                       # 屏蔽时间 1天
  8. 重启 fail2ban 服务

    sudo systemctl restart fail2ban
  9. 等鱼上钩并查看效果

    sudo fail2ban-client status mysqld-auth
  10. 捉住一个山东大汉!

    Status for the jail: mysqld-auth
    |- Filter
    |  |- Currently failed: 0
    |  |- Total failed:     0
    |  `- File list:        /var/log/mysql/error.log
    `- Actions
      |- Currently banned: 1
      |- Total banned:     1
      `- Banned IP list:   124.133.28.21
0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论
By 马丁龙猪

标签

归档

其他操作