Release some temporaries outside of ClientHello callbacks.

Also add ECH GREASE state into the mix. Clearing this isn't critical,
especially now that we have an SSL_HANDSHAKE structure, but it's easy
enough.

Bug: 275
Change-Id: If1aa8d5c0c8fdb5af710852778ce452c507a2524
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/47985
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/ssl/handshake_client.cc b/ssl/handshake_client.cc
index 07da255..aa015d4 100644
--- a/ssl/handshake_client.cc
+++ b/ssl/handshake_client.cc
@@ -422,6 +422,12 @@
   return ssl_early_data_accepted;
 }
 
+void ssl_done_writing_client_hello(SSL_HANDSHAKE *hs) {
+  hs->ech_grease.Reset();
+  hs->cookie.Reset();
+  hs->key_share_bytes.Reset();
+}
+
 static enum ssl_hs_wait_t do_start_connect(SSL_HANDSHAKE *hs) {
   SSL *const ssl = hs->ssl;
 
@@ -666,7 +672,7 @@
   // Clear some TLS 1.3 state that no longer needs to be retained.
   hs->key_shares[0].reset();
   hs->key_shares[1].reset();
-  hs->key_share_bytes.Reset();
+  ssl_done_writing_client_hello(hs);
 
   // A TLS 1.2 server would not know to skip the early data we offered. Report
   // an error code sooner. The caller may use this error code to implement the
diff --git a/ssl/internal.h b/ssl/internal.h
index c5fb263..d6801df 100644
--- a/ssl/internal.h
+++ b/ssl/internal.h
@@ -2135,6 +2135,10 @@
 // handshake. Note, in TLS 1.2 resumptions, this session is immutable.
 const SSL_SESSION *ssl_handshake_session(const SSL_HANDSHAKE *hs);
 
+// ssl_done_writing_client_hello is called after the last ClientHello is written
+// by |hs|. It releases some memory that is no longer needed.
+void ssl_done_writing_client_hello(SSL_HANDSHAKE *hs);
+
 
 // SSLKEYLOGFILE functions.
 
diff --git a/ssl/t1_lib.cc b/ssl/t1_lib.cc
index 0eec28a..da3400f 100644
--- a/ssl/t1_lib.cc
+++ b/ssl/t1_lib.cc
@@ -2265,7 +2265,6 @@
                        hs->key_share_bytes.size())) {
       return false;
     }
-    hs->key_share_bytes.Reset();
     if (group_id == 0) {
       return CBB_flush(out);
     }
@@ -2480,8 +2479,6 @@
     return false;
   }
 
-  // The cookie is no longer needed in memory.
-  hs->cookie.Reset();
   return true;
 }
 
diff --git a/ssl/tls13_client.cc b/ssl/tls13_client.cc
index 37ca4b2..c7f45f6 100644
--- a/ssl/tls13_client.cc
+++ b/ssl/tls13_client.cc
@@ -260,6 +260,7 @@
     return ssl_hs_error;
   }
 
+  ssl_done_writing_client_hello(hs);
   hs->tls13_state = state_read_server_hello;
   return ssl_hs_flush;
 }