根据 mongodb 文档中的仅在客户端出示证书时才验证,我使用以下 mongod.conf 配置文件运行 mongodb 容器。
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/server.pem
CAFile: /etc/ssl/ca.pem
allowConnectionsWithoutCertificates: true
这是我用来运行 mongodb 的命令
docker run -d \
--name mongodb \
-e MONGO_INITDB_ROOT_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD=rootpassword \
-v /path/to/the/mongod.conf:/etc/mongod.conf \
-v /path/to/the/server.pem:/etc/ssl/server.pem \
-v /path/to/the/ca.pem:/etc/ssl/ca.pem \
-v /path/to/the/client.pem:/etc/ssl/client.pem \
-p 27017:27017 \
mongo:4.4.26 --config /etc/mongod.conf
然后我尝试使用
MONGO_INITDB_ROOT
用户名和密码连接 mongodb。但以下按摩显示错误:
root@2b95c9e5d8a8:/# mongo admin -u root -p rootpassword
MongoDB shell version v4.4.26
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Error: network error while attempting to run command 'isMaster' on host '127.0.0.1:27017' :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1
来自docker日志:
{"t":{"$date":"2023-12-28T11:23:29.777+00:00"},"s":"I", "c":"NETWORK", "id":22988, "ctx":"conn1","msg":"Error receiving request from client. Ending connection from remote","attr":{"error":{"code":141,"codeName":"SSLHandshakeFailed","errmsg":"The server is configured to only allow SSL connections"},"remote":"127.0.0.1:39754","connectionId":1}}
所以需要基于tls的认证。但根据 mongodb 文档
A mongod / mongos running with these settings allows connection from:
- Clients that do not present a certificate.
- Clients that present a valid certificate.
All connections, including those that have not presented certificates, are encrypted using TLS/SSL.
因此,当我将
allowConnectionsWithoutCertificates
设置为 true 时,它应该让我也可以使用 TLS 进行连接加密。但事实并非如此。旗帜是否正常工作?还是我漏掉了什么?
您错过了客户端的 CA 证书。尝试一下
mongo admin -u root -p rootpassword --tlsCAFile=/path/to/the/ca.pem
它也可以与
一起使用mongo admin -u root -p rootpassword --tlsUseSystemCA
或
mongo admin -u root -p rootpassword --tlsAllowInvalidCertificates
请注意,顾名思义,
/path/to/the/client.pem
是一个client证书,您不需要在MongoDBserver端使用它。
并且仅当您计划使用客户端证书连接时才需要
CAFile: /etc/ssl/ca.pem
- 但情况似乎并非如此。