Enable TLS/SSL on a Connection (original) (raw)
In this guide, you can learn how to connect to MongoDB instances with theTLS/SSLsecurity protocol using the underlying TLS/SSL support in the JDK. To configure your connection to use TLS/SSL, enable the TLS/SSL settings in either the ConnectionStringor MongoClientSettings.
You can enable TLS/SSL for the connection to your MongoDB instance in two different ways: through a parameter in your connection string, or using a method in the MongoClientSettings.Builder
class.
Note
If you connect by using the DNS seedlist protocol, indicated by themongodb+srv
prefix in your connection string, the driver enables TLS/SSL. To disable it, set the tls
or ssl
parameter value tofalse
in your connection string or MongoClientSettings
instance.
To learn more about connection behavior when you use a DNS seedlist, see the SRV Connection Formatsection in the Server manual.
To enable TLS/SSL on a connection with a ConnectionString, assign the connection string parameter tls
a value of true
in the connection string passed toMongoClients.create()
:
MongoClient mongoClient = MongoClients.create("mongodb+srv://<db_username>:<db_password>@<cluster-url>?tls=true");
The following table describes the parameter you can include in your connection string to modify the driver's TSL behavior:
Option Name | Type | Description |
---|---|---|
ssl | boolean | Specifies that all communication with MongoDB instances mustuse TLS/SSL. Superseded by the tls option.Default: false |
tls | boolean | Specifies that all communication with MongoDB instances mustuse TLS. Supersedes the ssl option.Default: false |
tlsInsecure | boolean | Specifies that the driver must allow invalid hostnames for TLSconnections. Has the same effect as settingtlsAllowInvalidHostnames to true. To configure TLS security constraints in other ways, use acustom SSLContext.Default: false |
tlsAllowInvalidHostnames | boolean | Specifies that the driver must allow invalid hostnames in thecertificate for TLS connections. SupersedessslInvalidHostNameAllowed.Default: false |
To configure your MongoClient
's TLS/SSL connection options using theMongoClientSettings.Builder
class, chain theapplyToSslSettings()method. Set the enabled
property to true
in the SslSettings.Builder
block to enable TLS/SSL:
MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToSslSettings(builder ->
builder.enabled(true))
.build());
The following table describes the methods you can chain to your settings to modify the driver's TSL behavior:
Method | Description |
---|---|
applyConnectionString() | Uses the settings from a ConnectionString object. |
applySettings() | Uses the TLS/SSL settings specified in a SslSettings object. |
context() | Sets the SSLContext for use when you enable TLS/SSL. |
enabled() | Whether to enable TLS/SSL. (You must enable this for Atlas clusters.) |
invalidHostNameAllowed() | Whether to allow a mismatch between the server's hostname and the hostname specified by the TLS certificate. |
Java applications that initiate TLS/SSL requests require access to cryptographic certificates that prove identity for the application itself and other applications with which the application interacts. You can configure access to these certificates in your application with the following mechanisms:
- The JVM Trust Store and JVM Key Store
- A Client-Specific Trust Store and Key Store
Note
The following sections are based on the documentation for Oracle JDK, so some might not apply to your JDK or to your custom TLS/SSL implementation.
Note
By default, the JRE includes many commonly used public certificates from signing authorities like Let's Encrypt. As a result, you can connect to instances of MongoDB Atlas (or any other server whose certificate is signed by an authority in the JRE's default certificate store) with TLS/SSL without configuring the trust store.
The JVM trust store saves certificates that securely identify other applications with which your Java application interacts. Using these certificates, your application can prove that the connection to another application is genuine and secure from tampering by third parties.
If your MongoDB instance uses a certificate that is signed by an authority that is not present in the JRE's default certificate store, your application must configure two system properties to initiate SSL/TLS requests. These properties ensure that your application can validate the TLS/SSL certificate presented by a connected MongoDB instance.
javax.net.ssl.trustStore
: the path to a trust store containing the certificate of the signing authorityjavax.net.ssl.trustStorePassword
: the password to access the trust store defined injavax.net.ssl.trustStore
You can create a trust store with the keytoolcommand line tool provided as part of the JDK:
keytool -importcert -trustcacerts -file <path to certificate authority file>
-keystore <path to trust store> -storepass <password>
Note
By default, MongoDB instances do not perform client certificate validation. You must configure the key store if you configured your MongoDB instance to validate client certificates.
The JVM key store saves certificates that securely identify your Java application to other applications. Using these certificates, other applications can prove that the connection to your application is genuine and secure from tampering by third parties.
An application that initiates TLS/SSL requests needs to set two JVM system properties to ensure that the client presents a TLS/SSL certificate to the MongoDB deployment:
javax.net.ssl.keyStore
: the path to a key store containing the client's TLS/SSL certificatesjavax.net.ssl.keyStorePassword
: the password to access the key store defined injavax.net.ssl.keyStore
You can create a key store with the keytoolor opensslcommand line tool.
For more information about configuring a Java application to use TLS/SSL, please see the JSSE Reference Guide.
You can configure a client-specific trust store and key store using theinit()
method of the SSLContext
class.
You can find an example showing how to configure a client with an SSLContext
instance in theCustomize TLS/SSL Configuration with an SSLContext section of this guide.
For more information about the SSLContext
class, see the API documentation for SSL Context.
By default, the driver ensures that the hostname included in the server's TLS/SSL certificates matches the hostnames provided when constructing a MongoClient
. To disable hostname verification for your application, you can explicitly disable this by setting theinvalidHostNameAllowed
property of the builder to true
in theapplytoSslSettings()
builder lambda:
MongoClientSettings settings = MongoClientSettings.builder()
.applyToSslSettings(builder -> {
builder.enabled(true);
builder.invalidHostNameAllowed(true);
})
.build();
Warning
Disabling hostname verification can make your configurationinsecure. Disable hostname verification only for testing purposes or when there is no other alternative.
To restrict your application to use only the TLS 1.2 protocol, set thejdk.tls.client.protocols
system property to "TLSv1.2".
Note
Java Runtime Environments (JREs) before Java 8 only enabled the TLS 1.2 protocol in update releases. If your JRE has not enabled the TLS 1.2 protocol, upgrade to a later release to connect by using TLS 1.2.
If your TLS/SSL configuration requires customization, you can set the sslContext
property of your MongoClient
by passing an SSLContextobject to the builder in the applyToSslSettings()
lambda:
SSLContext sslContext = ...
MongoClientSettings settings = MongoClientSettings.builder()
.applyToSslSettings(builder -> {
builder.enabled(true);
builder.context(sslContext);
})
.build();
MongoClient client = MongoClients.create(settings);
If you use the driver with Netty for network IO, you have an option to plug an alternative TLS/SSL protocol implementation provided by Netty.
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
Note
The driver tests with Netty version io.netty:netty-all:4.1.87.Final
To instruct the driver to useio.netty.handler.ssl.SslContext, configureNettyTransportSettingswhen you define your MongoClientSettings. Use MongoClientSettings.Builder.transportSettingsand NettyTransportSettings.Builder.sslContextto build your settings:
SslContext sslContext = SslContextBuilder.forClient()
.sslProvider(SslProvider.OPENSSL)
.build();
MongoClientSettings settings = MongoClientSettings.builder()
.applyToSslSettings(builder -> builder.enabled(true))
.transportSettings(TransportSettings.nettyBuilder()
.sslContext(sslContext)
.build())
.build();
MongoClient client = MongoClients.create(settings);
For more details about the io.netty.handler.ssl.SslProvider
, see the Netty documentation
OCSP is a standard used to check whether X.509 certificates have been revoked. A certificate authority can add an X.509 certificate to the Certificate Revocation List (CRL) before the expiry time to invalidate the certificate. When a client sends an X.509 certificate during the TLS handshake, the CA's revocation server checks the CRL and returns a status of "good", "revoked", or "unknown".
The driver supports the following variations of OCSP:
- Client-Driven OCSP
- OCSP Stapling
The following sections describe the differences between them and how to enable them for your application.
Note
The Java driver uses the JVM arguments configured for the application and cannot be overridden for a specific MongoClient
instance.
In client-driven OCSP, the client sends the certificate in an OCSP request to an OCSP responder after receiving the certificate from the server. The OCSP responder checks the status of the certificate with a certificate authority (CA) and reports whether it's valid in a response sent to the client.
To enable client-driven OCSP for your application, set the following JVM system properties:
Property | Value |
---|---|
com.sun.net.ssl.checkRevocation | Set this property to true to enable revocation checking. |
ocsp.enable | Set this property to true to enable client-driven OCSP. |
Warning
If the OCSP responder is unavailable, the TLS support provided by the JDK reports a "hard fail". This differs from the "soft fail" behavior of the MongoDB Shell and some other drivers.
OCSP stapling is a mechanism in which the server must obtain the signed certificate from the certificate authority (CA) and include it in a time-stamped OCSP response to the client.
To enable OCSP stapling for your application, set the following JVM system properties:
Property | Description |
---|---|
com.sun.net.ssl.checkRevocation | Set this property to true to enable revocation checking. |
jdk.tls.client.enableStatusRequestExtension | Set this property to true to enable OCSP stapling.If unset or set to false, the connection can proceed regardless of the presence or status of the certificate revocation response. |
For more information about OCSP, check out the following resources:
- Oracle JDK 8 Documentation on how to enable OCSP for an application
- Official IETF specification for OCSP (RFC 6960)