diff --git a/src/shctx.c b/src/shctx.c
index d51f67c..ffc7729 100644
--- a/src/shctx.c
+++ b/src/shctx.c
@@ -849,10 +849,25 @@ int shctx_new_cb(SSL *ssl, SSL_SESSION *sess)
 	/* Inform other machines that we've been given a new key */
 	broadcast_key(packet->hdr.id, packet->data, data_len);
 
+	static unsigned char *ctx_sid_buf;
+	static unsigned int ctx_buflen;
+	unsigned char *new_ctx_buf;
+
 err:
 	/* reset original length values */
-	SSL_SESSION_set1_id(sess, sid_data, sid_length);
-	SSL_SESSION_set1_id_context(sess, sid_ctx_data, sid_ctx_length);
+
+	/* these setters call memcpy so src and dst must not be the same */
+
+	if (sid_ctx_length > ctx_buflen) {
+		new_ctx_buf = realloc(ctx_sid_buf, sid_ctx_length);
+		assert(new_ctx_buf);
+		ctx_sid_buf = new_ctx_buf;
+		ctx_buflen = sid_ctx_length;
+	}
+
+	SSL_SESSION_set1_id(sess, packet->hdr.id, sid_length);
+	memcpy(ctx_sid_buf, sid_ctx_data, sid_ctx_length);
+	SSL_SESSION_set1_id_context(sess, ctx_sid_buf, sid_ctx_length);
 
 	return 0; /* do not increment session reference count */
 }
