Powered By GitBook
Encrypting Connections with TLS
While authentication limits which clients can connect, TLS can be used to encrypt traffic between client/server and check the server’s identity. Additionally - in the most secure version of TLS with NATS - the server can be configured to verify the client's identity, thus authenticating it. When started in TLS mode, a nats-server will require all clients to connect with TLS. Moreover, if configured to connect with TLS, client libraries will fail to connect to a server without TLS.

Connecting with TLS and verify client identity

Using TLS to connect to a server that verifies the client's identity is straightforward. The client has to provide a certificate and private key. The NATS client will use these to prove it's identity to the server. For the client to verify the server's identity, the CA certificate is provided as well.
Use example certificates created in self signed certificates for testing.
1
> nats-server --tls --tlscert=server-cert.pem --tlskey=server-key.pem --tlscacert rootCA.pem --tlsverify
Copied!
Go
Java
JavaScript
Python
Ruby
TypeScript
C
1
nc, err := nats.Connect("localhost",
2
nats.ClientCert("client-cert.pem", "client-key.pem"),
3
nats.RootCAs("rootCA.pem"))
4
if err != nil {
5
log.Fatal(err)
6
}
7
defer nc.Close()
8
9
// Do something with the connection
Copied!
1
// This examples requires certificates to be in the java keystore format (.jks).
2
// To do so openssl is used to generate a pkcs12 file (.p12) from client-cert.pem and client-key.pem.
3
// The resulting file is then imported int a java keystore named keystore.jks using keytool which is part of java jdk.
4
// keytool is also used to import the CA certificate rootCA.pem into truststore.jks.
5
//
6
// openssl pkcs12 -export -out keystore.p12 -inkey client-key.pem -in client-cert.pem -password pass:password
7
// keytool -importkeystore -srcstoretype PKCS12 -srckeystore keystore.p12 -srcstorepass password -destkeystore keystore.jks -deststorepass password
8
//
9
// keytool -importcert -trustcacerts -file rootCA.pem -storepass password -noprompt -keystore truststore.jks
10
class SSLUtils {
11
public static String KEYSTORE_PATH = "keystore.jks";
12
public static String TRUSTSTORE_PATH = "truststore.jks";
13
public static String STORE_PASSWORD = "password";
14
public static String KEY_PASSWORD = "password";
15
public static String ALGORITHM = "SunX509";
16
17
public static KeyStore loadKeystore(String path) throws Exception {
18
KeyStore store = KeyStore.getInstance("JKS");
19
BufferedInputStream in = new BufferedInputStream(new FileInputStream(path));
20
21
try {
22
store.load(in, STORE_PASSWORD.toCharArray());
23
} finally {
24
if (in != null) {
25
in.close();
26
}
27
}
28
29
return store;
30
}
31
32
public static KeyManager[] createTestKeyManagers() throws Exception {
33
KeyStore store = loadKeystore(KEYSTORE_PATH);
34
KeyManagerFactory factory = KeyManagerFactory.getInstance(ALGORITHM);
35
factory.init(store, KEY_PASSWORD.toCharArray());
36
return factory.getKeyManagers();
37
}
38
39
public static TrustManager[] createTestTrustManagers() throws Exception {
40
KeyStore store = loadKeystore(TRUSTSTORE_PATH);
41
TrustManagerFactory factory = TrustManagerFactory.getInstance(ALGORITHM);
42
factory.init(store);
43
return factory.getTrustManagers();
44
}
45
46
public static SSLContext createSSLContext() throws Exception {
47
SSLContext ctx = SSLContext.getInstance(Options.DEFAULT_SSL_PROTOCOL);
48
ctx.init(createTestKeyManagers(), createTestTrustManagers(), new SecureRandom());
49
return ctx;
50
}
51
}
52
53
public class ConnectTLS {
54
public static void main(String[] args) {
55
56
try {
57
SSLContext ctx = SSLUtils.createSSLContext();
58
Options options = new Options.Builder().
59
server("nats://localhost:4222").
60
sslContext(ctx). // Set the SSL context
61
build();
62
Connection nc = Nats.connect(options);
63
64
// Do something with the connection
65
66
nc.close();
67
} catch (Exception e) {
68
e.printStackTrace();
69
}
70
}
71
}
Copied!
1
let caCert = fs.readFileSync("rootCA.pem");
2
let clientCert = fs.readFileSync("client-cert.pem");
3
let clientKey = fs.readFileSync("client-key.pem");
4
let nc = NATS.connect({
5
url: url,
6
tls: {
7
ca: [caCert],
8
key: [clientKey],
9
cert: [clientCert]
10
}
11
});
Copied!
1
nc = NATS()
2
3
ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
4
ssl_ctx.load_verify_locations('rootCA.pem')
5
ssl_ctx.load_cert_chain(certfile='client-cert.pem',
6
keyfile='client-key.pem')
7
await nc.connect(io_loop=loop, tls=ssl_ctx)
8
9
await nc.connect(servers=["nats://demo.nats.io:4222"], tls=ssl_ctx)
10
11
# Do something with the connection.
Copied!
1
EM.run do
2
3
options = {
4
:servers => [
5
'nats://localhost:4222',
6
],
7
:tls => {
8
:private_key_file => 'client-key.pem',
9
:cert_chain_file => 'client-cert.pem',
10
:ca_file => 'rootCA.pem'
11
}
12
}
13
14
NATS.connect(options) do |nc|
15
puts "#{Time.now.to_f} - Connected to NATS at #{nc.connected_server}"
16
17
nc.subscribe("hello") do |msg|
18
puts "#{Time.now.to_f} - Received: #{msg}"
19
end
20
21
nc.flush do
22
nc.publish("hello", "world")
23
end
24
25
EM.add_periodic_timer(0.1) do
26
next unless nc.connected?
27
nc.publish("hello", "hello")
28
end
29
30
# Set default callbacks
31
nc.on_error do |e|
32
puts "#{Time.now.to_f } - Error: #{e}"
33
end
34
35
nc.on_disconnect do |reason|
36
puts "#{Time.now.to_f} - Disconnected: #{reason}"
37
end
38
39
nc.on_reconnect do |nc|
40
puts "#{Time.now.to_f} - Reconnected to NATS server at #{nc.connected_server}"
41
end
42
43
nc.on_close do
44
puts "#{Time.now.to_f} - Connection to NATS closed"
45
EM.stop
46
end
47
end
48
end
Copied!
1
let caCert = readFileSync("rootCA.pem");
2
let clientCert = readFileSync("client-cert.pem");
3
let clientKey = readFileSync("client-key.pem");
4
let nc = await connect({
5
url: url,
6
tls: {
7
ca: [caCert],
8
key: [clientKey],
9
cert: [clientCert]
10
}
11
});
Copied!
1
natsConnection *conn = NULL;
2
natsOptions *opts = NULL;
3
natsStatus s = NATS_OK;
4
5
s = natsOptions_Create(&opts);
6
if (s == NATS_OK)
7
s = natsOptions_LoadCertificatesChain(opts, "client-cert.pem", "client-key.pem");
8
if (s == NATS_OK)
9
s = natsOptions_LoadCATrustedCertificates(opts, "rootCA.pem");
10
if (s == NATS_OK)
11
s = natsConnection_Connect(&conn, opts);
12
13
(...)
14
15
// Destroy objects that were created
16
natsConnection_Destroy(conn);
17
natsOptions_Destroy(opts);
Copied!

Connecting with the TLS Protocol

Clients (such as Go, Java, Javascript, Ruby and Type Script) support providing a URL containing the tls protocol to the NATS connect call. This will turn on TLS without the need for further code changes. However, in that case there is likely some form of default or environmental settings to allow the TLS libraries of your programming language to find certificate and trusted CAs. Unless these settings are taken into accounts or otherwise modified, this way of connecting is very likely to fail.
Last modified 8mo ago