tls: enforce certificate verification
[vpp.git] / src / vnet / session-apps / tls.c
index a747990..d71dfb4 100644 (file)
 #include <mbedtls/timing.h>
 #include <mbedtls/debug.h>
 
-#define TLS_DEBUG (0)
-#define TLS_DEBUG_LEVEL_CLIENT (0)
-#define TLS_DEBUG_LEVEL_SERVER (0)
-#define TLS_CHUNK_SIZE (1 << 14)
-#define TLS_USE_OUR_MEM_FUNCS (0)
+#define TLS_DEBUG              0
+#define TLS_DEBUG_LEVEL_CLIENT         0
+#define TLS_DEBUG_LEVEL_SERVER         0
+
+#define TLS_CHUNK_SIZE                 (1 << 14)
+#define TLS_USE_OUR_MEM_FUNCS  0
+#define TLS_CA_CERT_PATH       "/etc/ssl/certs/ca-certificates.crt"
 
 #if TLS_DEBUG
 #define TLS_DBG(_lvl, _fmt, _args...)                  \
@@ -67,6 +69,8 @@ typedef CLIB_PACKED (struct tls_cxt_id_
 }) tls_ctx_id_t;
 /* *INDENT-ON* */
 
+STATIC_ASSERT (sizeof (tls_ctx_id_t) <= 42, "ctx id must be less than 42");
+
 typedef struct tls_ctx_
 {
   union
@@ -79,12 +83,13 @@ typedef struct tls_ctx_
 #define tls_session_handle c_tls_ctx_id.tls_session_handle
 #define listener_ctx_index c_tls_ctx_id.listener_ctx_index
 #define tcp_is_ip4 c_tls_ctx_id.tcp_is_ip4
-
+#define tls_ctx_idx c_c_index
   /* Temporary storage for session open opaque. Overwritten once
    * underlying tcp connection is established */
 #define parent_app_api_context c_s_index
 
   u8 is_passive_close;
+  u8 *srv_hostname;
   mbedtls_ssl_context ssl;
   mbedtls_ssl_config conf;
   mbedtls_x509_crt srvcert;
@@ -94,13 +99,19 @@ typedef struct tls_ctx_
 typedef struct tls_main_
 {
   u32 app_index;
-  tls_ctx_t **ctx_pool;
+  tls_ctx_t ***ctx_pool;
   mbedtls_ctr_drbg_context *ctr_drbgs;
   mbedtls_entropy_context *entropy_pools;
   tls_ctx_t *listener_ctx_pool;
   tls_ctx_t *half_open_ctx_pool;
   clib_rwlock_t half_open_rwlock;
   mbedtls_x509_crt cacert;
+
+  /*
+   * Config
+   */
+  u8 use_test_cert_in_ca;
+  char *ca_cert_path;
 } tls_main_t;
 
 static tls_main_t tls_main;
@@ -174,37 +185,40 @@ tls_ctx_alloc (void)
 {
   u8 thread_index = vlib_get_thread_index ();
   tls_main_t *tm = &tls_main;
-  tls_ctx_t *ctx;
+  tls_ctx_t **ctx;
 
   pool_get (tm->ctx_pool[thread_index], ctx);
-  memset (ctx, 0, sizeof (*ctx));
-  ctx->c_thread_index = thread_index;
+  if (!(*ctx))
+    *ctx = clib_mem_alloc (sizeof (tls_ctx_t));
+
+  memset (*ctx, 0, sizeof (tls_ctx_t));
+  (*ctx)->c_thread_index = thread_index;
   return ctx - tm->ctx_pool[thread_index];
 }
 
 void
 tls_ctx_free (tls_ctx_t * ctx)
 {
-  pool_put (tls_main.ctx_pool[vlib_get_thread_index ()], ctx);
+  vec_free (ctx->srv_hostname);
+  pool_put_index (tls_main.ctx_pool[vlib_get_thread_index ()],
+                 ctx->tls_ctx_idx);
 }
 
 tls_ctx_t *
 tls_ctx_get (u32 ctx_index)
 {
-  return pool_elt_at_index (tls_main.ctx_pool[vlib_get_thread_index ()],
-                           ctx_index);
+  tls_ctx_t **ctx;
+  ctx = pool_elt_at_index (tls_main.ctx_pool[vlib_get_thread_index ()],
+                          ctx_index);
+  return (*ctx);
 }
 
 tls_ctx_t *
 tls_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
 {
-  return pool_elt_at_index (tls_main.ctx_pool[thread_index], ctx_index);
-}
-
-u32
-tls_ctx_index (tls_ctx_t * ctx)
-{
-  return (ctx - tls_main.ctx_pool[vlib_get_thread_index ()]);
+  tls_ctx_t **ctx;
+  ctx = pool_elt_at_index (tls_main.ctx_pool[thread_index], ctx_index);
+  return (*ctx);
 }
 
 u32
@@ -219,9 +233,9 @@ tls_listener_ctx_alloc (void)
 }
 
 void
-tls_ctx_listener_free (tls_ctx_t * ctx)
+tls_listener_ctx_free (tls_ctx_t * ctx)
 {
-  pool_put (tls_main.half_open_ctx_pool, ctx);
+  pool_put (tls_main.listener_ctx_pool, ctx);
 }
 
 tls_ctx_t *
@@ -414,22 +428,22 @@ tls_ctx_init_client (tls_ctx_t * ctx)
       return -1;
     }
 
-  if ((rv = mbedtls_ssl_set_hostname (&ctx->ssl, "SERVER NAME")) != 0)
+  if ((rv = mbedtls_ssl_set_hostname (&ctx->ssl,
+                                     (const char *) ctx->srv_hostname)) != 0)
     {
       TLS_DBG (1, "failed\n  ! mbedtls_ssl_set_hostname returned %d\n", rv);
       return -1;
     }
 
-  ctx_ptr = uword_to_pointer (tls_ctx_index (ctx), void *);
+  ctx_ptr = uword_to_pointer (ctx->tls_ctx_idx, void *);
   mbedtls_ssl_set_bio (&ctx->ssl, ctx_ptr, tls_net_send, tls_net_recv, NULL);
-
   mbedtls_debug_set_threshold (TLS_DEBUG_LEVEL_CLIENT);
 
   /*
    * 2. Do the first 2 steps in the handshake.
    */
   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
-          tls_ctx_index (ctx));
+          ctx->tls_ctx_idx);
   while (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
     {
       rv = mbedtls_ssl_handshake_step (&ctx->ssl);
@@ -437,13 +451,14 @@ tls_ctx_init_client (tls_ctx_t * ctx)
        break;
     }
   TLS_DBG (2, "tls state for [%u]%u is %u", ctx->c_thread_index,
-          tls_ctx_index (ctx), ctx->ssl.state);
+          ctx->tls_ctx_idx, ctx->ssl.state);
   return 0;
 }
 
 static int
 tls_ctx_init_server (tls_ctx_t * ctx)
 {
+  tls_main_t *tm = &tls_main;
   application_t *app;
   void *ctx_ptr;
   int rv;
@@ -466,17 +481,7 @@ tls_ctx_init_server (tls_ctx_t * ctx)
 
   rv = mbedtls_x509_crt_parse (&ctx->srvcert,
                               (const unsigned char *) app->tls_cert,
-                              mbedtls_test_srv_crt_len);
-  if (rv != 0)
-    {
-      TLS_DBG (1, " failed\n  !  mbedtls_x509_crt_parse returned %d", rv);
-      goto exit;
-    }
-
-  /* TODO clone CA */
-  rv = mbedtls_x509_crt_parse (&ctx->srvcert,
-                              (const unsigned char *) mbedtls_test_cas_pem,
-                              mbedtls_test_cas_pem_len);
+                              vec_len (app->tls_cert));
   if (rv != 0)
     {
       TLS_DBG (1, " failed\n  !  mbedtls_x509_crt_parse returned %d", rv);
@@ -485,7 +490,7 @@ tls_ctx_init_server (tls_ctx_t * ctx)
 
   rv = mbedtls_pk_parse_key (&ctx->pkey,
                             (const unsigned char *) app->tls_key,
-                            mbedtls_test_srv_key_len, NULL, 0);
+                            vec_len (app->tls_key), NULL, 0);
   if (rv != 0)
     {
       TLS_DBG (1, " failed\n  !  mbedtls_pk_parse_key returned %d", rv);
@@ -513,7 +518,7 @@ tls_ctx_init_server (tls_ctx_t * ctx)
      mbedtls_ssl_cache_set );
    */
 
-  mbedtls_ssl_conf_ca_chain (&ctx->conf, ctx->srvcert.next, NULL);
+  mbedtls_ssl_conf_ca_chain (&ctx->conf, &tm->cacert, NULL);
   if ((rv = mbedtls_ssl_conf_own_cert (&ctx->conf, &ctx->srvcert, &ctx->pkey))
       != 0)
     {
@@ -528,7 +533,7 @@ tls_ctx_init_server (tls_ctx_t * ctx)
     }
 
   mbedtls_ssl_session_reset (&ctx->ssl);
-  ctx_ptr = uword_to_pointer (tls_ctx_index (ctx), void *);
+  ctx_ptr = uword_to_pointer (ctx->tls_ctx_idx, void *);
   mbedtls_ssl_set_bio (&ctx->ssl, ctx_ptr, tls_net_send, tls_net_recv, NULL);
 
   mbedtls_debug_set_threshold (TLS_DEBUG_LEVEL_SERVER);
@@ -537,7 +542,7 @@ tls_ctx_init_server (tls_ctx_t * ctx)
    * 3. Start handshake state machine
    */
   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
-          tls_ctx_index (ctx));
+          ctx->tls_ctx_idx);
   while (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
     {
       rv = mbedtls_ssl_handshake_step (&ctx->ssl);
@@ -546,7 +551,7 @@ tls_ctx_init_server (tls_ctx_t * ctx)
     }
 
   TLS_DBG (2, "tls state for [%u]%u is %u", ctx->c_thread_index,
-          tls_ctx_index (ctx), ctx->ssl.state);
+          ctx->tls_ctx_idx, ctx->ssl.state);
   return 0;
 
 exit:
@@ -569,7 +574,7 @@ tls_notify_app_accept (tls_ctx_t * ctx)
 
   app_session = session_alloc (vlib_get_thread_index ());
   app_session->app_index = ctx->parent_app_index;
-  app_session->connection_index = tls_ctx_index (ctx);
+  app_session->connection_index = ctx->tls_ctx_idx;
   app_session->session_type = app_listener->session_type;
   app_session->listener_index = app_listener->session_index;
   if ((rv = session_alloc_fifos (sm, app_session)))
@@ -578,13 +583,12 @@ tls_notify_app_accept (tls_ctx_t * ctx)
       return rv;
     }
   ctx->c_s_index = app_session->session_index;
-  ctx->c_c_index = tls_ctx_index (ctx);
   ctx->app_session_handle = session_handle (app_session);
   return app->cb_fns.session_accept_callback (app_session);
 }
 
 static int
-tls_notify_app_connected (tls_ctx_t * ctx)
+tls_notify_app_connected (tls_ctx_t * ctx, u8 is_failed)
 {
   int (*cb_fn) (u32, u32, stream_session_t *, u8);
   stream_session_t *app_session;
@@ -594,10 +598,13 @@ tls_notify_app_connected (tls_ctx_t * ctx)
   app = application_get (ctx->parent_app_index);
   cb_fn = app->cb_fns.session_connected_callback;
 
+  if (is_failed)
+    goto failed;
+
   sm = application_get_connect_segment_manager (app);
   app_session = session_alloc (vlib_get_thread_index ());
   app_session->app_index = ctx->parent_app_index;
-  app_session->connection_index = tls_ctx_index (ctx);
+  app_session->connection_index = ctx->tls_ctx_idx;
   app_session->session_type =
     session_type_from_proto_and_ip (TRANSPORT_PROTO_TLS, ctx->tcp_is_ip4);
   if (session_alloc_fifos (sm, app_session))
@@ -605,13 +612,12 @@ tls_notify_app_connected (tls_ctx_t * ctx)
 
   ctx->app_session_handle = session_handle (app_session);
   ctx->c_s_index = app_session->session_index;
-  ctx->c_c_index = tls_ctx_index (ctx);
   app_session->session_state = SESSION_STATE_READY;
   if (cb_fn (ctx->parent_app_index, ctx->parent_app_api_context,
             app_session, 0 /* not failed */ ))
     {
       TLS_DBG (1, "failed to notify app");
-      tls_disconnect (tls_ctx_index (ctx), vlib_get_thread_index ());
+      tls_disconnect (ctx->tls_ctx_idx, vlib_get_thread_index ());
     }
 
   return 0;
@@ -632,7 +638,7 @@ tls_handshake_rx (tls_ctx_t * ctx)
       if (rv != 0)
        break;
     }
-  TLS_DBG (2, "tls state for %u is %u", tls_ctx_index (ctx), ctx->ssl.state);
+  TLS_DBG (2, "tls state for %u is %u", ctx->tls_ctx_idx, ctx->ssl.state);
 
   if (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
     return 0;
@@ -652,12 +658,17 @@ tls_handshake_rx (tls_ctx_t * ctx)
          mbedtls_x509_crt_verify_info (buf, sizeof (buf), "  ! ", flags);
          TLS_DBG (1, "%s\n", buf);
 
-         /* For testing purposes not enforcing this */
-         /* tls_disconnect (tls_ctx_index (ctx), vlib_get_thread_index ());
-            return -1;
+         /*
+          * Presence of hostname enforces strict certificate verification
           */
+         if (ctx->srv_hostname)
+           {
+             tls_disconnect (ctx->tls_ctx_idx, vlib_get_thread_index ());
+             tls_notify_app_connected (ctx, /* is failed */ 1);
+             return -1;
+           }
        }
-      tls_notify_app_connected (ctx);
+      tls_notify_app_connected (ctx, /* is failed */ 0);
     }
   else
     {
@@ -665,7 +676,7 @@ tls_handshake_rx (tls_ctx_t * ctx)
     }
 
   TLS_DBG (1, "Handshake for %u complete. TLS cipher is %x",
-          tls_ctx_index (ctx), ctx->ssl.session->ciphersuite);
+          ctx->tls_ctx_idx, ctx->ssl.session->ciphersuite);
   return 0;
 }
 
@@ -721,6 +732,7 @@ tls_session_accept_callback (stream_session_t * tls_session)
   ctx = tls_ctx_get (ctx_index);
   memcpy (ctx, lctx, sizeof (*lctx));
   ctx->c_thread_index = vlib_get_thread_index ();
+  ctx->tls_ctx_idx = ctx_index;
   tls_session->session_state = SESSION_STATE_READY;
   tls_session->opaque = ctx_index;
   ctx->tls_session_handle = session_handle (tls_session);
@@ -840,15 +852,22 @@ tls_session_connected_callback (u32 tls_app_index, u32 ho_ctx_index,
   cb_fn = app->cb_fns.session_connected_callback;
 
   if (is_fail)
-    goto failed;
+    {
+      tls_ctx_half_open_reader_unlock ();
+      tls_ctx_half_open_free (ho_ctx_index);
+      return cb_fn (ho_ctx->parent_app_index, ho_ctx->c_s_index, 0,
+                   1 /* failed */ );
+    }
 
   ctx_index = tls_ctx_alloc ();
   ctx = tls_ctx_get (ctx_index);
   clib_memcpy (ctx, ho_ctx, sizeof (*ctx));
-  ctx->c_thread_index = vlib_get_thread_index ();
   tls_ctx_half_open_reader_unlock ();
   tls_ctx_half_open_free (ho_ctx_index);
 
+  ctx->c_thread_index = vlib_get_thread_index ();
+  ctx->tls_ctx_idx = ctx_index;
+
   TLS_DBG (1, "TCP connect for %u returned %u. New connection [%u]%u",
           ho_ctx_index, is_fail, vlib_get_thread_index (),
           (ctx) ? ctx_index : ~0);
@@ -858,12 +877,6 @@ tls_session_connected_callback (u32 tls_app_index, u32 ho_ctx_index,
   tls_session->session_state = SESSION_STATE_READY;
 
   return tls_ctx_init_client (ctx);
-
-failed:
-  tls_ctx_half_open_reader_unlock ();
-  tls_ctx_half_open_free (ho_ctx_index);
-  return cb_fn (ho_ctx->parent_app_index, ho_ctx->c_s_index, 0,
-               1 /* failed */ );
 }
 
 /* *INDENT-OFF* */
@@ -897,6 +910,11 @@ tls_connect (transport_endpoint_t * tep)
   ctx->parent_app_index = sep->app_index;
   ctx->parent_app_api_context = sep->opaque;
   ctx->tcp_is_ip4 = sep->is_ip4;
+  if (sep->hostname)
+    {
+      ctx->srv_hostname = format (0, "%v", sep->hostname);
+      vec_terminate_c_string (ctx->srv_hostname);
+    }
   tls_ctx_half_open_reader_unlock ();
 
   app = application_get (sep->app_index);
@@ -934,6 +952,13 @@ tls_disconnect (u32 ctx_index, u32 thread_index)
                                     app_session->server_tx_fifo);
       session_free (app_session);
     }
+  if (ctx->ssl.conf->endpoint == MBEDTLS_SSL_IS_SERVER)
+    {
+      mbedtls_x509_crt_free (&ctx->srvcert);
+      mbedtls_pk_free (&ctx->pkey);
+    }
+  mbedtls_ssl_free (&ctx->ssl);
+  mbedtls_ssl_config_free (&ctx->conf);
   tls_ctx_free (ctx);
 }
 
@@ -972,12 +997,26 @@ tls_start_listen (u32 app_listener_index, transport_endpoint_t * tep)
 }
 
 u32
-tls_stop_listen (u32 listener_index)
+tls_stop_listen (u32 lctx_index)
 {
-  clib_warning ("TBD");
+  tls_main_t *tm = &tls_main;
+  application_t *tls_app;
+  tls_ctx_t *lctx;
+  lctx = tls_listener_ctx_get (lctx_index);
+  tls_app = application_get (tm->app_index);
+  application_stop_listen (tls_app, lctx->tls_session_handle);
+  tls_listener_ctx_free (lctx);
   return 0;
 }
 
+transport_connection_t *
+tls_connection_get (u32 ctx_index, u32 thread_index)
+{
+  tls_ctx_t *ctx;
+  ctx = tls_ctx_get_w_thread (ctx_index, thread_index);
+  return &ctx->connection;
+}
+
 transport_connection_t *
 tls_listener_get (u32 listener_index)
 {
@@ -997,9 +1036,8 @@ format_tls_ctx (u8 * s, va_list * args)
   if (thread_index != child_ti)
     clib_warning ("app and tls sessions are on different threads!");
 
-  s =
-    format (s, "[#%d][TLS] app %u child %u", child_ti, ctx->parent_app_index,
-           child_si);
+  s = format (s, "[#%d][TLS] app %u child %u", child_ti,
+             ctx->parent_app_index, child_si);
   return s;
 }
 
@@ -1053,6 +1091,7 @@ const static transport_proto_vft_t tls_proto = {
   .open = tls_connect,
   .close = tls_disconnect,
   .bind = tls_start_listen,
+  .get_connection = tls_connection_get,
   .get_listener = tls_listener_get,
   .unbind = tls_stop_listen,
   .tx_type = TRANSPORT_TX_INTERNAL,
@@ -1078,17 +1117,33 @@ tls_init_ca_chain (void)
   tls_main_t *tm = &tls_main;
   int rv;
 
-  /* TODO config */
+  if (!tm->ca_cert_path)
+    tm->ca_cert_path = TLS_CA_CERT_PATH;
+
+  if (access (tm->ca_cert_path, F_OK | R_OK) == -1)
+    {
+      clib_warning ("Could not initialize TLS CA certificates");
+      return -1;
+    }
+
   mbedtls_x509_crt_init (&tm->cacert);
-  rv = mbedtls_x509_crt_parse (&tm->cacert,
-                              (const unsigned char *) mbedtls_test_cas_pem,
-                              mbedtls_test_cas_pem_len);
+  rv = mbedtls_x509_crt_parse_file (&tm->cacert, tm->ca_cert_path);
   if (rv < 0)
     {
-      clib_warning ("mbedtls_x509_crt_parse returned -0x%x", -rv);
-      return -1;
+      clib_warning ("Couldn't parse system CA certificates: -0x%x", -rv);
     }
-  return 0;
+  if (tm->use_test_cert_in_ca)
+    {
+      rv = mbedtls_x509_crt_parse (&tm->cacert,
+                                  (const unsigned char *) test_srv_crt_rsa,
+                                  test_srv_crt_rsa_len);
+      if (rv < 0)
+       {
+         clib_warning ("Couldn't parse test certificate: -0x%x", -rv);
+         return -1;
+       }
+    }
+  return (rv < 0 ? -1 : 0);
 }
 
 clib_error_t *
@@ -1152,6 +1207,24 @@ tls_init (vlib_main_t * vm)
 
 VLIB_INIT_FUNCTION (tls_init);
 
+static clib_error_t *
+tls_config_fn (vlib_main_t * vm, unformat_input_t * input)
+{
+  tls_main_t *tm = &tls_main;
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "use-test-cert-in-ca"))
+       tm->use_test_cert_in_ca = 1;
+      else if (unformat (input, "ca-cert-path %s", &tm->ca_cert_path))
+       ;
+      else
+       return clib_error_return (0, "unknown input `%U'",
+                                 format_unformat_error, input);
+    }
+  return 0;
+}
+
+VLIB_EARLY_CONFIG_FUNCTION (tls_config_fn, "tls");
 /*
  * fd.io coding-style-patch-verification: ON
  *