Create MBEDTLS_SSL_KEYING_MATERIAL_EXPORT option

Add the option MBEDTLS_SSL_KEYING_MATERIAL_EXPORT to mbedtls_config.h
to control if the function mbedtls_ssl_export_keying_material() should
be available. By default, the option is disabled.

This is because the exporter for TLS 1.2 requires client_random and
server_random need to be stored after the handshake is complete.

Signed-off-by: Max Fillinger <max@max-fillinger.net>
diff --git a/include/mbedtls/mbedtls_config.h b/include/mbedtls/mbedtls_config.h
index 2dc475b..ca1486d 100644
--- a/include/mbedtls/mbedtls_config.h
+++ b/include/mbedtls/mbedtls_config.h
@@ -737,6 +737,20 @@
  */
 //#define MBEDTLS_SSL_RECORD_SIZE_LIMIT
 
+/*
+ * \def MBEDTLS_SSL_KEYING_MATERIAL_EXPORT
+ *
+ * When this option is enabled, the client and server can extract additional
+ * shared symmetric keys after an SSL handshake using the function
+ * mbedtls_ssl_export_keying_material().
+ *
+ * The process for deriving the keys is specified in RFC 5705 for TLS 1.2 and
+ * in RFC 8446, Section 7.5, for TLS 1.3.
+ *
+ * Uncomment this macro to enable mbedtls_ssl_export_keying_material().
+ */
+//#define MBEDTLS_SSL_KEYING_MATERIAL_EXPORT
+
 /**
  * \def MBEDTLS_SSL_RENEGOTIATION
  *
diff --git a/include/mbedtls/ssl.h b/include/mbedtls/ssl.h
index 9ded4e6..8383ead 100644
--- a/include/mbedtls/ssl.h
+++ b/include/mbedtls/ssl.h
@@ -676,6 +676,14 @@
 /* Length in number of bytes of the TLS sequence number */
 #define MBEDTLS_SSL_SEQUENCE_NUMBER_LEN 8
 
+/* Helper to state that client_random and server_random need to be stored
+ * after the handshake is complete. This is required for context serialization
+ * and for the keying material exporter in TLS 1.2. */
+#if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) || \
+    (defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) && defined(MBEDTLS_SSL_PROTO_TLS1_2))
+#define MBEDTLS_SSL_KEEP_RANDBYTES
+#endif
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -5407,7 +5415,7 @@
  *
  * \return            0 on success. An SSL specific error on failure.
  */
- #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) || !defined(MBEDTLS_SSL_PROTO_TLS1_2)
+#if defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
 int mbedtls_ssl_export_keying_material(mbedtls_ssl_context *ssl,
                                        uint8_t *out, const size_t key_len,
                                        const char *label, const size_t label_len,