Sample server GREASE from the server_random.

Originally GREASE was a client-only thing but, in TLS 1.3, we send some
bogus extensions in NewSessionTicket and CertificateRequest. Sampling
from the client_random works fine, but better to use our own entropy
rather than the peer's.

Change-Id: Ic7317eb75a9024c677fcde8e62c73aff380294e4
Reviewed-on: https://boringssl-review.googlesource.com/18144
Reviewed-by: Steven Valdez <svaldez@google.com>
diff --git a/ssl/handshake_client.cc b/ssl/handshake_client.cc
index 12947f0..4c85531 100644
--- a/ssl/handshake_client.cc
+++ b/ssl/handshake_client.cc
@@ -551,18 +551,6 @@
   return ret;
 }
 
-uint16_t ssl_get_grease_value(const SSL *ssl, enum ssl_grease_index_t index) {
-  /* Use the client_random for entropy. This both avoids calling |RAND_bytes| on
-   * a single byte repeatedly and ensures the values are deterministic. This
-   * allows the same ClientHello be sent twice for a HelloRetryRequest or the
-   * same group be advertised in both supported_groups and key_shares. */
-  uint16_t ret = ssl->s3->client_random[index];
-  /* This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16. */
-  ret = (ret & 0xf0) | 0x0a;
-  ret |= ret << 8;
-  return ret;
-}
-
 /* ssl_get_client_disabled sets |*out_mask_a| and |*out_mask_k| to masks of
  * disabled algorithms. */
 static void ssl_get_client_disabled(SSL *ssl, uint32_t *out_mask_a,
diff --git a/ssl/s3_both.cc b/ssl/s3_both.cc
index 3423234..1c47c1c 100644
--- a/ssl/s3_both.cc
+++ b/ssl/s3_both.cc
@@ -861,4 +861,21 @@
   return ret;
 }
 
+uint16_t ssl_get_grease_value(const SSL *ssl, enum ssl_grease_index_t index) {
+  /* Use the client_random or server_random for entropy. This both avoids
+   * calling |RAND_bytes| on a single byte repeatedly and ensures the values are
+   * deterministic. This allows the same ClientHello be sent twice for a
+   * HelloRetryRequest or the same group be advertised in both supported_groups
+   * and key_shares. */
+  uint16_t ret = ssl->server ? ssl->s3->server_random[index]
+                             : ssl->s3->client_random[index];
+  /* The first four bytes of server_random are a timestamp prior to TLS 1.3, but
+   * servers have no fields to GREASE until TLS 1.3. */
+  assert(!ssl->server || ssl3_protocol_version(ssl) >= TLS1_3_VERSION);
+  /* This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16. */
+  ret = (ret & 0xf0) | 0x0a;
+  ret |= ret << 8;
+  return ret;
+}
+
 }  // namespace bssl