当前位置: 首页 > news >正文

MongoDB使用x.509证书认证

文章目录

  • 自定义证书
    • 生成CA证书
    • 生成服务器之间的证书
    • 生成集群证书
    • 生成用户证书
  • MongoDB配置
  • java使用x.509证书连接MongoDB
  • MongoShell使用证书连接

8.0版本的mongodb开启复制集,配置证书认证

自定义证书

生成CA证书

生成ca私钥: openssl genrsa -out ca.key 4096 # 生成RSA 4096位私钥
生成ca证书: openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.crt -subj "/CN=MongoDB Root CA/O=MyOrg/OU=Security"
验证ca证书: openssl x509 -in ca.crt -text -noout
生成pkcs12格式的p12文件:后续用于java代码认证
cat ca.crt ca.key > ca.pem
openssl pkcs12 -export -in ca.pem -out ca.p12 -password pass:123456

生成服务器之间的证书

生成服务器私钥: openssl genrsa -out server.key 2048
生成证书签名请求: openssl req -new -key server.key -out server.csr -subj "/CN=1.1.1.1/O=MyOrg/OU=Servers"
生成扩展配置文件(server.ext):

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature, keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:mongodb-server.example.com,DNS:localhost,IP:192.168.1.100

用ca签发证书: openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 -sha256 -extfile server.ext
合并证书与私钥: cat server.crt server.key > server.pem
验证服务器证书: openssl verify -CAfile ca.crt server.crt # 应显示 “OK”

生成集群证书

生成集群私钥: openssl genrsa -out cluster.key 2048
生成CSR : openssl req -new -key cluster.key -out cluster.csr -subj "/CN=node1/O=MyOrg/OU=MongoDB-Cluster" 必须包含一致的 O(组织)或 OU(部门),否则集群节点无法相互认证。
生成扩展配置文件(cluster.ext):

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature, keyEncipherment
extendedKeyUsage=clientAuth

ca签发集群证书: openssl x509 -req -in cluster.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out cluster.crt -days 365 -sha256 -extfile cluster.ext
合并证书与私钥: cat cluster.crt cluster.key > cluster.pem
验证集群证书:
openssl x509 -in cluster.crt -text | grep "Subject:" # 确认O/OU一致性
openssl verify -CAfile ca.crt cluster.crt # 应显示 “OK”

生成用户证书

生成用户私钥: openssl genrsa -out zy1.key 2048
生成CSR : openssl req -new -key zy1.key -out zy1.csr -subj "/O=MyOrg/CN=zy1" 必须包含一致的 O(组织)或 OU(部门),否则集群节点无法相互认证。
生成扩展配置文件( zy1.ext):

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature, keyEncipherment
extendedKeyUsage=clientAuth

ca签发集群证书: openssl x509 -req -in zy1.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out zy1.crt -days 365 -sha256 -extfile zy1.ext
合并证书与私钥: cat zy1.crt zy1.key > zy1.pem
获取subject : openssl x509 -in /usr/local/database/mongodb8.0.5/crt/zy1.pem -inform PEM -subject -nameopt RFC2253

生成pkcs12 格式的信任库文件:
openssl pkcs12 -export -inkey zy1.pem -in zy1.pem -out zy1_pem.p12 -password pass:123456
测试PKCS12密码正确性
keytool -list -v -keystore C:\Users\Administrator\Desktop\crt\zy1_pem.p12 -storetype pkcs12

MongoDB配置

mongodb配置:

     # mongod.confnet:tls:mode: requireTLSCAFile: /path/to/ca.crtcertificateKeyFile: /path/to/server.pemclusterFile: /path/to/cluster.pemsecurity:clusterAuthMode: x509authorization: enabled	

所有pem文件的权限都设为600 : chmod 600 ca.crt server.pem cluster.pem
客户端的证书由同一CA签发,并且在Mongodb中创建对应用户,如下:用户名为O=MyOrg,CN=zy,需要与证书中的Subject保持一致。可以通过名命令获取:
openssl x509 -in /usr/local/database/mongodb8.0.5/crt/zy1.pem -inform PEM -subject -nameopt RFC2253

db.getSiblingDB("$external").runCommand({createUser: "O=MyOrg,CN=zy",roles: [{ role: "readWrite", db: "test" },{ role: "userAdminAnyDatabase", db: "admin" }],writeConcern: { w: "majority" , wtimeout: 5000 }}
)

java使用x.509证书连接MongoDB

package com.zy.sslcontext;import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;/*** Connect to a MongoDB cluster with TLS connection.* Validate MongoDB server's certificate with the CA certificate. Present a Client certificate to be validated by* the MongoDB server.** Use X509 certificate to authenticate with the MongoDB server** Create a custom {@link javax.net.ssl.SSLContext} with the TrustStore holding the CA certificate and* the KeyStore holding the Client certificate and provide it to the MongoDB Driver.*/
public class ValidateServerPresentClientCertificateX509Auth {public static void main(String[] args) {//     System.setProperty("javax.net.debug", "ssl:handshake:verbose");// Configure MongoDB Driver to use MONGODB-X509 as authentication mechanism// 此处url可以不用填写用户名密码,则后续配置时采用credential(MongoCredential.createMongoX509Credential())使用证书在的用户信息进行数据操作String connectionString = "mongodb://zy:123456@1.1.1.1:27017/?&ssl=true"; SSLContext sslContext;try {sslContext = getSSLContext();} catch (Exception e) {System.out.println("Failed to generate SSLContext. Error: " + e.getMessage());return;}MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(new ConnectionString(connectionString)) .applyToSslSettings(builder -> {builder.enabled(true); // 开启sslbuilder.context(sslContext);})
//                .credential(MongoCredential.createCredential("zy","admin","123456".toCharArray()))
//                .credential(MongoCredential.createMongoX509Credential("O=MyOrg,CN=zy"))
//                .credential(MongoCredential.createMongoX509Credential()).applyToConnectionPoolSettings(builder -> builder.maxSize(1)          // 总最大连接数(所有实例总和).minSize(1)           // 总最小空闲连接数.maxWaitTime(1500, TimeUnit.MILLISECONDS).maxConnectionIdleTime(10, TimeUnit.MINUTES)).applyToSocketSettings(b -> b.connectTimeout(3000, TimeUnit.MILLISECONDS).readTimeout(5000, TimeUnit.MILLISECONDS)).build();MongoClient client = MongoClients.create(settings);MongoDatabase test = client.getDatabase("test");MongoCollection<Document> coll  = test.getCollection("collection1");// Retrieve the first document and print itSystem.out.println(coll.getNamespace());System.out.println(coll.find().first());MongoCollection<Document> collection = client.getDatabase("zy").getCollection("test1");collection.find().forEach(System.out::println);}/*** Load CA certificate from the file into the Trust Store.* Use PKCS12 keystore storing the Client certificate and read it into the {@link KeyStore}* Generate {@link SSLContext} from the Trust Store and {@link KeyStore}** @return SSLContext** @throws IOException* @throws CertificateException* @throws NoSuchAlgorithmException* @throws KeyStoreException* @throws KeyManagementException*/private static SSLContext getSSLContext() throws IOException, CertificateException,NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {//        String certsPath = System.getProperty("cert_path");String certsPath = "C:\\Users\\Administrator\\Desktop\\crt\\";// Path to the CA certificate on diskString caCertPath = certsPath + "ca.crt";// 避坑:使用JKS认证失败// openssl pkcs12 -export -inkey zy.key -in zy.pem -out zy.p12// Path to the PKCS12 Key Store holding the Client certificateString clientCertPath = certsPath + "zy1_pem.p12";String clientCertPwd  = "123456";SSLContext sslContext;try (InputStream caInputStream = new FileInputStream(caCertPath);InputStream clientInputStream = new FileInputStream(clientCertPath)) {// Read Client certificate from PKCS12 Key StoreKeyStore clientKS = KeyStore.getInstance("PKCS12");clientKS.load(clientInputStream, clientCertPwd.toCharArray());// Retrieve Key Managers from the Client certificate Key StoreKeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());kmf.init(clientKS, clientCertPwd.toCharArray());KeyManager[] keyManagers = kmf.getKeyManagers();// Read CA certificate from file and convert it into X509CertificateCertificateFactory certFactory = CertificateFactory.getInstance("X509");X509Certificate caCert = (X509Certificate)certFactory.generateCertificate(caInputStream);KeyStore caKS = KeyStore.getInstance(KeyStore.getDefaultType());caKS.load(null);caKS.setCertificateEntry("caCert", caCert);// Initialize Trust ManagerTrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(caKS);// Create SSLContext. We need Trust Manager only in this use casesslContext = SSLContext.getInstance("TLS");sslContext.init(keyManagers, tmf.getTrustManagers(), null);}return sslContext;}
}

MongoShell使用证书连接

./mongosh --host 1.1.1.1 --tls --tlsCAFile /usr/local/database/mongodb8.0.5/crt/ca.crt --tlsCertificateKeyFile /usr/local/database/mongodb8.0.5/crt/zy.pem --authenticationDatabase '$external' --authenticationMechanism MONGODB-X509

相关文章:

  • Matlab基于PSO-MVMD粒子群算法优化多元变分模态分解
  • 逆向破解:x64dbg
  • Python 处理图像并生成 JSONL 元数据文件 - 灵活text版本
  • 机器学习——集成学习基础
  • AI边缘网关_5G/4G边缘计算网关厂家_计讯物联
  • Clion远程开发git触发“No such device or address”的解决方案
  • 数据库笔记(1)
  • Oracle adg环境下调整redo日志组以及standby日志组大小
  • 音视频学习:使用NDK编译FFmpeg动态库
  • Matlab 基于GUI的汽车巡航模糊pid控制
  • 榜单按行显示
  • Baumer工业相机堡盟工业相机的工业视觉是否可以在室外可以做视觉检测项目
  • Fellou智能体调研
  • c# 如何在集合中转换为子类集合
  • 监控易运维管理软件:架构稳健,组件强大
  • 使用 Navicat 将 Excel 导入数据库
  • .NET 8 API 实现websocket,并在前端angular实现调用
  • 代码随想录算法训练营第三十八天|动态规划part6(完全背包2)
  • 设计杂谈-工厂模式
  • Excel-to-JSON插件专业版功能详解:让Excel数据转换更灵活
  • 母亲节书单|关于生育自由的未来
  • 兵韬志略|美2026国防预算未达1万亿,但仍寻求“暗度陈仓”
  • 全国人大常委会启动食品安全法执法检查
  • 美众议院通过法案将“墨西哥湾”更名为“美国湾”
  • 安徽六安原市长潘东旭,已任省市场监督管理局党组书记、局长
  • 金融监管总局:力争实现全国普惠型小微企业贷款增速不低于各项贷款增速