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

Go

  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. // Do something with the connection

Java

  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. public static KeyStore loadKeystore(String path) throws Exception {
  17. KeyStore store = KeyStore.getInstance("JKS");
  18. BufferedInputStream in = new BufferedInputStream(new FileInputStream(path));
  19. try {
  20. store.load(in, STORE_PASSWORD.toCharArray());
  21. } finally {
  22. if (in != null) {
  23. in.close();
  24. }
  25. }
  26. return store;
  27. }
  28. public static KeyManager[] createTestKeyManagers() throws Exception {
  29. KeyStore store = loadKeystore(KEYSTORE_PATH);
  30. KeyManagerFactory factory = KeyManagerFactory.getInstance(ALGORITHM);
  31. factory.init(store, KEY_PASSWORD.toCharArray());
  32. return factory.getKeyManagers();
  33. }
  34. public static TrustManager[] createTestTrustManagers() throws Exception {
  35. KeyStore store = loadKeystore(TRUSTSTORE_PATH);
  36. TrustManagerFactory factory = TrustManagerFactory.getInstance(ALGORITHM);
  37. factory.init(store);
  38. return factory.getTrustManagers();
  39. }
  40. public static SSLContext createSSLContext() throws Exception {
  41. SSLContext ctx = SSLContext.getInstance(Options.DEFAULT_SSL_PROTOCOL);
  42. ctx.init(createTestKeyManagers(), createTestTrustManagers(), new SecureRandom());
  43. return ctx;
  44. }
  45. }
  46. public class ConnectTLS {
  47. public static void main(String[] args) {
  48. try {
  49. SSLContext ctx = SSLUtils.createSSLContext();
  50. Options options = new Options.Builder().
  51. server("nats://localhost:4222").
  52. sslContext(ctx). // Set the SSL context
  53. build();
  54. Connection nc = Nats.connect(options);
  55. // Do something with the connection
  56. nc.close();
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }

JavaScript

  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. });

Python

  1. nc = NATS()
  2. ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
  3. ssl_ctx.load_verify_locations('rootCA.pem')
  4. ssl_ctx.load_cert_chain(certfile='client-cert.pem',
  5. keyfile='client-key.pem')
  6. await nc.connect(io_loop=loop, tls=ssl_ctx)
  7. await nc.connect(servers=["nats://demo.nats.io:4222"], tls=ssl_ctx)
  8. # Do something with the connection.

Ruby

  1. EM.run do
  2. options = {
  3. :servers => [
  4. 'nats://localhost:4222',
  5. ],
  6. :tls => {
  7. :private_key_file => 'client-key.pem',
  8. :cert_chain_file => 'client-cert.pem',
  9. :ca_file => 'rootCA.pem'
  10. }
  11. }
  12. NATS.connect(options) do |nc|
  13. puts "#{Time.now.to_f} - Connected to NATS at #{nc.connected_server}"
  14. nc.subscribe("hello") do |msg|
  15. puts "#{Time.now.to_f} - Received: #{msg}"
  16. end
  17. nc.flush do
  18. nc.publish("hello", "world")
  19. end
  20. EM.add_periodic_timer(0.1) do
  21. next unless nc.connected?
  22. nc.publish("hello", "hello")
  23. end
  24. # Set default callbacks
  25. nc.on_error do |e|
  26. puts "#{Time.now.to_f } - Error: #{e}"
  27. end
  28. nc.on_disconnect do |reason|
  29. puts "#{Time.now.to_f} - Disconnected: #{reason}"
  30. end
  31. nc.on_reconnect do |nc|
  32. puts "#{Time.now.to_f} - Reconnected to NATS server at #{nc.connected_server}"
  33. end
  34. nc.on_close do
  35. puts "#{Time.now.to_f} - Connection to NATS closed"
  36. EM.stop
  37. end
  38. end
  39. end

TypeScript

  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. });

C

  1. natsConnection *conn = NULL;
  2. natsOptions *opts = NULL;
  3. natsStatus s = NATS_OK;
  4. s = natsOptions_Create(&opts);
  5. if (s == NATS_OK)
  6. s = natsOptions_LoadCertificatesChain(opts, "client-cert.pem", "client-key.pem");
  7. if (s == NATS_OK)
  8. s = natsOptions_LoadCATrustedCertificates(opts, "rootCA.pem");
  9. if (s == NATS_OK)
  10. s = natsConnection_Connect(&conn, opts);
  11. (...)
  12. // Destroy objects that were created
  13. natsConnection_Destroy(conn);
  14. natsOptions_Destroy(opts);

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.