Skip to contentSkip to conversation

Refactor key_state_export_keying_material functions

PATCH Superseded Arne Schwabe 4 participants 12 messages Aug 12, 2020 – Aug 24, 2020

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/3 Refactor key_state_export_keying_material functions

This refactors the common code between mbed SSL and OpenSSL into export_user_keying_material and also prepares the backend functions to export more than one key.

Also fix checking the return value of SSL_export_keying_material only 1 is a sucess, -1 is also an error.

Patch V2: Cache secrets for mbed TLS instead generating all ekms
in the call back function

---
 src/openvpn/ssl.c         | 36 ++++++++++++++++++-
 src/openvpn/ssl_backend.h | 16 +++++++--
 src/openvpn/ssl_mbedtls.c | 73 ++++++++++++++++++++-------------------
 src/openvpn/ssl_mbedtls.h | 12 +++++--
 src/openvpn/ssl_openssl.c | 43 +++++++++--------------
 5 files changed, 113 insertions(+), 67 deletions(-)
src/openvpn/ssl.c +35 -1
index f16114c2..3fcaa25f 100644
@@ -2412,6 +2412,40 @@ error:
     return false;
 }
 
+static void
+export_user_keying_material(struct key_state_ssl *ssl,
+                            struct tls_session *session)
+{
+    if (session->opt->ekm_size > 0)
+    {
+        unsigned int size = session->opt->ekm_size;
+        struct gc_arena gc = gc_new();
+
+        unsigned char *ekm;
+        if ((ekm = key_state_export_keying_material(session,
+                                                    session->opt->ekm_label,
+                                                    session->opt->ekm_label_size,
+                                                    session->opt->ekm_size,
+                                                    &gc)))
+        {
+            unsigned int len = (size * 2) + 2;
+
+            const char *key = format_hex_ex(ekm, size, len, 0, NULL, &gc);
+            setenv_str(session->opt->es, "exported_keying_material", key);
+
+            dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s",
+                 __func__, key);
+            secure_memzero(ekm, size);
+        }
+        else
+        {
+            msg(M_WARN, "WARNING: Export keying material failed!");
+            setenv_del(session->opt->es, "exported_keying_material");
+        }
+        gc_free(&gc);
+    }
+}
+
 /**
  * Handle reading key data, peer-info, username/password, OCC
  * from the TLS control channel (cleartext).
@@ -2541,7 +2575,7 @@ key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_sessio
     if ((ks->authenticated > KS_AUTH_FALSE)
         && plugin_defined(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL))
     {
-        key_state_export_keying_material(&ks->ks_ssl, session);
+        export_user_keying_material(&ks->ks_ssl, session);
 
         if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL, session->opt->es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
         {
src/openvpn/ssl_backend.h +13 -3
index 7f52ab1e..eb7d541d 100644
@@ -394,13 +394,23 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
  * derived from existing TLS channel. This exported keying material can then be
  * used for a variety of purposes.
  *
+ *
  * @param ks_ssl       The SSL channel's state info
  * @param session      The session associated with the given key_state
+ * @param label        The label to use when exporting the key
+ * @param label_size   The size of the label to use when exporting the key
+ *
+ * @param gc           gc_arena that might be used to allocate the string
+ *                     returned
+ * @returns            The exported key material, the caller may zero the
+ *                     string but should not free it
  */
 
-void
-key_state_export_keying_material(struct key_state_ssl *ks_ssl,
-                                 struct tls_session *session) __attribute__((nonnull));
+unsigned char*
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 size_t ekm_size,
+                                 struct gc_arena *gc) __attribute__((nonnull));
 
 /**************************************************************************/
 /** @addtogroup control_tls
src/openvpn/ssl_mbedtls.c +38 -35

96 lines not on this page · raw message

src/openvpn/ssl_mbedtls.h +10 -2
index 0525134f..17aae551 100644
@@ -82,6 +82,15 @@ struct external_context {
     void *sign_ctx;
 };
 
+/** struct to cache TLS secrets for keying material exporter (RFC 5705).
+ * The constants (64 and 48) are inherent to TLS version and
+ * the whole keying material export will likely change when they change */
+struct tls_key_cache {
+    unsigned char client_server_random[64];
+    mbedtls_tls_prf_types tls_prf_type;
+    unsigned char master_secret[48];
+};
+
 /**
  * Structure that wraps the TLS context. Contents differ depending on the
  * SSL library used.
@@ -114,8 +123,7 @@ struct key_state_ssl {
     mbedtls_ssl_context *ctx;           /**< mbedTLS connection context */
     bio_ctx *bio_ctx;
 
-    /** Keying material exporter cache (RFC 5705). */
-    uint8_t *exported_key_material;
+    struct tls_key_cache tls_key_cache;
 
 };
 
src/openvpn/ssl_openssl.c +17 -26

52 lines not on this page · raw message

Signature · 1 line
2.26.2
#1 lore raw

PATCH v2 2/3 Move openvpn specific key expansion into its own function

This moves the OpenVPN specific PRF into its own function also simplifies the code a bit by passing tls_session directly instead of 5 of its fields.

Patch V2: Rebase

---
 src/openvpn/ssl.c | 109 +++++++++++++++++++++++++++++-----------------
 1 file changed, 69 insertions(+), 40 deletions(-)
src/openvpn/ssl.c +69 -40
index 3fcaa25f..06cc4c0b 100644
@@ -1765,27 +1765,38 @@ openvpn_PRF(const uint8_t *secret,
     VALGRIND_MAKE_READABLE((void *)output, output_len);
 }
 
-/*
- * Using source entropy from local and remote hosts, mix into
- * master key.
- */
-static bool
-generate_key_expansion(struct key_ctx_bi *key,
-                       const struct key_type *key_type,
-                       const struct key_source2 *key_src,
-                       const struct session_id *client_sid,
-                       const struct session_id *server_sid,
-                       bool server)
+static void
+init_key_contexts(struct key_ctx_bi *key,
+                  const struct key_type *key_type,
+                  bool server,
+                  struct key2 *key2)
+{
+    /* Initialize OpenSSL key contexts */
+    int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
+    init_key_ctx_bi(key, key2, key_direction, key_type, "Data Channel");
+
+    /* Initialize implicit IVs */
+    key_ctx_update_implicit_iv(&key->encrypt, (*key2).keys[(int)server].hmac,
+                               MAX_HMAC_KEY_LENGTH);
+    key_ctx_update_implicit_iv(&key->decrypt, (*key2).keys[1-(int)server].hmac,
+                               MAX_HMAC_KEY_LENGTH);
+
+}
+
+
+static struct key2
+generate_key_expansion_oepnvpn_prf(const struct tls_session *session)
 {
+
     uint8_t master[48] = { 0 };
-    struct key2 key2 = { 0 };
-    bool ret = false;
 
-    if (key->initialized)
-    {
-        msg(D_TLS_ERRORS, "TLS Error: key already initialized");
-        goto exit;
-    }
+    const struct key_state *ks = &session->key[KS_PRIMARY];
+    const struct key_source2 *key_src = ks->key_src;
+
+    const struct session_id *client_sid = session->opt->server ?
+                                          &ks->session_id_remote : &session->session_id;
+    const struct session_id *server_sid = !session->opt->server ?
+                                          &ks->session_id_remote : &session->session_id;
 
     /* debugging print of source key material */
     key_source2_print(key_src);
@@ -1803,6 +1814,7 @@ generate_key_expansion(struct key_ctx_bi *key,
                 master,
                 sizeof(master));
 
+    struct key2 key2;
     /* compute key expansion */
     openvpn_PRF(master,
                 sizeof(master),
@@ -1815,41 +1827,62 @@ generate_key_expansion(struct key_ctx_bi *key,
                 server_sid,
                 (uint8_t *)key2.keys,
                 sizeof(key2.keys));
+    secure_memzero(&master, sizeof(master));
 
+    /* We use the DES fixup here so we can drop it once we
+     * drop DES support and non RFC5705 key derivation */
+    for (int i = 0; i < 2; ++i)
+    {
+        fixup_key(&key2.keys[i], &session->opt->key_type);
+    }
     key2.n = 2;
 
-    key2_print(&key2, key_type, "Master Encrypt", "Master Decrypt");
+    return key2;
+}
+
+/*
+ * Using source entropy from local and remote hosts, mix into
+ * master key.
+ */
+static bool
+generate_key_expansion(struct key_ctx_bi *key,
+                       const struct tls_session *session)
+{
+    bool ret = false;
+
+    if (key->initialized)
+    {
+        msg(D_TLS_ERRORS, "TLS Error: key already initialized");
+        goto exit;
+    }
+
+
+    bool server = session->opt->server;
+
+    struct key2 key2 = generate_key_expansion_oepnvpn_prf(session);
+
+    key2_print(&key2, &session->opt->key_type,
+               "Master Encrypt", "Master Decrypt");
 
     /* check for weak keys */
     for (int i = 0; i < 2; ++i)
     {
-        fixup_key(&key2.keys[i], key_type);
-        if (!check_key(&key2.keys[i], key_type))
+        if (!check_key(&key2.keys[i], &session->opt->key_type))
         {
             msg(D_TLS_ERRORS, "TLS Error: Bad dynamic key generated");
             goto exit;
         }
     }
-
-    /* Initialize OpenSSL key contexts */
-    int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
-    init_key_ctx_bi(key, &key2, key_direction, key_type, "Data Channel");
-
-    /* Initialize implicit IVs */
-    key_ctx_update_implicit_iv(&key->encrypt, key2.keys[(int)server].hmac,
-                               MAX_HMAC_KEY_LENGTH);
-    key_ctx_update_implicit_iv(&key->decrypt, key2.keys[1-(int)server].hmac,
-                               MAX_HMAC_KEY_LENGTH);
-
+    init_key_contexts(key, &session->opt->key_type, server, &key2);
     ret = true;
 
 exit:
-    secure_memzero(&master, sizeof(master));
     secure_memzero(&key2, sizeof(key2));
 
     return ret;
 }
 
+
 static void
 key_ctx_update_implicit_iv(struct key_ctx *ctx, uint8_t *key, size_t key_len)
 {
@@ -1879,10 +1912,7 @@ tls_session_generate_data_channel_keys(struct tls_session *session)
 {
     bool ret = false;
     struct key_state *ks = &session->key[KS_PRIMARY];   /* primary key */
-    const struct session_id *client_sid = session->opt->server ?
-                                          &ks->session_id_remote : &session->session_id;
-    const struct session_id *server_sid = !session->opt->server ?
-                                          &ks->session_id_remote : &session->session_id;
+
 
     if (ks->authenticated == KS_AUTH_FALSE)
     {
@@ -1891,9 +1921,8 @@ tls_session_generate_data_channel_keys(struct tls_session *session)
     }
 
     ks->crypto_options.flags = session->opt->crypto_flags;
-    if (!generate_key_expansion(&ks->crypto_options.key_ctx_bi,
-                                &session->opt->key_type, ks->key_src, client_sid, server_sid,
-                                session->opt->server))
+
+    if (!generate_key_expansion(&ks->crypto_options.key_ctx_bi, session))
     {
         msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
         goto cleanup;
Signature · 1 line
2.26.2
#3 lore raw

PATCH v2 3/3 Implement generating data channel keys via EKM/RFC 5705

In reply to Arne Schwabe

OpenVPN currently uses its own (based on TLS 1.0) key derivation mechansim to generate the 256 bytes key data in key2 struct that are then used used to generate encryption/hmac/iv vectors. While this mechanism is still secure, it is not state of the art.

Instead of modernisating our own approach, this commit implements key derivation using the Keying Material Exporters API introduced by RFC 5705.

We also use an opportunistic approach of negotiating the use of EKM (exported key material) through an IV_PROTO flag and prefer EKM to our own PRF if both client and server support it. The use of EKM is pushed to the client as part of NCP as key-derivation tls-ekm.

We still exchange the random data (112 bytes from client to server and 64 byte from server to client) that for the OpenVPN PRF but do not use it. Removing that exchange would break the handshake and make a key-method 3 or similar necessary.

Side note: this commit breaks the (not yet merged) WolfSSL support as it claims to support EKM in the OpenSSL compat API but always returns an error if you try to use it.

Patch V2: rebase/change to V2 of EKM refactoring

---
 Changes.rst                      | 11 +++++++
 doc/doxygen/doc_key_generation.h | 15 ++++++++--
 src/openvpn/crypto.h             |  4 +++
 src/openvpn/init.c               |  1 +
 src/openvpn/multi.c              |  4 +++
 src/openvpn/options.c            | 14 +++++++++
 src/openvpn/options.h            |  3 ++
 src/openvpn/push.c               |  5 +++-
 src/openvpn/ssl.c                | 50 ++++++++++++++++++++++++++++++--
 src/openvpn/ssl.h                |  2 ++
 src/openvpn/ssl_backend.h        |  2 ++
 src/openvpn/ssl_mbedtls.c        |  7 ++---
 12 files changed, 107 insertions(+), 11 deletions(-)
Changes.rst +11 -0
index bacc98cd..2c28a399 100644
@@ -1,3 +1,14 @@
+Overview of changes in 2.6
+==========================
+
+
+New features
+------------
+Keying Material Exporters (RFC 5705) based key generation
+    As part of the cipher negotiation OpenVPN will automatically prefer
+    the RFC5705 based key material generation to the current custom
+    OpenVPN PRF. This feature requires OpenSSL or mbed TLS 2.18+.
+
 Overview of changes in 2.5
 ==========================
 
doc/doxygen/doc_key_generation.h +13 -2
index 4bb9c708..bbd6c0c5 100644
@@ -58,6 +58,12 @@
  *
  * @subsection key_generation_method_2 Key method 2
  *
+ * There are two methods for generating key data when using key method 2
+ * the first is OpenVPN's traditional approach that exchanges random
+ * data and uses a PRF and the other is using the RFC5705 keying material
+ * exporter to generate the key material. For both methods the random
+ * data is exchange but only used in the traditional method.
+ *
  * -# The client generates random material in the following amounts:
  *    - Pre-master secret: 48 bytes
  *    - Client's PRF seed for master secret: 32 bytes
@@ -73,8 +79,13 @@
  *    server's random material.
  *
  * %Key method 2 %key expansion is performed by the \c
- * generate_key_expansion() function.  Please refer to its source code for
- * details of the %key expansion process.
+ * generate_key_expansion_oepnvpn_prf() function.  Please refer to its source
+ * code for details of the %key expansion process.
+ *
+ * When the client sends the IV_PROTO_TLS_KEY_EXPORT and the server replies
+ * with `key-derivation tls-ekm` RFC5705 key material exporter with the label
+ * EXPORTER-OpenVPN-datakeys is used for the key data.
+ *
  *
  * @subsection key_generation_random Source of random material
  *
src/openvpn/crypto.h +4 -0
index 999f643e..ec935ca5 100644
@@ -254,6 +254,10 @@ struct crypto_options
 #define CO_MUTE_REPLAY_WARNINGS (1<<2)
     /**< Bit-flag indicating not to display
      *   replay warnings. */
+#define CO_USE_TLS_KEY_MATERIAL_EXPORT  (1<<3)
+    /**< Bit-flag indicating that key derivation
+     * is done using TLS keying material export [RFC5705]
+     */
     unsigned int flags;         /**< Bit-flags determining behavior of
                                  *   security operation functions. */
 };
src/openvpn/init.c +1 -0
index dfa045b0..34a7313e 100644
@@ -676,6 +676,7 @@ restore_ncp_options(struct context *c)
     c->options.ciphername = c->c1.ciphername;
     c->options.authname = c->c1.authname;
     c->options.keysize = c->c1.keysize;
+    c->options.data_channel_use_ekm = false;
 }
 
 void
src/openvpn/multi.c +4 -0
index 13738180..a5862020 100644
@@ -1817,6 +1817,10 @@ multi_client_set_protocol_options(struct context *c)
         c->c2.push_request_received = true;
     }
 
+#ifdef HAVE_EXPORT_KEYING_MATERIAL
+    o->data_channel_use_ekm = (proto & IV_PROTO_TLS_KEY_EXPORT);
+#endif
+
     /* Select cipher if client supports Negotiable Crypto Parameters */
     if (!o->ncp_enabled)
     {
src/openvpn/options.c +14 -0
index 8bf82c57..90e78a7b 100644
@@ -7947,6 +7947,20 @@ add_option(struct options *options,
         }
         options->ncp_ciphers = p[1];
     }
+    else if (streq(p[0], "key-derivation") && p[1])
+    {
+        VERIFY_PERMISSION(OPT_P_NCP)
+#ifdef HAVE_EXPORT_KEYING_MATERIAL
+        if (streq(p[1], "tls-ekm"))
+        {
+            options->data_channel_use_ekm = true;
+        }
+        else
+#endif
+        {
+            msg(msglevel, "Unknown key-derivation method %s", p[1]);
+        }
+    }
     else if (streq(p[0], "ncp-disable") && !p[1])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INSTANCE);
src/openvpn/options.h +3 -0
index 877e9396..c730c6a7 100644
@@ -648,6 +648,9 @@ struct options
     /* Useful when packets sent by openvpn itself are not subject
      * to the routing tables that would move packets into the tunnel. */
     bool allow_recursive_routing;
+
+    /* Use RFC 5705 key export */
+    bool data_channel_use_ekm;
 };
 
 #define streq(x, y) (!strcmp((x), (y)))
src/openvpn/push.c +4 -1
index e0d2eeaf..17bba948 100644
@@ -479,7 +479,10 @@ prepare_push_reply(struct context *c, struct gc_arena *gc,
     {
         push_option_fmt(gc, push_list, M_USAGE, "cipher %s", o->ciphername);
     }
-
+    if (o->data_channel_use_ekm)
+    {
+        push_option_fmt(gc, push_list, M_USAGE, "key-derivation tls-ekm");
+    }
     return true;
 }
 
src/openvpn/ssl.c +47 -3

83 lines not on this page · raw message

src/openvpn/ssl.h +2 -0
index 005628f6..f00f8abd 100644
@@ -116,6 +116,8 @@
  * to wait for a push-request to send a push-reply */
 #define IV_PROTO_REQUEST_PUSH   (1<<2)
 
+/** Supports key derivation via TLS key material exporter [RFC5705] */
+#define IV_PROTO_TLS_KEY_EXPORT (1<<3)
 
 /* Default field in X509 to be username */
 #define X509_USERNAME_FIELD_DEFAULT "CN"
src/openvpn/ssl_backend.h +2 -0
index eb7d541d..2be32244 100644
@@ -389,6 +389,8 @@ void key_state_ssl_free(struct key_state_ssl *ks_ssl);
 void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
                                 const char *crl_file, bool crl_inline);
 
+#define EXPORT_KEY_DATA_LABEL       "EXPORTER-OpenVPN-datakeys"
+#define EXPORT_KEY_DATA_EKM_SIZE    (2 * (MAX_CIPHER_KEY_LENGTH + MAX_HMAC_KEY_LENGTH))
 /**
  * Keying Material Exporters [RFC 5705] allows additional keying material to be
  * derived from existing TLS channel. This exported keying material can then be
src/openvpn/ssl_mbedtls.c +2 -5
index 4287b59e..da19fe38 100644
@@ -1158,11 +1158,8 @@ key_state_ssl_init(struct key_state_ssl *ks_ssl,
 
 #ifdef HAVE_EXPORT_KEYING_MATERIAL
     /* Initialize keying material exporter */
-    if (session->opt->ekm_size)
-    {
-        mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config,
-                                            mbedtls_ssl_export_keys_cb, session);
-    }
+    mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config,
+                                        mbedtls_ssl_export_keys_cb, session);
 #endif
 
     /* Initialise SSL context */
Signature · 1 line
2.26.2
#5 lore raw
In reply to Arne Schwabe

typo

Quoted 6 lines · Arne Schwabe

This refactors the common code between mbed SSL and OpenSSL into export_user_keying_material and also prepares the backend functions to export more than one key.

Also fix checking the return value of SSL_export_keying_material only 1 is a sucess, -1 is also an error.

sucess -> success

#4 lore raw

Re: [Openvpn-devel] [PATCH v2 3/3] Implement generating data channel keys via EKM/RFC 5705

In reply to Arne Schwabe

typos/grammar

Quoted 2 lines · Arne Schwabe

OpenVPN currently uses its own (based on TLS 1.0) key derivation mechansim to generate the 256 bytes key data in key2 struct that

mechansim -> mechanism

Quoted 4 lines

are then used used to generate encryption/hmac/iv vectors. While this mechanism is still secure, it is not state of the art.

Instead of modernisating our own approach, this commit implements

modernisating - > modernising

Quoted 11 lines

key derivation using the Keying Material Exporters API introduced by RFC 5705.

We also use an opportunistic approach of negotiating the use of EKM (exported key material) through an IV_PROTO flag and prefer EKM to our own PRF if both client and server support it. The use of EKM is pushed to the client as part of NCP as key-derivation tls-ekm.

We still exchange the random data (112 bytes from client to server and 64 byte from server to client) that for the OpenVPN PRF but

client) that for - unnecessary 'that'

Quoted 63 lines

do not use it. Removing that exchange would break the handshake and make a key-method 3 or similar necessary.

Side note: this commit breaks the (not yet merged) WolfSSL support as it claims to support EKM in the OpenSSL compat API but always returns an error if you try to use it.

Patch V2: rebase/change to V2 of EKM refactoring

---
  Changes.rst                      | 11 +++++++
  doc/doxygen/doc_key_generation.h | 15 ++++++++--
  src/openvpn/crypto.h             |  4 +++
  src/openvpn/init.c               |  1 +
  src/openvpn/multi.c              |  4 +++
  src/openvpn/options.c            | 14 +++++++++
  src/openvpn/options.h            |  3 ++
  src/openvpn/push.c               |  5 +++-
  src/openvpn/ssl.c                | 50 ++++++++++++++++++++++++++++++--
  src/openvpn/ssl.h                |  2 ++
  src/openvpn/ssl_backend.h        |  2 ++
  src/openvpn/ssl_mbedtls.c        |  7 ++---
  12 files changed, 107 insertions(+), 11 deletions(-)
Changes.rst +11 -0
index bacc98cd..2c28a399 100644
@@ -1,3 +1,14 @@
+Overview of changes in 2.6
+==========================
+
+
+New features
+------------
+Keying Material Exporters (RFC 5705) based key generation
+    As part of the cipher negotiation OpenVPN will automatically prefer
+    the RFC5705 based key material generation to the current custom
+    OpenVPN PRF. This feature requires OpenSSL or mbed TLS 2.18+.
+
  Overview of changes in 2.5
  ==========================
 
doc/doxygen/doc_key_generation.h +6 -0
index 4bb9c708..bbd6c0c5 100644
@@ -58,6 +58,12 @@
   *
   * @subsection key_generation_method_2 Key method 2
   *
+ * There are two methods for generating key data when using key method 2
+ * the first is OpenVPN's traditional approach that exchanges random
+ * data and uses a PRF and the other is using the RFC5705 keying material
+ * exporter to generate the key material. For both methods the random
+ * data is exchange but only used in the traditional method.
+ *
   * -# The client generates random material in the following amounts:
   *    - Pre-master secret: 48 bytes
   *    - Client's PRF seed for master secret: 32 bytes
@@ -73,8 +79,13 @@
   *    server's random material.

doc/doxygen/doc_key_generation.h line 87

Quoted 10 lines
doc/doxygen/doc_key_generation.h +6 -2
   *
   * %Key method 2 %key expansion is performed by the \c
- * generate_key_expansion() function.  Please refer to its source code for
- * details of the %key expansion process.
+ * generate_key_expansion_oepnvpn_prf() function.  Please refer to its source
+ * code for details of the %key expansion process.
+ *
+ * When the client sends the IV_PROTO_TLS_KEY_EXPORT and the server replies
+ * with `key-derivation tls-ekm` RFC5705 key material exporter with the label
+ * EXPORTER-OpenVPN-datakeys is used for the key data.

Grammar: split the sentence by a 'then'.

Quoted 3 lines
doc/doxygen/doc_key_generation.h +3 -0
+ * When the client sends the IV_PROTO_TLS_KEY_EXPORT and the server replies
+ * with `key-derivation tls-ekm` then RFC5705 key material exporter with the label
+ * EXPORTER-OpenVPN-datakeys is used for the key data.
#6 lore raw
In reply to Arne Schwabe

Hi,

Quoted 20 lines · Arne Schwabe

This refactors the common code between mbed SSL and OpenSSL into export_user_keying_material and also prepares the backend functions to export more than one key.

Also fix checking the return value of SSL_export_keying_material only 1 is a sucess, -1 is also an error.

Patch V2: Cache secrets for mbed TLS instead generating all ekms
in the call back function

---

[...]

src/openvpn/ssl_backend.h void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, · line 397

Quoted 4 lines
src/openvpn/ssl_backend.h +1 -0
@@ -394,13 +394,23 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
  * derived from existing TLS channel. This exported keying material can then be
  * used for a variety of purposes.
  *
+ *

This extra newline seems unneeded.

Quoted 9 lines
src/openvpn/ssl_backend.h +7 -0
  * @param ks_ssl       The SSL channel's state info
  * @param session      The session associated with the given key_state
+ * @param label        The label to use when exporting the key
+ * @param label_size   The size of the label to use when exporting the key
+ *
+ * @param gc           gc_arena that might be used to allocate the string
+ *                     returned
+ * @returns            The exported key material, the caller may zero the
+ *                     string but should not free it

src/openvpn/ssl_backend.h void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, · line 413

Quoted 10 lines
src/openvpn/ssl_backend.h +5 -3
  */
 
-void
-key_state_export_keying_material(struct key_state_ssl *ks_ssl,
-                                 struct tls_session *session) __attribute__((nonnull));
+unsigned char*
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 size_t ekm_size,
+                                 struct gc_arena *gc) __attribute__((nonnull));

(Quoting a former colleague:) comment is a lie! It does not match the actual function prototype.

All the code itself looks good to me. I *think* it could be made slightly better even, but these changes make sense for the intended goal, and look correct.

Tested both openssl and mbedtls builds (with -fsanitize=address), and verified that this indeed produces the same exported values for both builds and a build without this patch.

-Steffan

#7 lore raw

PATCH v3 1/3 Refactor key_state_export_keying_material functions

This refactors the common code between mbed SSL and OpenSSL into export_user_keying_material and also prepares the backend functions to export more than one key.

Also fix checking the return value of SSL_export_keying_material only 1 is a sucess, -1 is also an error.

Patch V2: Cache secrets for mbed TLS instead generating all ekms
in the call back function

Patch V3: comment is no longer a lie. (fixed doxygen)

---
 src/openvpn/ssl.c         | 36 ++++++++++++++++++-
 src/openvpn/ssl_backend.h | 20 +++++++----
 src/openvpn/ssl_mbedtls.c | 73 ++++++++++++++++++++-------------------
 src/openvpn/ssl_mbedtls.h | 12 +++++--
 src/openvpn/ssl_openssl.c | 43 +++++++++--------------
 5 files changed, 114 insertions(+), 70 deletions(-)
src/openvpn/ssl.c +35 -1
index f16114c2..3fcaa25f 100644
@@ -2412,6 +2412,40 @@ error:
     return false;
 }
 
+static void
+export_user_keying_material(struct key_state_ssl *ssl,
+                            struct tls_session *session)
+{
+    if (session->opt->ekm_size > 0)
+    {
+        unsigned int size = session->opt->ekm_size;
+        struct gc_arena gc = gc_new();
+
+        unsigned char *ekm;
+        if ((ekm = key_state_export_keying_material(session,
+                                                    session->opt->ekm_label,
+                                                    session->opt->ekm_label_size,
+                                                    session->opt->ekm_size,
+                                                    &gc)))
+        {
+            unsigned int len = (size * 2) + 2;
+
+            const char *key = format_hex_ex(ekm, size, len, 0, NULL, &gc);
+            setenv_str(session->opt->es, "exported_keying_material", key);
+
+            dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s",
+                 __func__, key);
+            secure_memzero(ekm, size);
+        }
+        else
+        {
+            msg(M_WARN, "WARNING: Export keying material failed!");
+            setenv_del(session->opt->es, "exported_keying_material");
+        }
+        gc_free(&gc);
+    }
+}
+
 /**
  * Handle reading key data, peer-info, username/password, OCC
  * from the TLS control channel (cleartext).
@@ -2541,7 +2575,7 @@ key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_sessio
     if ((ks->authenticated > KS_AUTH_FALSE)
         && plugin_defined(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL))
     {
-        key_state_export_keying_material(&ks->ks_ssl, session);
+        export_user_keying_material(&ks->ks_ssl, session);
 
         if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL, session->opt->es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
         {
src/openvpn/ssl_backend.h +14 -6
index 7f52ab1e..cf9fba25 100644
@@ -394,13 +394,21 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
  * derived from existing TLS channel. This exported keying material can then be
  * used for a variety of purposes.
  *
- * @param ks_ssl       The SSL channel's state info
  * @param session      The session associated with the given key_state
- */
-
-void
-key_state_export_keying_material(struct key_state_ssl *ks_ssl,
-                                 struct tls_session *session) __attribute__((nonnull));
+ * @param label        The label to use when exporting the key
+ * @param label_size   The size of the label to use when exporting the key
+ * @param ekm_size     THe size of the exported/returned key material
+ * @param gc           gc_arena that might be used to allocate the string
+ *                     returned
+ * @returns            The exported key material, the caller may zero the
+ *                     string but should not free it
+ */
+
+unsigned char*
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 size_t ekm_size,
+                                 struct gc_arena *gc) __attribute__((nonnull));
 
 /**************************************************************************/
 /** @addtogroup control_tls
src/openvpn/ssl_mbedtls.c +38 -35

96 lines not on this page · raw message

src/openvpn/ssl_mbedtls.h +10 -2
index 0525134f..17aae551 100644
@@ -82,6 +82,15 @@ struct external_context {
     void *sign_ctx;
 };
 
+/** struct to cache TLS secrets for keying material exporter (RFC 5705).
+ * The constants (64 and 48) are inherent to TLS version and
+ * the whole keying material export will likely change when they change */
+struct tls_key_cache {
+    unsigned char client_server_random[64];
+    mbedtls_tls_prf_types tls_prf_type;
+    unsigned char master_secret[48];
+};
+
 /**
  * Structure that wraps the TLS context. Contents differ depending on the
  * SSL library used.
@@ -114,8 +123,7 @@ struct key_state_ssl {
     mbedtls_ssl_context *ctx;           /**< mbedTLS connection context */
     bio_ctx *bio_ctx;
 
-    /** Keying material exporter cache (RFC 5705). */
-    uint8_t *exported_key_material;
+    struct tls_key_cache tls_key_cache;
 
 };
 
src/openvpn/ssl_openssl.c +17 -26

52 lines not on this page · raw message

Signature · 1 line
2.26.2
#11 lore raw

PATCH v3 3/3 Implement generating data channel keys via EKM/RFC 5705

In reply to Arne Schwabe

OpenVPN currently uses its own (based on TLS 1.0) key derivation mechanism to generate the 256 bytes key data in key2 struct that are then used used to generate encryption/hmac/iv vectors. While this mechanism is still secure, it is not state of the art.

Instead of modernising our own approach, this commit implements key derivation using the Keying Material Exporters API introduced by RFC 5705.

We also use an opportunistic approach of negotiating the use of EKM (exported key material) through an IV_PROTO flag and prefer EKM to our own PRF if both client and server support it. The use of EKM is pushed to the client as part of NCP as key-derivation tls-ekm.

We still exchange the random data (112 bytes from client to server and 64 byte from server to client) for the OpenVPN PRF but do not use it. Removing that exchange would break the handshake and make a key-method 3 or similar necessary.

As a side effect, this makes a little bit easier to have a FIPS compatible version of OpenVPN since we do not rely on calling MD5 anymore.

Side note: this commit breaks the (not yet merged) WolfSSL support as it claims to support EKM in the OpenSSL compat API but always returns an error if you try to use it.

Patch V2: rebase/change to V2 of EKM refactoring

Patch V3: add Changes.rst

---
 Changes.rst                      | 11 +++++++
 doc/doxygen/doc_key_generation.h | 14 ++++++--
 src/openvpn/crypto.h             |  4 +++
 src/openvpn/init.c               |  1 +
 src/openvpn/multi.c              |  4 +++
 src/openvpn/options.c            | 14 ++++++++
 src/openvpn/options.h            |  3 ++
 src/openvpn/push.c               |  5 ++-
 src/openvpn/ssl.c                | 55 +++++++++++++++++++++++++++++---
 src/openvpn/ssl.h                |  2 ++
 src/openvpn/ssl_backend.h        |  2 ++
 src/openvpn/ssl_mbedtls.c        |  7 ++--
 12 files changed, 109 insertions(+), 13 deletions(-)
Changes.rst +11 -0
index 0aee3603..4c652315 100644
@@ -1,3 +1,14 @@
+Overview of changes in 2.6
+==========================
+
+
+New features
+------------
+Keying Material Exporters (RFC 5705) based key generation
+    As part of the cipher negotiation OpenVPN will automatically prefer
+    the RFC5705 based key material generation to the current custom
+    OpenVPN PRF. This feature requires OpenSSL or mbed TLS 2.18+.
+
 Overview of changes in 2.5
 ==========================
 
doc/doxygen/doc_key_generation.h +12 -2
index 4bb9c708..cef773a9 100644
@@ -58,6 +58,12 @@
  *
  * @subsection key_generation_method_2 Key method 2
  *
+ * There are two methods for generating key data when using key method 2
+ * the first is OpenVPN's traditional approach that exchanges random
+ * data and uses a PRF and the other is using the RFC5705 keying material
+ * exporter to generate the key material. For both methods the random
+ * data is exchange but only used in the traditional method.
+ *
  * -# The client generates random material in the following amounts:
  *    - Pre-master secret: 48 bytes
  *    - Client's PRF seed for master secret: 32 bytes
@@ -73,8 +79,12 @@
  *    server's random material.
  *
  * %Key method 2 %key expansion is performed by the \c
- * generate_key_expansion() function.  Please refer to its source code for
- * details of the %key expansion process.
+ * generate_key_expansion_oepnvpn_prf() function.  Please refer to its source
+ * code for details of the %key expansion process.
+ *
+ * When the client sends the IV_PROTO_TLS_KEY_EXPORT flag and the server replies
+ * with `key-derivation tls-ekm` the RFC5705 key material exporter with the
+ * label EXPORTER-OpenVPN-datakeys is used for the key data.
  *
  * @subsection key_generation_random Source of random material
  *
src/openvpn/crypto.h +4 -0
index 999f643e..ec935ca5 100644
@@ -254,6 +254,10 @@ struct crypto_options
 #define CO_MUTE_REPLAY_WARNINGS (1<<2)
     /**< Bit-flag indicating not to display
      *   replay warnings. */
+#define CO_USE_TLS_KEY_MATERIAL_EXPORT  (1<<3)
+    /**< Bit-flag indicating that key derivation
+     * is done using TLS keying material export [RFC5705]
+     */
     unsigned int flags;         /**< Bit-flags determining behavior of
                                  *   security operation functions. */
 };
src/openvpn/init.c +1 -0
index dfa045b0..34a7313e 100644
@@ -676,6 +676,7 @@ restore_ncp_options(struct context *c)
     c->options.ciphername = c->c1.ciphername;
     c->options.authname = c->c1.authname;
     c->options.keysize = c->c1.keysize;
+    c->options.data_channel_use_ekm = false;
 }
 
 void
src/openvpn/multi.c +4 -0
index 13738180..a5862020 100644
@@ -1817,6 +1817,10 @@ multi_client_set_protocol_options(struct context *c)
         c->c2.push_request_received = true;
     }
 
+#ifdef HAVE_EXPORT_KEYING_MATERIAL
+    o->data_channel_use_ekm = (proto & IV_PROTO_TLS_KEY_EXPORT);
+#endif
+
     /* Select cipher if client supports Negotiable Crypto Parameters */
     if (!o->ncp_enabled)
     {
src/openvpn/options.c +14 -0
index 8bf82c57..90e78a7b 100644
@@ -7947,6 +7947,20 @@ add_option(struct options *options,
         }
         options->ncp_ciphers = p[1];
     }
+    else if (streq(p[0], "key-derivation") && p[1])
+    {
+        VERIFY_PERMISSION(OPT_P_NCP)
+#ifdef HAVE_EXPORT_KEYING_MATERIAL
+        if (streq(p[1], "tls-ekm"))
+        {
+            options->data_channel_use_ekm = true;
+        }
+        else
+#endif
+        {
+            msg(msglevel, "Unknown key-derivation method %s", p[1]);
+        }
+    }
     else if (streq(p[0], "ncp-disable") && !p[1])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INSTANCE);
src/openvpn/options.h +3 -0
index 877e9396..c730c6a7 100644
@@ -648,6 +648,9 @@ struct options
     /* Useful when packets sent by openvpn itself are not subject
      * to the routing tables that would move packets into the tunnel. */
     bool allow_recursive_routing;
+
+    /* Use RFC 5705 key export */
+    bool data_channel_use_ekm;
 };
 
 #define streq(x, y) (!strcmp((x), (y)))
src/openvpn/push.c +4 -1
index e0d2eeaf..17bba948 100644
@@ -479,7 +479,10 @@ prepare_push_reply(struct context *c, struct gc_arena *gc,
     {
         push_option_fmt(gc, push_list, M_USAGE, "cipher %s", o->ciphername);
     }
-
+    if (o->data_channel_use_ekm)
+    {
+        push_option_fmt(gc, push_list, M_USAGE, "key-derivation tls-ekm");
+    }
     return true;
 }
 
src/openvpn/ssl.c +50 -5

97 lines not on this page · raw message

src/openvpn/ssl.h +2 -0
index 005628f6..f00f8abd 100644
@@ -116,6 +116,8 @@
  * to wait for a push-request to send a push-reply */
 #define IV_PROTO_REQUEST_PUSH   (1<<2)
 
+/** Supports key derivation via TLS key material exporter [RFC5705] */
+#define IV_PROTO_TLS_KEY_EXPORT (1<<3)
 
 /* Default field in X509 to be username */
 #define X509_USERNAME_FIELD_DEFAULT "CN"
src/openvpn/ssl_backend.h +2 -0
index cf9fba25..06ced86a 100644
@@ -389,6 +389,8 @@ void key_state_ssl_free(struct key_state_ssl *ks_ssl);
 void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
                                 const char *crl_file, bool crl_inline);
 
+#define EXPORT_KEY_DATA_LABEL       "EXPORTER-OpenVPN-datakeys"
+#define EXPORT_KEY_DATA_EKM_SIZE    (2 * (MAX_CIPHER_KEY_LENGTH + MAX_HMAC_KEY_LENGTH))
 /**
  * Keying Material Exporters [RFC 5705] allows additional keying material to be
  * derived from existing TLS channel. This exported keying material can then be
src/openvpn/ssl_mbedtls.c +2 -5
index 4287b59e..da19fe38 100644
@@ -1158,11 +1158,8 @@ key_state_ssl_init(struct key_state_ssl *ks_ssl,
 
 #ifdef HAVE_EXPORT_KEYING_MATERIAL
     /* Initialize keying material exporter */
-    if (session->opt->ekm_size)
-    {
-        mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config,
-                                            mbedtls_ssl_export_keys_cb, session);
-    }
+    mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config,
+                                        mbedtls_ssl_export_keys_cb, session);
 #endif
 
     /* Initialise SSL context */
Signature · 1 line
2.26.2
Acked-by on v3 1/3
#8 lore raw
In reply to Arne Schwabe

Hi,

Quoted 289 lines · Arne Schwabe

This refactors the common code between mbed SSL and OpenSSL into export_user_keying_material and also prepares the backend functions to export more than one key.

Also fix checking the return value of SSL_export_keying_material only 1 is a sucess, -1 is also an error.

Patch V2: Cache secrets for mbed TLS instead generating all ekms
in the call back function

Patch V3: comment is no longer a lie. (fixed doxygen)

---
 src/openvpn/ssl.c         | 36 ++++++++++++++++++-
 src/openvpn/ssl_backend.h | 20 +++++++----
 src/openvpn/ssl_mbedtls.c | 73 ++++++++++++++++++++-------------------
 src/openvpn/ssl_mbedtls.h | 12 +++++--
 src/openvpn/ssl_openssl.c | 43 +++++++++--------------
 5 files changed, 114 insertions(+), 70 deletions(-)
src/openvpn/ssl.c +35 -1
index f16114c2..3fcaa25f 100644
@@ -2412,6 +2412,40 @@ error:
     return false;
 }
 
+static void
+export_user_keying_material(struct key_state_ssl *ssl,
+                            struct tls_session *session)
+{
+    if (session->opt->ekm_size > 0)
+    {
+        unsigned int size = session->opt->ekm_size;
+        struct gc_arena gc = gc_new();
+
+        unsigned char *ekm;
+        if ((ekm = key_state_export_keying_material(session,
+                                                    session->opt->ekm_label,
+                                                    session->opt->ekm_label_size,
+                                                    session->opt->ekm_size,
+                                                    &gc)))
+        {
+            unsigned int len = (size * 2) + 2;
+
+            const char *key = format_hex_ex(ekm, size, len, 0, NULL, &gc);
+            setenv_str(session->opt->es, "exported_keying_material", key);
+
+            dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s",
+                 __func__, key);
+            secure_memzero(ekm, size);
+        }
+        else
+        {
+            msg(M_WARN, "WARNING: Export keying material failed!");
+            setenv_del(session->opt->es, "exported_keying_material");
+        }
+        gc_free(&gc);
+    }
+}
+
 /**
  * Handle reading key data, peer-info, username/password, OCC
  * from the TLS control channel (cleartext).
@@ -2541,7 +2575,7 @@ key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_sessio
     if ((ks->authenticated > KS_AUTH_FALSE)
         && plugin_defined(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL))
     {
-        key_state_export_keying_material(&ks->ks_ssl, session);
+        export_user_keying_material(&ks->ks_ssl, session);
 
         if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL, session->opt->es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
         {
src/openvpn/ssl_backend.h +14 -6
index 7f52ab1e..cf9fba25 100644
@@ -394,13 +394,21 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
  * derived from existing TLS channel. This exported keying material can then be
  * used for a variety of purposes.
  *
- * @param ks_ssl       The SSL channel's state info
  * @param session      The session associated with the given key_state
- */
-
-void
-key_state_export_keying_material(struct key_state_ssl *ks_ssl,
-                                 struct tls_session *session) __attribute__((nonnull));
+ * @param label        The label to use when exporting the key
+ * @param label_size   The size of the label to use when exporting the key
+ * @param ekm_size     THe size of the exported/returned key material
+ * @param gc           gc_arena that might be used to allocate the string
+ *                     returned
+ * @returns            The exported key material, the caller may zero the
+ *                     string but should not free it
+ */
+
+unsigned char*
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 size_t ekm_size,
+                                 struct gc_arena *gc) __attribute__((nonnull));
 
 /**************************************************************************/
 /** @addtogroup control_tls
src/openvpn/ssl_mbedtls.c +38 -35
index 9c874788..4287b59e 100644
@@ -206,51 +206,54 @@ mbedtls_ssl_export_keys_cb(void *p_expkey, const unsigned char *ms,
 {
     struct tls_session *session = p_expkey;
     struct key_state_ssl *ks_ssl = &session->key[KS_PRIMARY].ks_ssl;
-    unsigned char client_server_random[64];
+    struct tls_key_cache *cache = &ks_ssl->tls_key_cache;
 
-    ks_ssl->exported_key_material = gc_malloc(session->opt->ekm_size,
-                                              true, NULL);
+    static_assert(sizeof(ks_ssl->ctx->session->master)
+                    == sizeof(cache->master_secret), "master size mismatch");
 
-    memcpy(client_server_random, client_random, 32);
-    memcpy(client_server_random + 32, server_random, 32);
+    memcpy(cache->client_server_random, client_random, 32);
+    memcpy(cache->client_server_random + 32, server_random, 32);
+    memcpy(cache->master_secret, ms, sizeof(cache->master_secret));
+    cache->tls_prf_type = tls_prf_type;
 
-    const size_t ms_len = sizeof(ks_ssl->ctx->session->master);
-    int ret = mbedtls_ssl_tls_prf(tls_prf_type, ms, ms_len,
-                                  session->opt->ekm_label, client_server_random,
-                                  sizeof(client_server_random), ks_ssl->exported_key_material,
-                                  session->opt->ekm_size);
-
-    if (!mbed_ok(ret))
-    {
-        secure_memzero(ks_ssl->exported_key_material, session->opt->ekm_size);
-    }
-
-    secure_memzero(client_server_random, sizeof(client_server_random));
-
-    return ret;
+    return true;
 }
-#endif /* HAVE_EXPORT_KEYING_MATERIAL */
 
-void
-key_state_export_keying_material(struct key_state_ssl *ssl,
-                                 struct tls_session *session)
+unsigned char *
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 size_t ekm_size,
+                                 struct gc_arena *gc)
 {
-    if (ssl->exported_key_material)
+    ASSERT(strlen(label) == label_size);
+
+    struct tls_key_cache *cache = &session->key[KS_PRIMARY].ks_ssl.tls_key_cache;
+
+    /* If the type is NONE, we either have no cached secrets or
+     * there is no PRF, in both cases we cannot generate key material */
+    if (cache->tls_prf_type == MBEDTLS_SSL_TLS_PRF_NONE)
     {
-        unsigned int size = session->opt->ekm_size;
-        struct gc_arena gc = gc_new();
-        unsigned int len = (size * 2) + 2;
+        return NULL;
+    }
 
-        const char *key = format_hex_ex(ssl->exported_key_material,
-                                        size, len, 0, NULL, &gc);
-        setenv_str(session->opt->es, "exported_keying_material", key);
+    unsigned char *ekm = (unsigned char *) gc_malloc(ekm_size, true, gc);
+    int ret = mbedtls_ssl_tls_prf(cache->tls_prf_type, cache->master_secret,
+                                  sizeof(cache->master_secret),
+                                  label, cache->client_server_random,
+                                  sizeof(cache->client_server_random),
+                                  ekm, ekm_size);
 
-        dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s",
-             __func__, key);
-        gc_free(&gc);
+    if (mbed_ok(ret))
+    {
+        return ekm;
+    }
+    else
+    {
+        secure_memzero(ekm, session->opt->ekm_size);
+        return  NULL;
     }
 }
-
+#endif /* HAVE_EXPORT_KEYING_MATERIAL */
 
 bool
 tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
@@ -1178,7 +1181,7 @@ key_state_ssl_free(struct key_state_ssl *ks_ssl)
 {
     if (ks_ssl)
     {
-        free(ks_ssl->exported_key_material);
+        CLEAR(ks_ssl->tls_key_cache);
 
         if (ks_ssl->ctx)
         {
src/openvpn/ssl_mbedtls.h +10 -2
index 0525134f..17aae551 100644
@@ -82,6 +82,15 @@ struct external_context {
     void *sign_ctx;
 };
 
+/** struct to cache TLS secrets for keying material exporter (RFC 5705).
+ * The constants (64 and 48) are inherent to TLS version and
+ * the whole keying material export will likely change when they change */
+struct tls_key_cache {
+    unsigned char client_server_random[64];
+    mbedtls_tls_prf_types tls_prf_type;
+    unsigned char master_secret[48];
+};
+
 /**
  * Structure that wraps the TLS context. Contents differ depending on the
  * SSL library used.
@@ -114,8 +123,7 @@ struct key_state_ssl {
     mbedtls_ssl_context *ctx;           /**< mbedTLS connection context */
     bio_ctx *bio_ctx;
 
-    /** Keying material exporter cache (RFC 5705). */
-    uint8_t *exported_key_material;
+    struct tls_key_cache tls_key_cache;
 
 };
 
src/openvpn/ssl_openssl.c +10 -26
index 5ba74402..f52c7c39 100644
@@ -158,35 +158,26 @@ tls_ctx_initialised(struct tls_root_ctx *ctx)
     return NULL != ctx->ctx;
 }
 
-void
-key_state_export_keying_material(struct key_state_ssl *ssl,
-                                 struct tls_session *session)
-{
-    if (session->opt->ekm_size > 0)
-    {
-        unsigned int size = session->opt->ekm_size;
-        struct gc_arena gc = gc_new();
-        unsigned char *ekm = (unsigned char *) gc_malloc(size, true, &gc);
+unsigned char*
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 size_t ekm_size,
+                                 struct gc_arena *gc)
 
-        if (SSL_export_keying_material(ssl->ssl, ekm, size,
-                                       session->opt->ekm_label,
-                                       session->opt->ekm_label_size,
-                                       NULL, 0, 0))
-        {
-            unsigned int len = (size * 2) + 2;
+{
+    unsigned char *ekm = (unsigned char *) gc_malloc(ekm_size, true, gc);
 
-            const char *key = format_hex_ex(ekm, size, len, 0, NULL, &gc);
-            setenv_str(session->opt->es, "exported_keying_material", key);
+    SSL* ssl = session->key[KS_PRIMARY].ks_ssl.ssl;
 
-            dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s",
-                 __func__, key);
-        }
-        else
-        {
-            msg(M_WARN, "WARNING: Export keying material failed!");
-            setenv_del(session->opt->es, "exported_keying_material");
-        }
-        gc_free(&gc);
+    if (SSL_export_keying_material(ssl, ekm, ekm_size, label,
+                                   label_size, NULL, 0, 0) == 1)

src/openvpn/ssl_openssl.c tls_ctx_initialised(struct tls_root_ctx *ctx) · line 183

Quoted 10 lines
src/openvpn/ssl_openssl.c +7 -0
+    {
+        return ekm;
+    }
+    else
+    {
+        secure_memzero(ekm, ekm_size);
+        return NULL;
     }
 }
 

Thanks, looks good to me now. Changes wrt v2 in comments and whitespace only, so didn't re-test.

-Steffan

#2 lore raw

Re: [Openvpn-devel] [PATCH v2 2/3] Move openvpn specific key expansion into its own function

In reply to Arne Schwabe

Hi,

Quoted 3 lines · Arne Schwabe

This moves the OpenVPN specific PRF into its own function also simplifies the code a bit by passing tls_session directly instead of 5 of its fields.

Moves in the right direction. Some comments though:

Quoted 23 lines

Patch V2: Rebase

---
 src/openvpn/ssl.c | 109 +++++++++++++++++++++++++++++-----------------
 1 file changed, 69 insertions(+), 40 deletions(-)
src/openvpn/ssl.c +0 -8
index 3fcaa25f..06cc4c0b 100644
@@ -1765,27 +1765,38 @@ openvpn_PRF(const uint8_t *secret,
     VALGRIND_MAKE_READABLE((void *)output, output_len);
 }
 
-/*
- * Using source entropy from local and remote hosts, mix into
- * master key.
- */
-static bool
-generate_key_expansion(struct key_ctx_bi *key,
-                       const struct key_type *key_type,
-                       const struct key_source2 *key_src,

src/openvpn/ssl.c openvpn_PRF(const uint8_t *secret, · line 1774

Quoted 10 lines
src/openvpn/ssl.c +7 -3
-                       const struct session_id *client_sid,
-                       const struct session_id *server_sid,
-                       bool server)
+static void
+init_key_contexts(struct key_ctx_bi *key,
+                  const struct key_type *key_type,
+                  bool server,
+                  struct key2 *key2)
+{
+    /* Initialize OpenSSL key contexts */

Since you're touching this, can you remove "OpenSSL" from this comment. It's a lie! Sometimes.

Quoted 4 lines
src/openvpn/ssl.c +4 -0
+    int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
+    init_key_ctx_bi(key, key2, key_direction, key_type, "Data Channel");
+
+    /* Initialize implicit IVs */

src/openvpn/ssl.c openvpn_PRF(const uint8_t *secret, · line 1788

Quoted 10 lines
src/openvpn/ssl.c +10 -0
+    key_ctx_update_implicit_iv(&key->encrypt, (*key2).keys[(int)server].hmac,
+                               MAX_HMAC_KEY_LENGTH);
+    key_ctx_update_implicit_iv(&key->decrypt, (*key2).keys[1-(int)server].hmac,
+                               MAX_HMAC_KEY_LENGTH);
+
+}
+
+
+static struct key2
+generate_key_expansion_oepnvpn_prf(const struct tls_session *session)

What is this oepnvpn you're talking about?

src/openvpn/ssl.c openvpn_PRF(const uint8_t *secret, · line 1790

Quoted 2 lines
src/openvpn/ssl.c +1 -0
 {
+

Unneeded newline.

Quoted 29 lines
src/openvpn/ssl.c +8 -7
     uint8_t master[48] = { 0 };
-    struct key2 key2 = { 0 };
-    bool ret = false;
 
-    if (key->initialized)
-    {
-        msg(D_TLS_ERRORS, "TLS Error: key already initialized");
-        goto exit;
-    }
+    const struct key_state *ks = &session->key[KS_PRIMARY];
+    const struct key_source2 *key_src = ks->key_src;
+
+    const struct session_id *client_sid = session->opt->server ?
+                                          &ks->session_id_remote : &session->session_id;
+    const struct session_id *server_sid = !session->opt->server ?
+                                          &ks->session_id_remote : &session->session_id;
 
     /* debugging print of source key material */
     key_source2_print(key_src);
@@ -1803,6 +1814,7 @@ generate_key_expansion(struct key_ctx_bi *key,
                 master,
                 sizeof(master));
 
+    struct key2 key2;
     /* compute key expansion */
     openvpn_PRF(master,
                 sizeof(master),
@@ -1815,41 +1827,62 @@ generate_key_expansion(struct key_ctx_bi *key,
                 server_sid,

src/openvpn/ssl.c generate_key_expansion(struct key_ctx_bi *key, · line 1837

Quoted 10 lines
src/openvpn/ssl.c +7 -0
                 (uint8_t *)key2.keys,
                 sizeof(key2.keys));
+    secure_memzero(&master, sizeof(master));
 
+    /* We use the DES fixup here so we can drop it once we
+     * drop DES support and non RFC5705 key derivation */
+    for (int i = 0; i < 2; ++i)
+    {
+        fixup_key(&key2.keys[i], &session->opt->key_type);
+    }

Very nice that we can finally get rid of this. But I'm wondering now:
should we forbid DES (or maybe even any small block cipher) when using EKM?

Even if we remove small block cipher support completely from 2.6, I'd still really like to backport EKM to 2.5 ("long-term compat"). At that will still allow persistent users to force it to use DES.

Quoted 16 lines
src/openvpn/ssl.c +13 -1
     key2.n = 2;
 
-    key2_print(&key2, key_type, "Master Encrypt", "Master Decrypt");
+    return key2;
+}
+
+/*
+ * Using source entropy from local and remote hosts, mix into
+ * master key.
+ */
+static bool
+generate_key_expansion(struct key_ctx_bi *key,
+                       const struct tls_session *session)
+{
+    bool ret = false;
+

src/openvpn/ssl.c generate_key_expansion(struct key_ctx_bi *key, · line 1862

Quoted 10 lines
src/openvpn/ssl.c +10 -0
+    if (key->initialized)
+    {
+        msg(D_TLS_ERRORS, "TLS Error: key already initialized");
+        goto exit;
+    }
+
+
+    bool server = session->opt->server;
+
+    struct key2 key2 = generate_key_expansion_oepnvpn_prf(session);

Possible use-before-initialization/declaration here (undefined behavior).

key2 is used in the exit: label, so it should not be declared after the "goto exit" above. This is type of mistake is the reason I don't like late-declaration of any variable in functions that use a goto-error flow. Next to not-too-smart static analyzers complaining about this construct even if not used behind the label.

Quoted 55 lines
src/openvpn/ssl.c +7 -18
+
+    key2_print(&key2, &session->opt->key_type,
+               "Master Encrypt", "Master Decrypt");
 
     /* check for weak keys */
     for (int i = 0; i < 2; ++i)
     {
-        fixup_key(&key2.keys[i], key_type);
-        if (!check_key(&key2.keys[i], key_type))
+        if (!check_key(&key2.keys[i], &session->opt->key_type))
         {
             msg(D_TLS_ERRORS, "TLS Error: Bad dynamic key generated");
             goto exit;
         }
     }
-
-    /* Initialize OpenSSL key contexts */
-    int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
-    init_key_ctx_bi(key, &key2, key_direction, key_type, "Data Channel");
-
-    /* Initialize implicit IVs */
-    key_ctx_update_implicit_iv(&key->encrypt, key2.keys[(int)server].hmac,
-                               MAX_HMAC_KEY_LENGTH);
-    key_ctx_update_implicit_iv(&key->decrypt, key2.keys[1-(int)server].hmac,
-                               MAX_HMAC_KEY_LENGTH);
-
+    init_key_contexts(key, &session->opt->key_type, server, &key2);
     ret = true;
 
 exit:
-    secure_memzero(&master, sizeof(master));
     secure_memzero(&key2, sizeof(key2));
 
     return ret;
 }
 
+
 static void
 key_ctx_update_implicit_iv(struct key_ctx *ctx, uint8_t *key, size_t key_len)
 {
@@ -1879,10 +1912,7 @@ tls_session_generate_data_channel_keys(struct tls_session *session)
 {
     bool ret = false;
     struct key_state *ks = &session->key[KS_PRIMARY];   /* primary key */
-    const struct session_id *client_sid = session->opt->server ?
-                                          &ks->session_id_remote : &session->session_id;
-    const struct session_id *server_sid = !session->opt->server ?
-                                          &ks->session_id_remote : &session->session_id;
+
 
     if (ks->authenticated == KS_AUTH_FALSE)
     {
@@ -1891,9 +1921,8 @@ tls_session_generate_data_channel_keys(struct tls_session *session)
     }

src/openvpn/ssl.c tls_session_generate_data_channel_keys(struct tls_session *session) · line 1928

Quoted 10 lines
src/openvpn/ssl.c +2 -3
 
     ks->crypto_options.flags = session->opt->crypto_flags;
-    if (!generate_key_expansion(&ks->crypto_options.key_ctx_bi,
-                                &session->opt->key_type, ks->key_src, client_sid, server_sid,
-                                session->opt->server))
+
+    if (!generate_key_expansion(&ks->crypto_options.key_ctx_bi, session))
     {
         msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
         goto cleanup;

-Steffan

#9 lore raw
In reply to Arne Schwabe

Your patch has been applied to the master branch.

I have no idea what this all does (and not enough brain power to develop interest in finding out :-/ ) but if Steffan says it's good, so it is.

Also, t_client agrees :-)

commit 10abd656a3ae279cea7344055ce23637b7a62f6b (master)

Author: Arne Schwabe
Date:   Fri Aug 14 16:51:53 2020 +0200
     Refactor key_state_export_keying_material functions

     Signed-off-by: Arne Schwabe <[email protected]...>
     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Steffan Karger <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg20739.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#10 lore raw

Hi,

this commit seems to require a more recent mbedTLS version - it fails a number of my buildslaves with

gcc -DHAVE_CONFIG_H -I. -I../.. -I../../include -I../../include -I../../src/compat -DPLUGIN_LIBDIR=\"/usr/local/lib/openvpn/plugins\" -Wall -Wno-unused-parameter -Wno-unused-function -Wno-stringop-truncation -g -O2 -std=c99 -MT auth_token.o -MD -MP -MF .deps/auth_token.Tpo -c -o auth_token.o auth_token.c
In file included from ssl_backend.h:41:0,

                 from ssl_common.h:38,
                 from ssl.h:43,
                 from openvpn.h:31,
                 from auth_token.c:12:
ssl_mbedtls.h:90:5: error: unknown type name 'mbedtls_tls_prf_types'
     mbedtls_tls_prf_types tls_prf_type;
     ^

- I think it *should* fail the configure phase if mbedTLS is too old, and clearly specify which version is required now (we have a check, but it's fairly unspecific, and only says "mbed TLS 2.y.z required").

I've opened a trac ticket to track this

https://community.openvpn.net/openvpn/ticket/1319

gert

Quoted 33 lines · Gert Doering

Your patch has been applied to the master branch.

I have no idea what this all does (and not enough brain power to develop interest in finding out :-/ ) but if Steffan says it's good, so it is.

Also, t_client agrees :-)

commit 10abd656a3ae279cea7344055ce23637b7a62f6b (master)

Author: Arne Schwabe
Date:   Fri Aug 14 16:51:53 2020 +0200
     Refactor key_state_export_keying_material functions

     Signed-off-by: Arne Schwabe <[email protected]...>
     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Steffan Karger <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg20739.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

_______________________________________________
Openvpn-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openvpn-devel

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...