MongoDB爱好者
垂直技术交流平台

MongoDB 3.6 Authentication IP Restrictions

前言

好了,看了这个标题,我不知道你有没有一种潜意识,如果有,没错,那就是这个了,MongoDB 终于开放了我觉得对于一个数据库的安全来说,比较重要的一个模块了 — IP 白名单。

众所周知,MySQL、Oracle、SqlServer等知名的数据库都是有在安全方面作出相当的防护的。

  • IP白名单
  • 针对库、表的权限区分
  • 针对不同的增删改查、事务、admin等的权限分配
  • 甚至于Oracle还提供了针对于不同权限所组合而成的逻辑角色,MySQL在这方面也做了相应的调整。

但是回过头来看看MongoDB,从最一开始的最最简单的用户名+密码的方式,到了之后引入了Bult-in Role、Custom Role、Privilege等的概念推出,再到即将推出的3.6中,明确了将bind_ip调整成了localhost,这也是受比特币案的影响吧。

这一次,3.6中,新加入了authenticationRestrictions,就是用来解决IP白名单的缺陷。

那么接下来就让我们一起来看一下,这个非常吸引我的特性是如何实现的吧。

讲道理

首先还是先来看看MongoDB的官方文档吧。https://docs.mongodb.com/master/reference/method/db.createUser/#authentication-restrictions

Field Name Value Description
clientSource Array of IP addresses and/or CIDR ranges If present, when authenticating a user, the server verifies that the client’s IP address is either in the given list or belongs to a CIDR range in the list. If the client’s IP address is not present, the server does not authenticate the user.
serverAddress Array of IP addresses and/or CIDR ranges A list of IP addresses or CIDR ranges to which the client can connect. If present, the server will verify that the client’s connection was accepted via an IP address in the given list. If the connection was accepted via an unrecognized IP address, the server does not authenticate the user.

简单来说,clientSource 就是针对客户端的IP 做白名单控制。serverAddress 就是针对服务端的IP 做白名单控制。

那么这里问题来了,客户端IP 好理解,无非就是哪里连过来的连接么,这和我们理解上的都一致,那么服务端地IP呢,什么意思?

这里,服务端的IP 指的是客户端在连接过来的时候指定的host 地址,比如:mongo --host=192.168.56.101,那么serverAddress 就必须包含192.168.56.101,这里的包含是什么意思?和MySQL一样,同样可以指定B、C网段,来达到多个地址地开放,只是写法有些许出入,MySQL中是:192.168.56.*,MongoDB 中是:192.168.56.0/24。那么如果是使用驱动的话,也是一样的,在host参数中指定对应的IP即可。

那么接下来我们就来操作一把。

摆事实

1.创建一个应用账号miracle

use admin

db.createUser(
   {
     user: "root",
     pwd: "root",
     roles: [{role: 'root', db: 'admin'} ]
   }
)

db.createUser(
   {
     user: "miracle",
     pwd: "young",
     roles: [ {role: 'readWrite', db: 'young'} ],
     authenticationRestrictions: [ {
        clientSource: ["192.168.31.246"],
        serverAddress: ["192.168.31.246"]
     } ]
   }
)

Alt text

2.重启数据库,开启权限认证
Alt text

3.进入miracle 数据库,并验证
Alt text
Alt text

4.使用符合要求的格式重新连接数据库
Alt text

5.第四步中出错的原因是因为默认3.6 开启了bind_ip=localhost,而由于一开始忽略了这个问题,折腾了我好久。重启数据库加上--bind_ip_all
Alt text

6.重新连接
Alt text

总结

至此,MongoDB的IP白名单功能验证完毕,希望能够帮助到大家在实际的维护中更安全的控制好开发者的权限。


我是上海小胖[MiracleYoung],专注MongoDB、MySQL、Redis等开源数据库的 DevOps,拥抱开源,接受收费。

上海小胖[MiracleYoung] 原创地址: https://segmentfault.com/u/shanghaixiaopang/articles

联系方式:miracleyoung0723@gmail.com

欢迎各位大神前来评论。

每周五,敬请期待,上海小胖[MiracleYoung] 独更。

如果夏雨荷还在大明湖畔等着我的话,我就不更了。

赞(7)
未经允许不得转载:MongoDB中文社区 » MongoDB 3.6 Authentication IP Restrictions

评论 1

评论前必须登录!

 

  1. #1

    那如果clientSource或者serverAddress变了怎么办

    Kee4年前 (2020-04-20)