Index: tls.c
==================================================================
--- tls.c
+++ tls.c
@@ -74,10 +74,12 @@
 #define TLS_PROTO_TLS1_1	0x08
 #define TLS_PROTO_TLS1_2	0x10
 #define TLS_PROTO_TLS1_3	0x20
 #define ENABLED(flag, mask)	(((flag) & (mask)) == (mask))
 
+#define SSLKEYLOGFILE		"SSLKEYLOGFILE"
+
 /*
  * Static data structures
  */
 
 #ifndef OPENSSL_NO_DH
@@ -402,10 +404,20 @@
     Tcl_DecrRefCount(cmdPtr);
 
     Tcl_Release((ClientData) statePtr);
     Tcl_Release((ClientData) statePtr->interp);
 }
+
+void KeyLogCallback(const SSL *ssl, const char *line) {
+    char *str = getenv(SSLKEYLOGFILE);
+    FILE *fd;
+    if (str) {
+	fd = fopen(str, "a");
+	fprintf(fd, "%s\n",line);
+	fclose(fd);
+    }
+}
 
 /*
  *-------------------------------------------------------------------
  *
  * PasswordCallback -- 
@@ -1244,10 +1256,14 @@
     ctx = SSL_CTX_new (method);
 
     if (!ctx) {
         return(NULL);
     }
+
+    if (getenv(SSLKEYLOGFILE)) {
+	SSL_CTX_set_keylog_callback(ctx, KeyLogCallback);
+    }
 
 #if !defined(NO_TLS1_3)
     if (proto == TLS_PROTO_TLS1_3) {
         SSL_CTX_set_min_proto_version (ctx, TLS1_3_VERSION);
         SSL_CTX_set_max_proto_version (ctx, TLS1_3_VERSION);

Index: tls.htm
==================================================================
--- tls.htm
+++ tls.htm
@@ -413,10 +413,16 @@
 The use of the variable <strong>tls::debug</strong> is not recommended.
 It may be removed from future releases.
 </em>
 </p>
 
+<h3><a name="DEBUG">DEBUG</a></h3>
+
+TLS key logging can be enabled by setting the environment variable
+<b>SSLKEYLOGFILE</b> to the name of the file to log to. Then whenever TLS
+key material is generated or received it will be logged to the file.
+
 <h3><a name="HTTPS EXAMPLE">HTTPS EXAMPLE</a></h3>
 
 <p>This example uses a sample server.pem provided with the TLS release,
 courtesy of the <strong>OpenSSL</strong> project.</p>