Index: asp3_tinet_ecnl_rx/trunk/wolfssl-3.12.2/src/tls13.c
===================================================================
--- asp3_tinet_ecnl_rx/trunk/wolfssl-3.12.2/src/tls13.c	(revision 337)
+++ asp3_tinet_ecnl_rx/trunk/wolfssl-3.12.2/src/tls13.c	(revision 372)
@@ -22,18 +22,55 @@
 
 /*
- * WOLFSSL_TLS13_DRAFT_18
- *    Conform with Draft 18 of the TLS v1.3 specification.
+ * BUILD_GCM
+ *    Enables AES-GCM ciphersuites.
+ * HAVE_AESCCM
+ *    Enables AES-CCM ciphersuites.
+ * HAVE_SESSION_TICKET
+ *    Enables session tickets - required for TLS 1.3 resumption.
+ * NO_PSK
+ *    Do not enable Pre-Shared Keys.
+ * TLS13_SUPPORTS_EXPORTERS
+ *    Gaurd to compile out any code for exporter keys.
+ *    Feature not supported yet.
+ * WOLFSSL_ASYNC_CRYPT
+ *    Enables the use of asynchornous cryptographic operations.
+ *    This is available for ciphers and certificates.
+ * HAVE_CHACHA && HAVE_POLY1305
+ *    Enables use of CHACHA20-POLY1305 ciphersuites.
+ * WOLFSSL_DEBUG_TLS
+ *    Writes out details of TLS 1.3 protocol including hanshake message buffers
+ *    and key generation input and output.
  * WOLFSSL_EARLY_DATA
  *    Allow 0-RTT Handshake using Early Data extensions and handshake message
+ * WOLFSSL_EARLY_DATA_GROUP
+ *    Group EarlyData message with ClientHello when sending
+ * WOLFSSL_NO_SERVER_GROUPS_EXT
+ *    Do not send the server's groups in an extension when the server's top
+ *    preference is not in client's list.
  * WOLFSSL_POST_HANDSHAKE_AUTH
  *    Allow TLS v1.3 code to perform post-handshake authentication of the
  *    client.
+ * WOLFSSL_SEND_HRR_COOKIE
+ *    Send a cookie in hello_retry_request message to enable stateless tracking
+ *    of ClientHello replies.
+ * WOLFSSL_TLS13
+ *    Enable TLS 1.3 protocol implementation.
+ * WOLFSSL_TLS13_DRAFT_18
+ *    Conform with Draft 18 of the TLS v1.3 specification.
+ * WOLFSSL_TLS13_DRAFT_22
+ *    Conform with Draft 22 of the TLS v1.3 specification.
+ * WOLFSSL_TLS13_DRAFT_23
+ *    Conform with Draft 23 of the TLS v1.3 specification.
+ * WOLFSSL_TLS13_MIDDLEBOX_COMPAT
+ *    Enable middlebox compatability in the TLS 1.3 handshake.
+ *    This includes sending ChangeCipherSpec before encrypted messages and
+ *    including a session id.
+ * WOLFSSL_TLS13_SHA512
+ *    Allow generation of SHA-512 digests in handshake - no ciphersuite
+ *    requires SHA-512 at this time.
  * WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  *    Allow a NewSessionTicket message to be sent by server before Client's
  *    Finished message.
- *    See TLS v.13 specification, Section 4.6.1, Paragraph 4 (Note).
- * TLS13_SUPPORTS_EXPORTERS
- *    Gaurd to compile out any code for exporter keys.
- *    Feature not supported yet.
+ *    See TLS v1.3 specification, Section 4.6.1, Paragraph 4 (Note).
  */
 
@@ -46,5 +83,5 @@
 #ifdef WOLFSSL_TLS13
 #ifdef HAVE_SESSION_TICKET
-    #include <sys/time.h>
+    #include <wolfssl/wolfcrypt/wc_port.h>
 #endif
 
@@ -94,4 +131,9 @@
 #endif
 
+#ifndef HAVE_HKDF
+    #error The build option HAVE_HKDF is required for TLS 1.3
+#endif
+
+
 /* Set ret to error value and jump to label.
  *
@@ -135,5 +177,5 @@
         #endif
 
-        #ifdef WOLFSSL_TLS13_TLS13_SHA512
+        #ifdef WOLFSSL_TLS13_SHA512
         case sha512_mac:
             hash = WC_SHA512;
@@ -170,4 +212,5 @@
  *
  * okm          The generated pseudorandom key - output key material.
+ * okmLen       The length of generated pseudorandom key - output key material.
  * prk          The salt - pseudo-random key.
  * prkLen       The length of the salt - pseudo-random key.
@@ -191,8 +234,8 @@
 
     /* Output length. */
-    data[idx++] = okmLen >> 8;
-    data[idx++] = okmLen;
+    data[idx++] = (byte)(okmLen >> 8);
+    data[idx++] = (byte)okmLen;
     /* Length of protocol | label. */
-    data[idx++] = protocolLen + labelLen;
+    data[idx++] = (byte)(protocolLen + labelLen);
     /* Protocol */
     XMEMCPY(&data[idx], protocol, protocolLen);
@@ -202,5 +245,5 @@
     idx += labelLen;
     /* Length of hash of messages */
-    data[idx++] = infoLen;
+    data[idx++] = (byte)infoLen;
     /* Hash of messages */
     XMEMCPY(&data[idx], info, infoLen);
@@ -257,10 +300,10 @@
                         byte* msg, int msgLen, int hashAlgo)
 {
-    byte        hash[MAX_DIGEST_SIZE];
+    byte        hash[WC_MAX_DIGEST_SIZE];
     Digest      digest;
     word32      hashSz = 0;
     const byte* protocol;
     word32      protocolLen;
-    int         digestAlg;
+    int         digestAlg = -1;
     int         ret = BAD_FUNC_ARG;
 
@@ -305,5 +348,11 @@
             break;
 #endif
-    }
+        default:
+            digestAlg = -1;
+            break;
+    }
+
+    if (digestAlg < 0)
+        return HASH_TYPE_E;
 
     if (ret != 0)
@@ -345,5 +394,5 @@
 {
     int         ret = 0;
-    byte        hash[MAX_DIGEST_SIZE];
+    byte        hash[WC_MAX_DIGEST_SIZE];
     word32      hashSz = 0;
     word32      hashOutSz = 0;
@@ -808,4 +857,60 @@
 #endif
 }
+
+#ifndef WOLFSSL_TLS13_DRAFT_18
+#if defined(HAVE_SESSION_TICKET)
+/* Length of the resumption label. */
+#define RESUMPTION_LABEL_SZ         10
+/* Resumption label for generating PSK assocated with the ticket. */
+static const byte resumptionLabel[RESUMPTION_LABEL_SZ+1] = "resumption";
+/* Derive the PSK assocated with the ticket.
+ *
+ * ssl       The SSL/TLS object.
+ * nonce     The nonce to derive with.
+ * nonceLen  The length of the nonce to derive with.
+ * secret    The derived secret.
+ * returns 0 on success, otherwise failure.
+ */
+static int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen,
+                               byte* secret)
+{
+    int         digestAlg;
+    /* Only one protocol version defined at this time. */
+    const byte* protocol    = tls13ProtocolLabel;
+    word32      protocolLen = TLS13_PROTOCOL_LABEL_SZ;
+
+    WOLFSSL_MSG("Derive Resumption PSK");
+
+    switch (ssl->specs.mac_algorithm) {
+        #ifndef NO_SHA256
+        case sha256_mac:
+            digestAlg = WC_SHA256;
+            break;
+        #endif
+
+        #ifdef WOLFSSL_SHA384
+        case sha384_mac:
+            digestAlg = WC_SHA384;
+            break;
+        #endif
+
+        #ifdef WOLFSSL_TLS13_SHA512
+        case sha512_mac:
+            digestAlg = WC_SHA512;
+            break;
+        #endif
+
+        default:
+            return BAD_FUNC_ARG;
+    }
+
+    return HKDF_Expand_Label(secret, ssl->specs.hash_size,
+                             ssl->session.masterSecret, ssl->specs.hash_size,
+                             protocol, protocolLen, resumptionLabel,
+                             RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg);
+}
+#endif /* HAVE_SESSION_TICKET */
+#endif /* WOLFSSL_TLS13_DRAFT_18 */
+
 
 /* Calculate the HMAC of message data to this point.
@@ -897,5 +1002,5 @@
 static int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
 {
-    int   ret;
+    int   ret = BAD_FUNC_ARG; /* Assume failure */
     int   i = 0;
 #ifdef WOLFSSL_SMALL_STACK
@@ -925,5 +1030,5 @@
 #ifdef WOLFSSL_EARLY_DATA
         case early_data_key:
-            ret = DeriveEarlyTrafficSecret(ssl, ssl->arrays->clientSecret);
+            ret = DeriveEarlyTrafficSecret(ssl, ssl->clientSecret);
             if (ret != 0)
                 goto end;
@@ -934,5 +1039,5 @@
             if (provision & PROVISION_CLIENT) {
                 ret = DeriveClientHandshakeSecret(ssl,
-                                                  ssl->arrays->clientSecret);
+                                                  ssl->clientSecret);
                 if (ret != 0)
                     goto end;
@@ -940,5 +1045,5 @@
             if (provision & PROVISION_SERVER) {
                 ret = DeriveServerHandshakeSecret(ssl,
-                                                  ssl->arrays->serverSecret);
+                                                  ssl->serverSecret);
                 if (ret != 0)
                     goto end;
@@ -948,10 +1053,10 @@
         case traffic_key:
             if (provision & PROVISION_CLIENT) {
-                ret = DeriveClientTrafficSecret(ssl, ssl->arrays->clientSecret);
+                ret = DeriveClientTrafficSecret(ssl, ssl->clientSecret);
                 if (ret != 0)
                     goto end;
             }
             if (provision & PROVISION_SERVER) {
-                ret = DeriveServerTrafficSecret(ssl, ssl->arrays->serverSecret);
+                ret = DeriveServerTrafficSecret(ssl, ssl->serverSecret);
                 if (ret != 0)
                     goto end;
@@ -961,10 +1066,10 @@
         case update_traffic_key:
             if (provision & PROVISION_CLIENT) {
-                ret = DeriveTrafficSecret(ssl, ssl->arrays->clientSecret);
+                ret = DeriveTrafficSecret(ssl, ssl->clientSecret);
                 if (ret != 0)
                     goto end;
             }
             if (provision & PROVISION_SERVER) {
-                ret = DeriveTrafficSecret(ssl, ssl->arrays->serverSecret);
+                ret = DeriveTrafficSecret(ssl, ssl->serverSecret);
                 if (ret != 0)
                     goto end;
@@ -982,5 +1087,5 @@
         WOLFSSL_MSG("Derive Client Key");
         ret = DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
-                        ssl->arrays->clientSecret, writeKeyLabel,
+                        ssl->clientSecret, writeKeyLabel,
                         WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
         if (ret != 0)
@@ -993,5 +1098,5 @@
         WOLFSSL_MSG("Derive Server Key");
         ret = DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
-                        ssl->arrays->serverSecret, writeKeyLabel,
+                        ssl->serverSecret, writeKeyLabel,
                         WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
         if (ret != 0)
@@ -1004,5 +1109,5 @@
         WOLFSSL_MSG("Derive Client IV");
         ret = DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
-                        ssl->arrays->clientSecret, writeIVLabel,
+                        ssl->clientSecret, writeIVLabel,
                         WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
         if (ret != 0)
@@ -1015,5 +1120,5 @@
         WOLFSSL_MSG("Derive Server IV");
         ret = DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
-                        ssl->arrays->serverSecret, writeIVLabel,
+                        ssl->serverSecret, writeIVLabel,
                         WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
         if (ret != 0)
@@ -1311,5 +1416,10 @@
     rl->type    = type;
     rl->pvMajor = ssl->version.major;
+#ifdef WOLFSSL_TLS13_DRAFT_18
     rl->pvMinor = TLSv1_MINOR;
+#else
+    /* NOTE: May be TLSv1_MINOR when sending first ClientHello. */
+    rl->pvMinor = TLSv1_2_MINOR;
+#endif
     c16toa((word16)length, rl->length);
 }
@@ -1388,5 +1498,5 @@
  * out          The buffer to write into.
  */
-static INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
+static WC_INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
 {
     word32 seq[2] = {0, 0};
@@ -1418,5 +1528,5 @@
  * order  The side on which the message is to be or was sent.
  */
-static INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
+static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
                                    int order)
 {
@@ -1431,5 +1541,5 @@
 }
 
-#ifdef HAVE_CHACHA
+#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
 /* Encrypt with ChaCha20 and create authenication tag with Poly1305.
  *
@@ -1440,4 +1550,6 @@
  * sz      The number of bytes to encrypt.
  * nonce   The nonce to use with ChaCha20.
+ * aad     The additional authentication data.
+ * aadSz   The size of the addition authentication data.
  * tag     The authentication tag buffer.
  * returns 0 on success, otherwise failure.
@@ -1445,5 +1557,5 @@
 static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
                                     const byte* input, word16 sz, byte* nonce,
-                                    byte* tag)
+                                    const byte* aad, word16 aadSz, byte* tag)
 {
     int    ret    = 0;
@@ -1474,6 +1586,6 @@
         return ret;
     /* Add authentication code of encrypted data to end. */
-    ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, output, sz, tag,
-                          POLY1305_AUTH_SZ);
+    ret = wc_Poly1305_MAC(ssl->auth.poly1305, (byte*)aad, aadSz, output, sz,
+                          tag, POLY1305_AUTH_SZ);
 
     return ret;
@@ -1486,11 +1598,13 @@
  * output  The buffer to write encrypted data and authentication tag into.
  *         May be the same pointer as input.
- * input   The data to encrypt.
+ * input   The record header and data to encrypt.
  * sz      The number of bytes to encrypt.
+ * aad     The additional authentication data.
+ * aadSz   The size of the addition authentication data.
  * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
  * returns 0 on success, otherwise failure.
  */
 static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
-                        word16 sz, int asyncOkay)
+                        word16 sz, const byte* aad, word16 aadSz, int asyncOkay)
 {
     int    ret    = 0;
@@ -1525,4 +1639,9 @@
             WOLFSSL_MSG("Data to encrypt");
             WOLFSSL_BUFFER(input, dataSz);
+#if !defined(WOLFSSL_TLS13_DRAFT_18) && !defined(WOLFSSL_TLS13_DRAFT_22) && \
+                                        !defined(WOLFSSL_TLS13_DRAFT_23)
+            WOLFSSL_MSG("Additional Authentication Data");
+            WOLFSSL_BUFFER(aad, aadSz);
+#endif
         #endif
 
@@ -1547,5 +1666,5 @@
                 case wolfssl_aes_gcm:
                 #ifdef WOLFSSL_ASYNC_CRYPT
-                    /* intialize event */
+                    /* initialize event */
                     asyncDev = &ssl->encrypt.aes->asyncDev;
                     ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
@@ -1557,5 +1676,5 @@
                     ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
                         dataSz, ssl->encrypt.nonce, nonceSz,
-                        output + dataSz, macSz, NULL, 0);
+                        output + dataSz, macSz, aad, aadSz);
                     break;
             #endif
@@ -1564,5 +1683,5 @@
                 case wolfssl_aes_ccm:
                 #ifdef WOLFSSL_ASYNC_CRYPT
-                    /* intialize event */
+                    /* initialize event */
                     asyncDev = &ssl->encrypt.aes->asyncDev;
                     ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
@@ -1574,5 +1693,5 @@
                     ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
                         dataSz, ssl->encrypt.nonce, nonceSz,
-                        output + dataSz, macSz, NULL, 0);
+                        output + dataSz, macSz, aad, aadSz);
                     break;
             #endif
@@ -1581,5 +1700,5 @@
                 case wolfssl_chacha:
                     ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
-                        ssl->encrypt.nonce, output + dataSz);
+                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
                     break;
             #endif
@@ -1631,5 +1750,5 @@
 }
 
-#ifdef HAVE_CHACHA
+#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
 /* Decrypt with ChaCha20 and check authenication tag with Poly1305.
  *
@@ -1640,4 +1759,6 @@
  * sz      The number of bytes to decrypt.
  * nonce   The nonce to use with ChaCha20.
+ * aad     The additional authentication data.
+ * aadSz   The size of the addition authentication data.
  * tagIn   The authentication tag data from packet.
  * returns 0 on success, otherwise failure.
@@ -1645,4 +1766,5 @@
 static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
                                     const byte* input, word16 sz, byte* nonce,
+                                    const byte* aad, word16 aadSz,
                                     const byte* tagIn)
 {
@@ -1669,6 +1791,6 @@
         return ret;
     /* Generate authentication tag for encrypted data. */
-    if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, (byte*)input, sz,
-                               tag, sizeof(tag))) != 0) {
+    if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, (byte*)aad, aadSz,
+                                    (byte*)input, sz, tag, sizeof(tag))) != 0) {
         return ret;
     }
@@ -1692,9 +1814,12 @@
  * output  The buffer to write decrypted data into.
  *         May be the same pointer as input.
- * input   The data to encrypt and authentication tag.
+ * input   The data to decrypt and authentication tag.
  * sz      The length of the encrypted data plus authentication tag.
+ * aad     The additional authentication data.
+ * aadSz   The size of the addition authentication data.
  * returns 0 on success, otherwise failure.
  */
-int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz)
+int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz,
+                 const byte* aad, word16 aadSz)
 {
     int    ret    = 0;
@@ -1737,4 +1862,9 @@
             WOLFSSL_MSG("Data to decrypt");
             WOLFSSL_BUFFER(input, dataSz);
+#if !defined(WOLFSSL_TLS13_DRAFT_18) && !defined(WOLFSSL_TLS13_DRAFT_22) && \
+                                        !defined(WOLFSSL_TLS13_DRAFT_23)
+            WOLFSSL_MSG("Additional Authentication Data");
+            WOLFSSL_BUFFER(aad, aadSz);
+#endif
             WOLFSSL_MSG("Authentication tag");
             WOLFSSL_BUFFER(input + dataSz, macSz);
@@ -1761,5 +1891,5 @@
                 case wolfssl_aes_gcm:
                 #ifdef WOLFSSL_ASYNC_CRYPT
-                    /* intialize event */
+                    /* initialize event */
                     ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
                         WC_ASYNC_FLAG_CALL_AGAIN);
@@ -1771,5 +1901,5 @@
                     ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
                         dataSz, ssl->decrypt.nonce, nonceSz,
-                        input + dataSz, macSz, NULL, 0);
+                        input + dataSz, macSz, aad, aadSz);
                 #ifdef WOLFSSL_ASYNC_CRYPT
                     if (ret == WC_PENDING_E) {
@@ -1784,5 +1914,5 @@
                 case wolfssl_aes_ccm:
                 #ifdef WOLFSSL_ASYNC_CRYPT
-                    /* intialize event */
+                    /* initialize event */
                     ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
                         WC_ASYNC_FLAG_CALL_AGAIN);
@@ -1794,5 +1924,5 @@
                     ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
                         dataSz, ssl->decrypt.nonce, nonceSz,
-                        input + dataSz, macSz, NULL, 0);
+                        input + dataSz, macSz, aad, aadSz);
                 #ifdef WOLFSSL_ASYNC_CRYPT
                     if (ret == WC_PENDING_E) {
@@ -1807,5 +1937,5 @@
                 case wolfssl_chacha:
                     ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
-                        ssl->decrypt.nonce, input + dataSz);
+                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
                     break;
             #endif
@@ -1932,10 +2062,13 @@
         case BUILD_MSG_BEGIN:
         {
-            if (output == NULL || input == NULL)
-                return BAD_FUNC_ARG;
             /* catch mistaken sizeOnly parameter */
-            if (sizeOnly && (output || input)) {
-                WOLFSSL_MSG("BuildTls13Message with sizeOnly doesn't need "
-                            "input or output");
+            if (sizeOnly) {
+                if (output || input) {
+                    WOLFSSL_MSG("BuildTls13Message with sizeOnly "
+                                "doesn't need input or output");
+                    return BAD_FUNC_ARG;
+                }
+            }
+            else if (output == NULL || input == NULL) {
                 return BAD_FUNC_ARG;
             }
@@ -1986,5 +2119,5 @@
         {
             /* The real record content type goes at the end of the data. */
-            output[args->idx++] = type;
+            output[args->idx++] = (byte)type;
 
         #ifdef ATOMIC_USER
@@ -2000,6 +2133,15 @@
         #endif
             {
+#if defined(WOLFSSL_TLS13_DRAFT_18) || defined(WOLFSSL_TLS13_DRAFT_22) || \
+                                       defined(WOLFSSL_TLS13_DRAFT_23)
                 output += args->headerSz;
-                ret = EncryptTls13(ssl, output, output, args->size, asyncOkay);
+                ret = EncryptTls13(ssl, output, output, args->size, NULL, 0,
+                                                                     asyncOkay);
+#else
+                const byte* aad = output;
+                output += args->headerSz;
+                ret = EncryptTls13(ssl, output, output, args->size, aad,
+                                   RECORD_HEADER_SZ, asyncOkay);
+#endif
             }
             break;
@@ -2030,279 +2172,28 @@
 }
 
-#ifndef NO_WOLFSSL_CLIENT
 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
-/* Setup pre-shared key based on the details in the extension data.
- *
- * ssl  SSL/TLS object.
- * psk  Pre-shared key extension data.
- * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
- * other negative value on failure.
- */
-static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk)
-{
-    int ret;
-
-    ssl->options.cipherSuite0 = psk->cipherSuite0;
-    ssl->options.cipherSuite  = psk->cipherSuite;
-    if ((ret = SetCipherSpecs(ssl)) != 0)
-        return ret;
-
-#ifdef HAVE_SESSION_TICKET
-    if (psk->resumption) {
-    #ifdef WOLFSSL_EARLY_DATA
-        if (ssl->session.maxEarlyDataSz == 0)
-            ssl->earlyData = 0;
-    #endif
-        /* Resumption PSK is master secret. */
-        ssl->arrays->psk_keySz = ssl->specs.hash_size;
-        XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
-                ssl->arrays->psk_keySz);
-    }
-#endif
-#ifndef NO_PSK
-    if (!psk->resumption) {
-        /* Get the pre-shared key. */
-        ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
-                (char *)psk->identity, ssl->arrays->client_identity,
-                MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
-        if (ssl->arrays->psk_keySz == 0 ||
-                                 ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
-            return PSK_KEY_ERROR;
+/* Find the cipher suite in the suites set in the SSL.
+ *
+ * ssl    SSL/TLS object.
+ * suite  Cipher suite to look for.
+ * returns 1 when suite is found in SSL/TLS object's list and 0 otherwise.
+ */
+static int FindSuite(WOLFSSL* ssl, byte* suite)
+{
+    int i;
+
+    for (i = 0; i < ssl->suites->suiteSz; i += 2) {
+        if (ssl->suites->suites[i+0] == suite[0] &&
+            ssl->suites->suites[i+1] == suite[1]) {
+            return 1;
         }
     }
-#endif
-
-    /* Derive the early secret using the PSK. */
-    return DeriveEarlySecret(ssl);
-}
-
-/* Derive and write the binders into the ClientHello in space left when
- * writing the Pre-Shared Key extension.
- *
- * ssl     The SSL/TLS object.
- * output  The buffer containing the ClientHello.
- * idx     The index at the end of the completed ClientHello.
- * returns 0 on success and otherwise failure.
- */
-static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
-{
-    int           ret;
-    TLSX*         ext;
-    PreSharedKey* current;
-    byte          binderKey[MAX_DIGEST_SIZE];
-    word16        len;
-
-    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
-    if (ext == NULL)
-        return SANITY_MSG_E;
-
-    /* Get the size of the binders to determine where to write binders. */
-    idx -= TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
-                                            client_hello);
-
-    /* Hash truncated ClientHello - up to binders. */
-    ret = HashOutput(ssl, output, idx, 0);
-    if (ret != 0)
-        return ret;
-
-    current = (PreSharedKey*)ext->data;
-    /* Calculate the binder for each identity based on previous handshake data.
-     */
-    while (current != NULL) {
-        if ((ret = SetupPskKey(ssl, current)) != 0)
-            return ret;
-
-    #ifdef HAVE_SESSION_TICKET
-        if (current->resumption)
-            ret = DeriveBinderKeyResume(ssl, binderKey);
-    #endif
-    #ifndef NO_PSK
-        if (!current->resumption)
-            ret = DeriveBinderKey(ssl, binderKey);
-    #endif
-        if (ret != 0)
-            return ret;
-
-        /* Derive the Finished message secret. */
-        ret = DeriveFinishedSecret(ssl, binderKey,
-                                             ssl->keys.client_write_MAC_secret);
-        if (ret != 0)
-            return ret;
-
-        /* Build the HMAC of the handshake message data = binder. */
-        ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
-            current->binder, &current->binderLen);
-        if (ret != 0)
-            return ret;
-
-        current = current->next;
-    }
-
-    /* Data entered into extension, now write to message. */
-    len = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
-                                         client_hello);
-
-    /* Hash binders to complete the hash of the ClientHello. */
-    ret = HashOutputRaw(ssl, output + idx, len);
-    if (ret < 0)
-        return ret;
-
-    #ifdef WOLFSSL_EARLY_DATA
-    if (ssl->earlyData) {
-        if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data)) != 0)
-            return ret;
-
-        /* Derive early data encryption key. */
-        ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
-        if (ret != 0)
-            return ret;
-        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
-            return ret;
-    }
-    #endif
-    return ret;
-}
-#endif
-
-/* Send a ClientHello message to the server.
- * Include the information required to start a handshake with servers using
- * protocol versions less than TLS v1.3.
- * Only a client will send this message.
- *
- * ssl  The SSL/TLS object.
- * returns 0 on success and otherwise failure.
- */
-int SendTls13ClientHello(WOLFSSL* ssl)
-{
-    byte*  output;
-    word32 length;
-    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
-    int    sendSz;
-    int    ret;
-
-    WOLFSSL_ENTER("SendTls13ClientHello");
-
-#ifdef HAVE_SESSION_TICKET
-    if (ssl->options.resuming &&
-            (ssl->session.version.major != ssl->version.major ||
-             ssl->session.version.minor != ssl->version.minor)) {
-        /* Cannot resume with a different protocol version - new handshake. */
-        ssl->options.resuming = 0;
-        ssl->version.major = ssl->session.version.major;
-        ssl->version.minor = ssl->session.version.minor;
-        return SendClientHello(ssl);
-    }
-#endif
-
-    if (ssl->suites == NULL) {
-        WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
-        return SUITES_ERROR;
-    }
-
-    /* Version | Random | Session Id | Cipher Suites | Compression | Ext  */
-    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
-             SUITE_LEN + COMP_LEN + ENUM_LEN;
-
-    /* Auto populate extensions supported unless user defined. */
-    if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
-        return ret;
-#ifdef WOLFSSL_EARLY_DATA
-    #ifndef NO_PSK
-        if (!ssl->options.resuming && ssl->options.client_psk_cb == NULL)
-    #else
-        if (!ssl->options.resuming)
-    #endif
-            ssl->earlyData = 0;
-    if (ssl->earlyData && (ret = TLSX_EarlyData_Use(ssl, 0)) < 0)
-        return ret;
-#endif
-#ifdef HAVE_QSH
-    if (QSH_Init(ssl) != 0)
-        return MEMORY_E;
-#endif
-    /* Include length of TLS extensions. */
-    length += TLSX_GetRequestSize(ssl, client_hello);
-
-    /* Total message size. */
-    sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
-
-    /* Check buffers are big enough and grow if needed. */
-    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
-        return ret;
-
-    /* Get position in output buffer to write new message to. */
-    output = ssl->buffers.outputBuffer.buffer +
-             ssl->buffers.outputBuffer.length;
-
-    /* Put the record and handshake headers on. */
-    AddTls13Headers(output, length, client_hello, ssl);
-
-    /* Protocol version. */
-    output[idx++] = SSLv3_MAJOR;
-    output[idx++] = TLSv1_2_MINOR;
-    ssl->chVersion = ssl->version;
-
-    /* Client Random */
-    if (ssl->options.connectState == CONNECT_BEGIN) {
-        ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
-        if (ret != 0)
-            return ret;
-
-        /* Store random for possible second ClientHello. */
-        XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
-    }
-    else
-        XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
-    idx += RAN_LEN;
-
-    /* TLS v1.3 does not use session id - 0 length. */
-    output[idx++] = 0;
-
-    /* Cipher suites */
-    c16toa(ssl->suites->suiteSz, output + idx);
-    idx += OPAQUE16_LEN;
-    XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz);
-    idx += ssl->suites->suiteSz;
-
-    /* Compression not supported in TLS v1.3. */
-    output[idx++] = COMP_LEN;
-    output[idx++] = NO_COMPRESSION;
-
-    /* Write out extensions for a request. */
-    idx += TLSX_WriteRequest(ssl, output + idx, client_hello);
-
-#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
-    /* Resumption has a specific set of extensions and binder is calculated
-     * for each identity.
-     */
-    if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY))
-        ret = WritePSKBinders(ssl, output, idx);
-    else
-#endif
-        ret = HashOutput(ssl, output, idx, 0);
-    if (ret != 0)
-        return ret;
-
-    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
-
-#ifdef WOLFSSL_CALLBACKS
-    if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo);
-    if (ssl->toInfoOn) {
-        AddPacketInfo("ClientHello", &ssl->timeoutInfo, output, sendSz,
-                      ssl->heap);
-    }
-#endif
-
-    ssl->buffers.outputBuffer.length += sendSz;
-
-    ret = SendBuffered(ssl);
-
-    WOLFSSL_LEAVE("SendTls13ClientHello", ret);
-
-    return ret;
-}
+
+    return 0;
+}
+#endif
 
 #ifndef WOLFSSL_TLS13_DRAFT_18
-#ifdef WOLFSSL_SEND_HRR_COOKIE
+#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
 /* Create Cookie extension using the hash of the first ClientHello.
  *
@@ -2315,5 +2206,5 @@
 {
     int  ret;
-    byte mac[MAX_DIGEST_SIZE];
+    byte mac[WC_MAX_DIGEST_SIZE];
     Hmac cookieHmac;
     byte cookieType;
@@ -2383,7 +2274,7 @@
     WOLFSSL_BUFFER(hash, hashSz);
 
-#ifdef WOLFSSL_SEND_HRR_COOKIE
+#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
     if (ssl->options.sendCookie) {
-        byte   cookie[OPAQUE8_LEN + MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
+        byte   cookie[OPAQUE8_LEN + WC_MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
         TLSX*  ext;
         word32 idx = 0;
@@ -2412,6 +2303,388 @@
     return HashOutputRaw(ssl, hash, hashSz);
 }
-#endif
-
+
+/* The value in the random field of a ServerHello to indicate
+ * HelloRetryRequest.
+ */
+static byte helloRetryRequestRandom[] = {
+    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
+    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
+    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
+    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
+};
+#endif /* WOLFSSL_TLS13_DRAFT_18 */
+
+#ifndef NO_WOLFSSL_CLIENT
+#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+/* Setup pre-shared key based on the details in the extension data.
+ *
+ * ssl  SSL/TLS object.
+ * psk  Pre-shared key extension data.
+ * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
+ * other negative value on failure.
+ */
+static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk)
+{
+    int ret;
+    byte suite[2];
+
+    if (ssl->options.noPskDheKe && ssl->arrays->preMasterSz != 0)
+        return PSK_KEY_ERROR;
+
+    suite[0] = psk->cipherSuite0;
+    suite[1] = psk->cipherSuite;
+    if (!FindSuite(ssl, suite))
+        return PSK_KEY_ERROR;
+
+    ssl->options.cipherSuite0 = psk->cipherSuite0;
+    ssl->options.cipherSuite  = psk->cipherSuite;
+    if ((ret = SetCipherSpecs(ssl)) != 0)
+        return ret;
+
+#ifdef HAVE_SESSION_TICKET
+    if (psk->resumption) {
+    #ifdef WOLFSSL_EARLY_DATA
+        if (ssl->session.maxEarlyDataSz == 0)
+            ssl->earlyData = no_early_data;
+    #endif
+        /* Resumption PSK is master secret. */
+        ssl->arrays->psk_keySz = ssl->specs.hash_size;
+#ifdef WOLFSSL_TLS13_DRAFT_18
+        XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
+                ssl->arrays->psk_keySz);
+#else
+        if ((ret = DeriveResumptionPSK(ssl, ssl->session.ticketNonce.data,
+                    ssl->session.ticketNonce.len, ssl->arrays->psk_key)) != 0) {
+            return ret;
+        }
+#endif
+    }
+#endif
+#ifndef NO_PSK
+    if (!psk->resumption) {
+        const char* cipherName = NULL;
+        byte cipherSuite0 = TLS13_BYTE, cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
+
+        /* Get the pre-shared key. */
+        if (ssl->options.client_psk_tls13_cb != NULL) {
+            ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(ssl,
+                    (char *)psk->identity, ssl->arrays->client_identity,
+                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
+                    &cipherName);
+            if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
+                                                           &cipherSuite) != 0) {
+                return PSK_KEY_ERROR;
+            }
+        }
+        else {
+        ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
+                (char *)psk->identity, ssl->arrays->client_identity,
+                MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
+        }
+        if (ssl->arrays->psk_keySz == 0 ||
+                                 ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
+            return PSK_KEY_ERROR;
+        }
+
+        if (psk->cipherSuite0 != cipherSuite0 ||
+                                              psk->cipherSuite != cipherSuite) {
+            return PSK_KEY_ERROR;
+        }
+    }
+#endif
+
+    /* Derive the early secret using the PSK. */
+    return DeriveEarlySecret(ssl);
+}
+
+/* Derive and write the binders into the ClientHello in space left when
+ * writing the Pre-Shared Key extension.
+ *
+ * ssl     The SSL/TLS object.
+ * output  The buffer containing the ClientHello.
+ * idx     The index at the end of the completed ClientHello.
+ * returns 0 on success and otherwise failure.
+ */
+static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
+{
+    int           ret;
+    TLSX*         ext;
+    PreSharedKey* current;
+    byte          binderKey[WC_MAX_DIGEST_SIZE];
+    word16        len;
+
+    WOLFSSL_ENTER("WritePSKBinders");
+
+    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
+    if (ext == NULL)
+        return SANITY_MSG_E;
+
+    /* Get the size of the binders to determine where to write binders. */
+    idx -= TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
+                                            client_hello);
+
+    /* Hash truncated ClientHello - up to binders. */
+    ret = HashOutput(ssl, output, idx, 0);
+    if (ret != 0)
+        return ret;
+
+    current = (PreSharedKey*)ext->data;
+    /* Calculate the binder for each identity based on previous handshake data.
+     */
+    while (current != NULL) {
+        if ((ret = SetupPskKey(ssl, current)) != 0)
+            return ret;
+
+    #ifdef HAVE_SESSION_TICKET
+        if (current->resumption)
+            ret = DeriveBinderKeyResume(ssl, binderKey);
+    #endif
+    #ifndef NO_PSK
+        if (!current->resumption)
+            ret = DeriveBinderKey(ssl, binderKey);
+    #endif
+        if (ret != 0)
+            return ret;
+
+        /* Derive the Finished message secret. */
+        ret = DeriveFinishedSecret(ssl, binderKey,
+                                             ssl->keys.client_write_MAC_secret);
+        if (ret != 0)
+            return ret;
+
+        /* Build the HMAC of the handshake message data = binder. */
+        ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
+            current->binder, &current->binderLen);
+        if (ret != 0)
+            return ret;
+
+        current = current->next;
+    }
+
+    /* Data entered into extension, now write to message. */
+    len = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
+                                         client_hello);
+
+    /* Hash binders to complete the hash of the ClientHello. */
+    ret = HashOutputRaw(ssl, output + idx, len);
+    if (ret < 0)
+        return ret;
+
+    #ifdef WOLFSSL_EARLY_DATA
+    if (ssl->earlyData != no_early_data) {
+        if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data)) != 0)
+            return ret;
+
+        /* Derive early data encryption key. */
+        ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
+        if (ret != 0)
+            return ret;
+        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
+            return ret;
+    }
+    #endif
+
+    WOLFSSL_LEAVE("WritePSKBinders", ret);
+
+    return ret;
+}
+#endif
+
+/* handle generation of TLS 1.3 client_hello (1) */
+/* Send a ClientHello message to the server.
+ * Include the information required to start a handshake with servers using
+ * protocol versions less than TLS v1.3.
+ * Only a client will send this message.
+ *
+ * ssl  The SSL/TLS object.
+ * returns 0 on success and otherwise failure.
+ */
+int SendTls13ClientHello(WOLFSSL* ssl)
+{
+    byte*  output;
+    word16 length;
+    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
+    int    sendSz;
+    int    ret;
+
+    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
+    WOLFSSL_ENTER("SendTls13ClientHello");
+
+#ifdef HAVE_SESSION_TICKET
+    if (ssl->options.resuming &&
+            (ssl->session.version.major != ssl->version.major ||
+             ssl->session.version.minor != ssl->version.minor)) {
+    #ifndef WOLFSSL_NO_TLS12
+        if (ssl->session.version.major == ssl->version.major &&
+            ssl->session.version.minor < ssl->version.minor) {
+            /* Cannot resume with a different protocol version. */
+        ssl->options.resuming = 0;
+        ssl->version.major = ssl->session.version.major;
+        ssl->version.minor = ssl->session.version.minor;
+        return SendClientHello(ssl);
+    }
+        else
+    #endif
+            return VERSION_ERROR;
+    }
+#endif
+
+    if (ssl->suites == NULL) {
+        WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
+        return SUITES_ERROR;
+    }
+
+    /* Version | Random | Session Id | Cipher Suites | Compression */
+    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
+             SUITE_LEN + COMP_LEN + ENUM_LEN;
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
+    length += ID_LEN;
+    #else
+    if (ssl->session.sessionIDSz > 0)
+        length += ssl->session.sessionIDSz;
+    #endif
+#endif
+
+    /* Auto populate extensions supported unless user defined. */
+    if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
+        return ret;
+#ifdef WOLFSSL_EARLY_DATA
+    #ifndef NO_PSK
+        if (!ssl->options.resuming &&
+                                     ssl->options.client_psk_tls13_cb == NULL &&
+                                     ssl->options.client_psk_cb == NULL)
+    #else
+        if (!ssl->options.resuming)
+    #endif
+            ssl->earlyData = no_early_data;
+    if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
+        ssl->earlyData = no_early_data;
+    if (ssl->earlyData == no_early_data)
+        TLSX_Remove(&ssl->extensions, TLSX_EARLY_DATA, ssl->heap);
+    if (ssl->earlyData != no_early_data &&
+                                       (ret = TLSX_EarlyData_Use(ssl, 0)) < 0) {
+        return ret;
+    }
+#endif
+#ifdef HAVE_QSH
+    if (QSH_Init(ssl) != 0)
+        return MEMORY_E;
+#endif
+    /* Include length of TLS extensions. */
+    ret = TLSX_GetRequestSize(ssl, client_hello, &length);
+    if (ret != 0)
+        return ret;
+
+    /* Total message size. */
+    sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
+
+    /* Check buffers are big enough and grow if needed. */
+    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
+        return ret;
+
+    /* Get position in output buffer to write new message to. */
+    output = ssl->buffers.outputBuffer.buffer +
+             ssl->buffers.outputBuffer.length;
+
+    /* Put the record and handshake headers on. */
+    AddTls13Headers(output, length, client_hello, ssl);
+
+    /* Protocol version - negotiation now in extension: supported_versions. */
+    output[idx++] = SSLv3_MAJOR;
+    output[idx++] = TLSv1_2_MINOR;
+    /* Keep for downgrade. */
+    ssl->chVersion = ssl->version;
+
+    /* Client Random */
+    if (ssl->options.connectState == CONNECT_BEGIN) {
+        ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
+        if (ret != 0)
+            return ret;
+
+        /* Store random for possible second ClientHello. */
+        XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
+    }
+    else
+        XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
+    idx += RAN_LEN;
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
+    /* TLS v1.3 does not use session id - 0 length. */
+    output[idx++] = 0;
+#else
+    if (ssl->session.sessionIDSz > 0) {
+        /* Session resumption for old versions of protocol. */
+        output[idx++] = ID_LEN;
+        XMEMCPY(output + idx, ssl->session.sessionID, ssl->session.sessionIDSz);
+        idx += ID_LEN;
+    }
+    else {
+    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
+        output[idx++] = ID_LEN;
+        XMEMCPY(output + idx, ssl->arrays->clientRandom, ID_LEN);
+        idx += ID_LEN;
+    #else
+    /* TLS v1.3 does not use session id - 0 length. */
+    output[idx++] = 0;
+    #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
+    }
+#endif /* WOLFSSL_TLS13_DRAFT_18 */
+
+    /* Cipher suites */
+    c16toa(ssl->suites->suiteSz, output + idx);
+    idx += OPAQUE16_LEN;
+    XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz);
+    idx += ssl->suites->suiteSz;
+
+    /* Compression not supported in TLS v1.3. */
+    output[idx++] = COMP_LEN;
+    output[idx++] = NO_COMPRESSION;
+
+    /* Write out extensions for a request. */
+    length = 0;
+    ret = TLSX_WriteRequest(ssl, output + idx, client_hello, &length);
+    if (ret != 0)
+        return ret;
+    idx += length;
+
+#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+    /* Resumption has a specific set of extensions and binder is calculated
+     * for each identity.
+     */
+    if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY))
+        ret = WritePSKBinders(ssl, output, idx);
+    else
+#endif
+        ret = HashOutput(ssl, output, idx, 0);
+    if (ret != 0)
+        return ret;
+
+    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
+
+#ifdef WOLFSSL_CALLBACKS
+    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
+    if (ssl->toInfoOn) {
+        AddPacketInfo(ssl, "ClientHello", handshake, output, sendSz,
+                      WRITE_PROTO, ssl->heap);
+    }
+#endif
+
+    ssl->buffers.outputBuffer.length += sendSz;
+
+#ifdef WOLFSSL_EARLY_DATA_GROUP
+    if (ssl->earlyData == no_early_data)
+#endif
+    ret = SendBuffered(ssl);
+
+
+    WOLFSSL_LEAVE("SendTls13ClientHello", ret);
+    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
+
+    return ret;
+}
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
+/* handle rocessing of TLS 1.3 hello_retry_request (6) */
 /* Parse and handle a HelloRetryRequest message.
  * Only a client will receive this message.
@@ -2437,5 +2710,5 @@
 
 #ifdef WOLFSSL_CALLBACKS
-    if (ssl->hsInfoOn) AddPacketName("HelloRetryRequest", &ssl->handShakeInfo);
+    if (ssl->hsInfoOn) AddPacketName(ssl, "HelloRetryRequest");
     if (ssl->toInfoOn) AddLateName("HelloRetryRequest", &ssl->timeoutInfo);
 #endif
@@ -2451,14 +2724,4 @@
     if (ret != 0)
         return ret;
-
-#ifndef WOLFSSL_TLS13_DRAFT_18
-    /* Set the cipher suite from the message. */
-    ssl->options.cipherSuite0 = input[i++];
-    ssl->options.cipherSuite  = input[i++];
-
-    ret = SetCipherSpecs(ssl);
-    if (ret != 0)
-        return ret;
-#endif
 
     /* Length of extension data. */
@@ -2482,9 +2745,5 @@
 
     ssl->options.tls1_3 = 1;
-    ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST;
-
-#ifndef WOLFSSL_TLS13_DRAFT_18
-    ret = RestartHandshakeHash(ssl);
-#endif
+    ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
 
     WOLFSSL_LEAVE("DoTls13HelloRetryRequest", ret);
@@ -2492,5 +2751,8 @@
     return ret;
 }
-
+#endif
+
+
+/* handle processing of TLS 1.3 server_hello (2) and hello_retry_request (6) */
 /* Handle the ServerHello message from the server.
  * Only a client will receive this message.
@@ -2504,5 +2766,5 @@
  */
 int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
-                       word32 helloSz)
+                       word32 helloSz, byte* extMsgType)
 {
     ProtocolVersion pv;
@@ -2510,4 +2772,9 @@
     word32          begin = i;
     int             ret;
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    byte            sessIdSz;
+    const byte*     sessId;
+    byte            b;
+#endif
     word16          totalExtSz;
 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
@@ -2516,8 +2783,9 @@
 #endif
 
+    WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
     WOLFSSL_ENTER("DoTls13ServerHello");
 
 #ifdef WOLFSSL_CALLBACKS
-    if (ssl->hsInfoOn) AddPacketName("ServerHello", &ssl->handShakeInfo);
+    if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
     if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
 #endif
@@ -2530,20 +2798,45 @@
     XMEMCPY(&pv, input + i, OPAQUE16_LEN);
     i += OPAQUE16_LEN;
+#ifdef WOLFSSL_TLS13_DRAFT_18
     ret = CheckVersion(ssl, pv);
     if (ret != 0)
         return ret;
     if (!IsAtLeastTLSv1_3(pv) && pv.major != TLS_DRAFT_MAJOR) {
+#ifndef WOLFSSL_NO_TLS12
         if (ssl->options.downgrade) {
             ssl->version = pv;
             return DoServerHello(ssl, input, inOutIdx, helloSz);
         }
-
-        WOLFSSL_MSG("CLient using higher version, fatal error");
+#endif
+
+        WOLFSSL_MSG("Client using higher version, fatal error");
         return VERSION_ERROR;
     }
-
-    /* Random, cipher suite and extensions length check. */
-    if ((i - begin) + RAN_LEN + OPAQUE16_LEN + OPAQUE16_LEN > helloSz)
+#else
+#ifndef WOLFSSL_NO_TLS12
+    if (pv.major == ssl->version.major  && pv.minor < TLSv1_2_MINOR &&
+                                                       ssl->options.downgrade) {
+        /* Force client hello version 1.2 to work for static RSA. */
+        ssl->chVersion.minor = TLSv1_2_MINOR;
+        ssl->version.minor = TLSv1_2_MINOR;
+        return DoServerHello(ssl, input, inOutIdx, helloSz);
+    }
+#endif
+    if (pv.major != ssl->version.major || pv.minor != TLSv1_2_MINOR)
+        return VERSION_ERROR;
+#endif
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
+    /* Random length check */
+    if ((i - begin) + RAN_LEN > helloSz)
         return BUFFER_ERROR;
+#else
+    /* Random and session id length check */
+    if ((i - begin) + RAN_LEN + ENUM_LEN > helloSz)
+        return BUFFER_ERROR;
+
+    if (XMEMCMP(input + i, helloRetryRequestRandom, RAN_LEN) == 0)
+        *extMsgType = hello_retry_request;
+#endif
 
     /* Server random - keep for debugging. */
@@ -2551,9 +2844,52 @@
     i += RAN_LEN;
 
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    /* Session id */
+    sessIdSz = input[i++];
+    if ((i - begin) + sessIdSz > helloSz)
+        return BUFFER_ERROR;
+    sessId = input + i;
+    i += sessIdSz;
+#endif /* WOLFSSL_TLS13_DRAFT_18 */
+    ssl->options.haveSessionId = 1;
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
+    /* Ciphersuite check */
+    if ((i - begin) + OPAQUE16_LEN + OPAQUE16_LEN > helloSz)
+        return BUFFER_ERROR;
+#else
+    /* Ciphersuite and compression check */
+    if ((i - begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
+        return BUFFER_ERROR;
+#endif
+
     /* Set the cipher suite from the message. */
     ssl->options.cipherSuite0 = input[i++];
     ssl->options.cipherSuite  = input[i++];
 
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    /* Compression */
+    b = input[i++];
+    if (b != 0) {
+        WOLFSSL_MSG("Must be no compression types in list");
+        return INVALID_PARAMETER;
+    }
+#endif
+
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    if ((i - begin) + OPAQUE16_LEN > helloSz) {
+        if (!ssl->options.downgrade)
+            return BUFFER_ERROR;
+#ifndef WOLFSSL_NO_TLS12
+        ssl->version.minor = TLSv1_2_MINOR;
+#endif
+        ssl->options.haveEMS = 0;
+    }
+    if ((i - begin) < helloSz)
+#endif
+    {
     /* Get extension length and length check. */
+        if ((i - begin) + OPAQUE16_LEN > helloSz)
+            return BUFFER_ERROR;
     ato16(&input[i], &totalExtSz);
     i += OPAQUE16_LEN;
@@ -2561,10 +2897,16 @@
         return BUFFER_ERROR;
 
+#ifndef WOLFSSL_TLS13_DRAFT_18
+        if (ssl->options.downgrade)
+            ssl->version.minor = TLSv1_2_MINOR;
+#endif
     /* Parse and handle extensions. */
-    ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz, server_hello, NULL);
+        ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz, *extMsgType,
+                                                                          NULL);
     if (ret != 0)
         return ret;
 
     i += totalExtSz;
+    }
     *inOutIdx = i;
 
@@ -2581,4 +2923,56 @@
 #endif /* HAVE_SECRET_CALLBACK */
 
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    /* Version only negotiated in extensions for TLS v1.3.
+     * Only now do we know how to deal with session id.
+     */
+    if (!IsAtLeastTLSv1_3(ssl->version)) {
+#ifndef WOLFSSL_NO_TLS12
+        ssl->arrays->sessionIDSz = sessIdSz;
+
+        if (ssl->arrays->sessionIDSz > ID_LEN) {
+            WOLFSSL_MSG("Invalid session ID size");
+            ssl->arrays->sessionIDSz = 0;
+            return BUFFER_ERROR;
+        }
+        else if (ssl->arrays->sessionIDSz) {
+            XMEMCPY(ssl->arrays->sessionID, sessId, ssl->arrays->sessionIDSz);
+            ssl->options.haveSessionId = 1;
+        }
+
+        /* Force client hello version 1.2 to work for static RSA. */
+        ssl->chVersion.minor = TLSv1_2_MINOR;
+        /* Complete TLS v1.2 processing of ServerHello. */
+        ret = CompleteServerHello(ssl);
+#else
+        WOLFSSL_MSG("Client using higher version, fatal error");
+        ret = VERSION_ERROR;
+#endif
+
+        WOLFSSL_LEAVE("DoTls13ServerHello", ret);
+
+        return ret;
+    }
+
+    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
+    if (sessIdSz == 0)
+        return INVALID_PARAMETER;
+    if (ssl->session.sessionIDSz != 0) {
+        if (ssl->session.sessionIDSz != sessIdSz ||
+                   XMEMCMP(ssl->session.sessionID, sessId, sessIdSz) != 0) {
+            return INVALID_PARAMETER;
+        }
+    }
+    else if (XMEMCMP(ssl->arrays->clientRandom, sessId, sessIdSz) != 0)
+        return INVALID_PARAMETER;
+    #else
+    if (sessIdSz != ssl->session.sessionIDSz || (sessIdSz > 0 &&
+                  XMEMCMP(ssl->session.sessionID, sessId, sessIdSz) != 0)) {
+        WOLFSSL_MSG("Server sent different session id");
+        return INVALID_PARAMETER;
+    }
+    #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
+#endif
+
     ret = SetCipherSpecs(ssl);
     if (ret != 0)
@@ -2586,4 +2980,8 @@
 
 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    if (*extMsgType == server_hello)
+#endif
+    {
     ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
     if (ext != NULL)
@@ -2598,13 +2996,29 @@
     else if ((ret = SetupPskKey(ssl, psk)) != 0)
         return ret;
-#endif
-
+    }
+#endif
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
     ssl->keys.encryptionOn = 1;
+#else
+    if (*extMsgType == server_hello) {
+    ssl->keys.encryptionOn = 1;
+        ssl->options.serverState = SERVER_HELLO_COMPLETE;
+    }
+    else {
+        ssl->options.tls1_3 = 1;
+        ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
+
+        ret = RestartHandshakeHash(ssl);
+    }
+#endif
 
     WOLFSSL_LEAVE("DoTls13ServerHello", ret);
+    WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
 
     return ret;
 }
 
+/* handle processing TLS 1.3 encrypted_extensions (8) */
 /* Parse and handle an EncryptedExtensions message.
  * Only a client will receive this message.
@@ -2627,9 +3041,9 @@
     word16 totalExtSz;
 
+    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
     WOLFSSL_ENTER("DoTls13EncryptedExtensions");
 
 #ifdef WOLFSSL_CALLBACKS
-    if (ssl->hsInfoOn) AddPacketName("EncryptedExtensions",
-                                     &ssl->handShakeInfo);
+    if (ssl->hsInfoOn) AddPacketName(ssl, "EncryptedExtensions");
     if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
 #endif
@@ -2655,16 +3069,28 @@
 
 #ifdef WOLFSSL_EARLY_DATA
-    if (ssl->earlyData) {
+    if (ssl->earlyData != no_early_data) {
         TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
         if (ext == NULL || !ext->val)
-            ssl->earlyData = 0;
-    }
-#endif
+            ssl->earlyData = no_early_data;
+    }
+#endif
+
+#ifdef WOLFSSL_EARLY_DATA
+    if (ssl->earlyData == no_early_data) {
+        ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
+        if (ret != 0)
+            return ret;
+    }
+#endif
+
+    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
 
     WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
+    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
 
     return ret;
 }
 
+/* handle processing TLS v1.3 certificate_request (13) */
 /* Handle a TLS v1.3 CertificateRequest message.
  * This message is always encrypted.
@@ -2691,8 +3117,9 @@
 #endif
 
+    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
     WOLFSSL_ENTER("DoTls13CertificateRequest");
 
 #ifdef WOLFSSL_CALLBACKS
-    if (ssl->hsInfoOn) AddPacketName("CertificateRequest", &ssl->handShakeInfo);
+    if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateRequest");
     if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
 #endif
@@ -2799,15 +3226,6 @@
     *inOutIdx += ssl->keys.padSz;
 
-#if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
-    if (ssl->options.side == WOLFSSL_CLIENT_END &&
-                                ssl->options.handShakeState == HANDSHAKE_DONE) {
-        /* reset handshake states */
-        ssl->options.clientState = CLIENT_HELLO_COMPLETE;
-        ssl->options.connectState  = FIRST_REPLY_DONE;
-        ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
-    }
-#endif
-
     WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
+    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
 
     return ret;
@@ -2818,4 +3236,29 @@
 #ifndef NO_WOLFSSL_SERVER
 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+/* Refine list of supported cipher suites to those common to server and client.
+ *
+ * ssl         SSL/TLS object.
+ * peerSuites  The peer's advertised list of supported cipher suites.
+ */
+static void RefineSuites(WOLFSSL* ssl, Suites* peerSuites)
+{
+    byte suites[WOLFSSL_MAX_SUITE_SZ];
+    int suiteSz = 0;
+    int i, j;
+
+    for (i = 0; i < ssl->suites->suiteSz; i += 2) {
+        for (j = 0; j < peerSuites->suiteSz; j += 2) {
+            if (ssl->suites->suites[i+0] == peerSuites->suites[j+0] &&
+                ssl->suites->suites[i+1] == peerSuites->suites[j+1]) {
+                suites[suiteSz++] = peerSuites->suites[j+0];
+                suites[suiteSz++] = peerSuites->suites[j+1];
+            }
+        }
+    }
+
+    ssl->suites->suiteSz = suiteSz;
+    XMEMCPY(ssl->suites->suites, &suites, sizeof(suites));
+}
+
 /* Handle any Pre-Shared Key (PSK) extension.
  * Must do this in ClientHello as it requires a hash of the truncated message.
@@ -2835,17 +3278,25 @@
     word16        bindersLen;
     PreSharedKey* current;
-    byte          binderKey[MAX_DIGEST_SIZE];
-    byte          binder[MAX_DIGEST_SIZE];
+    byte          binderKey[WC_MAX_DIGEST_SIZE];
+    byte          binder[WC_MAX_DIGEST_SIZE];
     word32        binderLen;
     word16        modes;
+    byte          suite[2];
 #ifdef WOLFSSL_EARLY_DATA
     int           pskCnt = 0;
     TLSX*         extEarlyData;
 #endif
+#ifndef NO_PSK
+    const char*   cipherName = NULL;
+    byte          cipherSuite0 = TLS13_BYTE;
+    byte          cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
+#endif
+
+    WOLFSSL_ENTER("DoPreSharedKeys");
 
     ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
     if (ext == NULL) {
 #ifdef WOLFSSL_EARLY_DATA
-        ssl->earlyData = 0;
+        ssl->earlyData = no_early_data;
 #endif
         return 0;
@@ -2905,4 +3356,14 @@
             }
 
+            /* Check whether resumption is possible based on suites in SSL and
+             * ciphersuite in ticket.
+             */
+            suite[0] = ssl->session.cipherSuite0;
+            suite[1] = ssl->session.cipherSuite;
+            if (!FindSuite(ssl, suite)) {
+                current = current->next;
+                continue;
+            }
+
         #ifdef WOLFSSL_EARLY_DATA
             ssl->options.maxEarlyDataSz = ssl->session.maxEarlyDataSz;
@@ -2917,6 +3378,13 @@
             /* Resumption PSK is resumption master secret. */
             ssl->arrays->psk_keySz = ssl->specs.hash_size;
+        #ifdef WOLFSSL_TLS13_DRAFT_18
             XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
-                    ssl->specs.hash_size);
+                    ssl->arrays->psk_keySz);
+        #else
+            if ((ret = DeriveResumptionPSK(ssl, ssl->session.ticketNonce.data,
+                    ssl->session.ticketNonce.len, ssl->arrays->psk_key)) != 0) {
+                return ret;
+            }
+        #endif
 
             /* Derive the early secret using the PSK. */
@@ -2932,11 +3400,26 @@
     #endif
     #ifndef NO_PSK
-        if (ssl->options.server_psk_cb != NULL &&
+        if ((ssl->options.server_psk_tls13_cb != NULL &&
+             (ssl->arrays->psk_keySz = ssl->options.server_psk_tls13_cb(ssl,
+                             ssl->arrays->client_identity, ssl->arrays->psk_key,
+                             MAX_PSK_KEY_LEN, &cipherName)) != 0 && 
+             GetCipherSuiteFromName(cipherName, &cipherSuite0,
+                                                          &cipherSuite) == 0) ||
+            (ssl->options.server_psk_cb != NULL &&
             (ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
                              ssl->arrays->client_identity, ssl->arrays->psk_key,
-                             MAX_PSK_KEY_LEN)) != 0) {
+                             MAX_PSK_KEY_LEN)) != 0)) {
             if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN)
                 return PSK_KEY_ERROR;
 
+            /* Check whether PSK ciphersuite is in SSL. */
+            suite[0] = cipherSuite0;
+            suite[1] = cipherSuite;
+            if (!FindSuite(ssl, suite)) {
+                current = current->next;
+                continue;
+            }
+
+            /* Default to ciphersuite if cb doesn't specify. */
             ssl->options.resuming = 0;
 
@@ -2945,8 +3428,7 @@
                 return PSK_KEY_ERROR;
 
-            /* TODO: Callback should be able to change ciphersuite. */
-            /* Default to ciphersuite if cb doesn't specify. */
-            ssl->options.cipherSuite0 = TLS13_BYTE;
-            ssl->options.cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
+            /* Set PSK ciphersuite into SSL. */
+            ssl->options.cipherSuite0 = cipherSuite0;
+            ssl->options.cipherSuite  = cipherSuite;
             ret = SetCipherSpecs(ssl);
             if (ret != 0)
@@ -2993,4 +3475,16 @@
     }
 
+    if (current == NULL) {
+#ifdef WOLFSSL_PSK_ID_PROTECTION
+    #ifndef NO_CERTS
+        if (ssl->buffers.certChainCnt != 0)
+            return 0;
+    #endif
+        return BAD_BINDER;
+#else
+        return 0;
+#endif
+    }
+
     /* Hash the rest of the ClientHello. */
     ret = HashInputRaw(ssl, input + helloSz - bindersLen, bindersLen);
@@ -3001,5 +3495,5 @@
     extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
     if (extEarlyData != NULL) {
-        if (ssl->earlyData && current == ext->data) {
+        if (ssl->earlyData != no_early_data && current == ext->data) {
             extEarlyData->resp = 1;
 
@@ -3011,5 +3505,5 @@
                 return ret;
 
-            ssl->earlyData = 2;
+            ssl->earlyData = process_early_data;
         }
         else
@@ -3031,8 +3525,10 @@
         ssl->namedGroup = ssl->session.namedGroup;
 
-        /* Try to establish a new secret. */
+        /* Pick key share and Generate a new key if not present. */
         ret = TLSX_KeyShare_Establish(ssl);
-        if (ret == KEY_SHARE_ERROR)
-            return PSK_KEY_ERROR;
+        if (ret == KEY_SHARE_ERROR) {
+            ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
+            ret = 0;
+        }
         else if (ret < 0)
             return ret;
@@ -3041,8 +3537,13 @@
         ext->resp = 1;
     }
-    else if ((modes & (1 << PSK_KE)) == 0)
+    else {
+        if ((modes & (1 << PSK_KE)) == 0)
         return PSK_KEY_ERROR;
+        ssl->options.noPskDheKe = 1;
+    }
 
     *usingPSK = 1;
+
+    WOLFSSL_LEAVE("DoPreSharedKeys", ret);
 
     return ret;
@@ -3061,5 +3562,5 @@
 {
     int  ret;
-    byte mac[MAX_DIGEST_SIZE];
+    byte mac[WC_MAX_DIGEST_SIZE];
     Hmac cookieHmac;
     byte cookieType;
@@ -3096,6 +3597,9 @@
 /* Length of the KeyShare Extension */
 #define HRR_KEY_SHARE_SZ   (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
+/* Length of the Supported Vresions Extension */
+#define HRR_VERSIONS_SZ    (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
 /* Length of the Cookie Extension excluding cookie data */
 #define HRR_COOKIE_HDR_SZ  (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
+#ifdef WOLFSSL_TLS13_DRAFT_18
 /* PV | CipherSuite | Ext Len */
 #define HRR_BODY_SZ        (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
@@ -3105,4 +3609,16 @@
                           HRR_KEY_SHARE_SZ + \
                           HRR_COOKIE_HDR_SZ)
+#else
+/* PV | Random | Session Id | CipherSuite | Compression | Ext Len */
+#define HRR_BODY_SZ        (VERSION_SZ + RAN_LEN + ENUM_LEN + ID_LEN + \
+                            SUITE_LEN + COMP_LEN + OPAQUE16_LEN)
+/* HH | PV | CipherSuite | Ext Len | Key Share | Supported Version | Cookie */
+#define MAX_HRR_SZ   (HANDSHAKE_HEADER_SZ   + \
+                        HRR_BODY_SZ         + \
+                          HRR_KEY_SHARE_SZ  + \
+                          HRR_VERSIONS_SZ   + \
+                          HRR_COOKIE_HDR_SZ)
+#endif
+
 /* Restart the Hanshake hash from the cookie value.
  *
@@ -3141,20 +3657,20 @@
 
     /* Reconstruct the HelloRetryMessage for handshake hash. */
+#ifdef WOLFSSL_TLS13_DRAFT_18
     length = HRR_BODY_SZ + HRR_COOKIE_HDR_SZ + cookie->len;
+#else
+    length = HRR_BODY_SZ - ID_LEN + ssl->session.sessionIDSz +
+             HRR_COOKIE_HDR_SZ + cookie->len;
+    length += HRR_VERSIONS_SZ;
+#endif
     if (cookieDataSz > hashSz + OPAQUE16_LEN) {
         keyShareExt = 1;
         length += HRR_KEY_SHARE_SZ;
     }
+#ifdef WOLFSSL_TLS13_DRAFT_18
     AddTls13HandShakeHeader(hrr, length, 0, 0, hello_retry_request, ssl);
 
     idx += hashSz;
     hrrIdx = HANDSHAKE_HEADER_SZ;
-    /* TODO: [TLS13] Replace existing code with code in comment.
-     * Use the TLS v1.3 draft version for now.
-     *
-     * Change to:
-     * hrr[hrrIdx++] = ssl->version.major;
-     * hrr[hrrIdx++] = ssl->version.minor;
-     */
     /* The negotiated protocol version. */
     hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
@@ -3168,4 +3684,37 @@
     c16toa(length, hrr + hrrIdx);
     hrrIdx += 2;
+#else
+    AddTls13HandShakeHeader(hrr, length, 0, 0, server_hello, ssl);
+
+    idx += hashSz;
+    hrrIdx = HANDSHAKE_HEADER_SZ;
+
+    /* The negotiated protocol version. */
+    hrr[hrrIdx++] = ssl->version.major;
+    hrr[hrrIdx++] = TLSv1_2_MINOR;
+
+    /* HelloRetryRequest message has fixed value for random. */
+    XMEMCPY(hrr + hrrIdx, helloRetryRequestRandom, RAN_LEN);
+    hrrIdx += RAN_LEN;
+
+    hrr[hrrIdx++] = ssl->session.sessionIDSz;
+    if (ssl->session.sessionIDSz > 0) {
+        XMEMCPY(hrr + hrrIdx, ssl->session.sessionID, ssl->session.sessionIDSz);
+        hrrIdx += ssl->session.sessionIDSz;
+    }
+
+    /* Cipher Suite */
+    hrr[hrrIdx++] = cookieData[idx++];
+    hrr[hrrIdx++] = cookieData[idx++];
+
+    /* Compression not supported in TLS v1.3. */
+    hrr[hrrIdx++] = 0;
+
+    /* Extensions' length */
+    length -= HRR_BODY_SZ - ID_LEN + ssl->session.sessionIDSz;
+    c16toa(length, hrr + hrrIdx);
+    hrrIdx += 2;
+
+#endif
     /* Optional KeyShare Extension */
     if (keyShareExt) {
@@ -3177,4 +3726,17 @@
         hrr[hrrIdx++] = cookieData[idx++];
     }
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    c16toa(TLSX_SUPPORTED_VERSIONS, hrr + hrrIdx);
+    hrrIdx += 2;
+    c16toa(OPAQUE16_LEN, hrr + hrrIdx);
+    hrrIdx += 2;
+    #ifdef WOLFSSL_TLS13_DRAFT
+        hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
+        hrr[hrrIdx++] = TLS_DRAFT_MINOR;
+    #else
+        hrr[hrrIdx++] = ssl->version.major;
+        hrr[hrrIdx++] = ssl->version.minor;
+    #endif
+#endif
     /* Mandatory Cookie Extension */
     c16toa(TLSX_COOKIE, hrr + hrrIdx);
@@ -3214,5 +3776,5 @@
                        word32 helloSz)
 {
-    int             ret;
+    int             ret = VERSION_ERROR;
     byte            b;
     ProtocolVersion pv;
@@ -3220,12 +3782,16 @@
     word32          i = *inOutIdx;
     word32          begin = i;
-    word16          totalExtSz;
+    word16          totalExtSz = 0;
     int             usingPSK = 0;
     byte            sessIdSz;
-
+#ifndef WOLFSSL_NO_TLS12
+    int             bogusID = 0;
+#endif
+
+    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
     WOLFSSL_ENTER("DoTls13ClientHello");
 
 #ifdef WOLFSSL_CALLBACKS
-    if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo);
+    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
     if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
 #endif
@@ -3239,7 +3805,19 @@
     ssl->chVersion = pv;   /* store */
     i += OPAQUE16_LEN;
-
+    /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
+    if (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR)
+        pv.minor = TLSv1_2_MINOR;
+
+#ifndef WOLFSSL_NO_TLS12
     if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor < TLSv1_3_MINOR)
         return DoClientHello(ssl, input, inOutIdx, helloSz);
+#endif
+
+#ifdef HAVE_SESSION_TICKET
+    if (ssl->options.downgrade) {
+       if ((ret = HashInput(ssl, input + begin, helloSz)) != 0)
+            return ret;
+    }
+#endif
 
     /* Client random */
@@ -3252,10 +3830,27 @@
 #endif
 
+#ifdef WOLFSSL_TLS13_DRAFT_18
     /* Session id - empty in TLS v1.3 */
     sessIdSz = input[i++];
-    if (sessIdSz > 0) {
+    if (sessIdSz > 0 && !ssl->options.downgrade) {
         WOLFSSL_MSG("Client sent session id - not supported");
         return BUFFER_ERROR;
     }
+#else
+    sessIdSz = input[i++];
+    if (sessIdSz != ID_LEN && sessIdSz != 0)
+        return INVALID_PARAMETER;
+#endif
+    ssl->session.sessionIDSz = sessIdSz;
+    if (sessIdSz == ID_LEN) {
+        XMEMCPY(ssl->session.sessionID, input + i, sessIdSz);
+        i += ID_LEN;
+    }
+#ifndef WOLFSSL_NO_TLS12
+    #ifdef HAVE_SESSION_TICKET
+        if (sessIdSz > 0 && sessIdSz < ID_LEN)
+            bogusID = 1;
+    #endif
+#endif
 
     /* Cipher suites */
@@ -3287,9 +3882,5 @@
     }
 
-    /* TLS v1.3 ClientHello messages will have extensions. */
-    if ((i - begin) >= helloSz) {
-        WOLFSSL_MSG("ClientHello must have extensions in TLS v1.3");
-        return BUFFER_ERROR;
-    }
+    if ((i - begin) < helloSz) {
     if ((i - begin) + OPAQUE16_LEN > helloSz)
         return BUFFER_ERROR;
@@ -3313,26 +3904,42 @@
     }
 
-#ifdef HAVE_STUNNEL
+#if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
+                                                        defined(WOLFSSL_HAPROXY)
     if ((ret = SNI_Callback(ssl)) != 0)
         return ret;
-#endif /*HAVE_STUNNEL*/
+        ssl->options.side = WOLFSSL_SERVER_END;
+#endif /* OPENSSL_ALL || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
+    }
+
+    i += totalExtSz;
+    *inOutIdx = i;
 
     if (TLSX_Find(ssl->extensions, TLSX_SUPPORTED_VERSIONS) == NULL) {
         if (!ssl->options.downgrade) {
-            WOLFSSL_MSG("Client trying to connect with lesser version");
+            WOLFSSL_MSG("Client trying to connect with lesser version than "
+                        "TLS v1.3");
             return VERSION_ERROR;
         }
+
+        if (pv.minor < ssl->options.minDowngrade)
+            return VERSION_ERROR;
         ssl->version.minor = pv.minor;
     }
 
-#ifdef WOLFSSL_SEND_HRR_COOKIE
+    ssl->options.sendVerify = SEND_CERT;
+
+    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
+    ssl->options.haveSessionId = 1;
+
+    if (IsAtLeastTLSv1_3(ssl->version)) {
+#if !defined(WOLFSSL_TLS13_DRAFT_18) && defined(WOLFSSL_SEND_HRR_COOKIE)
     if (ssl->options.sendCookie &&
-                       ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
+              ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
         TLSX* ext;
 
         if ((ext = TLSX_Find(ssl->extensions, TLSX_COOKIE)) == NULL)
             return HRR_COOKIE_ERROR;
-        /* Ensure the cookie came from client and isn't the one in the response
-         * - HelloRetryRequest.
+            /* Ensure the cookie came from client and isn't the one in the
+             * response - HelloRetryRequest.
          */
         if (ext->resp == 1)
@@ -3344,11 +3951,37 @@
 #endif
 
-    ssl->options.sendVerify = SEND_CERT;
-
 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+        if (ssl->options.downgrade) {
+            if ((ret = InitHandshakeHashes(ssl)) != 0)
+                return ret;
+        }
+
+        /* Refine list for PSK processing. */
+        RefineSuites(ssl, &clSuites);
+
     /* Process the Pre-Shared Key extension if present. */
     ret = DoPreSharedKeys(ssl, input + begin, helloSz, &usingPSK);
     if (ret != 0)
         return ret;
+#endif
+    }
+#ifndef WOLFSSL_NO_TLS12
+    else if (ssl->options.resuming) {
+        ret = HandleTlsResumption(ssl, bogusID, &clSuites);
+        if (ret != 0)
+            return ret;
+        /* Check wheter resuming has been chosen */
+        if (ssl->options.clientState == CLIENT_KEYEXCHANGE_COMPLETE) {
+            WOLFSSL_LEAVE("DoTls13ClientHello", ret);
+            WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
+
+            return ret;
+        }
+    }
+#else
+    else {
+        WOLFSSL_MSG("Negotiated lesser version than TLS v1.3");
+        return VERSION_ERROR;
+    }
 #endif
 
@@ -3358,4 +3991,14 @@
             return ret;
         }
+
+        /* Check that the negotiated ciphersuite matches protocol version. */
+        if (IsAtLeastTLSv1_3(ssl->version)) {
+            if (ssl->options.cipherSuite0 != TLS13_BYTE) {
+                WOLFSSL_MSG("Negotiated ciphersuite from lesser version than "
+                            "TLS v1.3");
+                return VERSION_ERROR;
+            }
+        }
+        /* VerifyServerSuite handles when version is less than 1.3 */
 
 #ifdef HAVE_SESSION_TICKET
@@ -3369,22 +4012,27 @@
 #endif
 
+#ifdef HAVE_SESSION_TICKET
+        if (IsAtLeastTLSv1_3(ssl->version) || !ssl->options.downgrade)
+#endif
+        {
         if ((ret = HashInput(ssl, input + begin,  helloSz)) != 0)
             return ret;
-
+        }
+
+        if (IsAtLeastTLSv1_3(ssl->version)) {
         /* Derive early secret for handshake secret. */
         if ((ret = DeriveEarlySecret(ssl)) != 0)
             return ret;
     }
-
-    i += totalExtSz;
-    *inOutIdx = i;
-
-    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
+    }
 
     WOLFSSL_LEAVE("DoTls13ClientHello", ret);
+    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
 
     return ret;
 }
 
+#ifdef WOLFSSL_TLS13_DRAFT_18
+/* handle generation of TLS 1.3 hello_retry_request (6) */
 /* Send the HelloRetryRequest message to indicate the negotiated protocol
  * version and security parameters the server is willing to use.
@@ -3399,5 +4047,5 @@
     byte*  output;
     word32 length;
-    word32 len;
+    word16 len;
     word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
     int    sendSz;
@@ -3405,22 +4053,13 @@
     WOLFSSL_ENTER("SendTls13HelloRetryRequest");
 
-#ifndef WOLFSSL_TLS13_DRAFT_18
-    if ((ret = RestartHandshakeHash(ssl)) < 0)
-        return ret;
-#endif
-
     /* Get the length of the extensions that will be written. */
-    len = TLSX_GetResponseSize(ssl, hello_retry_request);
+    len = 0;
+    ret = TLSX_GetResponseSize(ssl, hello_retry_request, &len);
     /* There must be extensions sent to indicate what client needs to do. */
-    if (len == 0)
+    if (ret != 0)
         return MISSING_HANDSHAKE_DATA;
 
-#ifndef WOLFSSL_TLS13_DRAFT_18
-    /* Protocol version + CipherSuite + Extensions */
-    length = OPAQUE16_LEN + OPAQUE16_LEN + len;
-#else
     /* Protocol version + Extensions */
     length = OPAQUE16_LEN + len;
-#endif
     sendSz = idx + length;
 
@@ -3435,108 +4074,144 @@
     AddTls13Headers(output, length, hello_retry_request, ssl);
 
-    /* TODO: [TLS13] Replace existing code with code in comment.
-     * Use the TLS v1.3 draft version for now.
-     *
-     * Change to:
-     * output[idx++] = ssl->version.major;
-     * output[idx++] = ssl->version.minor;
-     */
     /* The negotiated protocol version. */
     output[idx++] = TLS_DRAFT_MAJOR;
     output[idx++] = TLS_DRAFT_MINOR;
 
+    /* Add TLS extensions. */
+    ret = TLSX_WriteResponse(ssl, output + idx, hello_retry_request, NULL);
+    if (ret != 0)
+        return ret;
+    idx += len;
+
+#ifdef WOLFSSL_CALLBACKS
+    if (ssl->hsInfoOn)
+        AddPacketName(ssl, "HelloRetryRequest");
+    if (ssl->toInfoOn) {
+        AddPacketInfo(ssl, "HelloRetryRequest", handshake, output, sendSz,
+                      WRITE_PROTO, ssl->heap);
+    }
+#endif
+    if ((ret = HashOutput(ssl, output, idx, 0)) != 0)
+        return ret;
+
+    ssl->buffers.outputBuffer.length += sendSz;
+
+    if (!ssl->options.groupMessages)
+        ret = SendBuffered(ssl);
+
+    WOLFSSL_LEAVE("SendTls13HelloRetryRequest", ret);
+
+    return ret;
+}
+#endif /* WOLFSSL_TLS13_DRAFT_18 */
+
+/* Send TLS v1.3 ServerHello message to client.
+ * Only a server will send this message.
+ *
+ * ssl  The SSL/TLS object.
+ * returns 0 on success, otherwise failure.
+ */
+#ifdef WOLFSSL_TLS13_DRAFT_18
+static
+#endif
+/* handle generation of TLS 1.3 server_hello (2) */
+int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType)
+{
+    int    ret;
+    byte*  output;
+    word16 length;
+    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
+    int    sendSz;
+
+    WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
+    WOLFSSL_ENTER("SendTls13ServerHello");
+
 #ifndef WOLFSSL_TLS13_DRAFT_18
+    if (extMsgType == hello_retry_request) {
+        if ((ret = RestartHandshakeHash(ssl)) < 0)
+            return ret;
+    }
+#endif
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
+    /* Protocol version, server random, cipher suite and extensions. */
+    length = VERSION_SZ + RAN_LEN + SUITE_LEN;
+    ret = TLSX_GetResponseSize(ssl, server_hello, &length);
+    if (ret != 0)
+        return ret;
+#else
+    /* Protocol version, server random, session id, cipher suite, compression
+     * and extensions.
+     */
+    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->session.sessionIDSz +
+             SUITE_LEN + COMP_LEN;
+    ret = TLSX_GetResponseSize(ssl, extMsgType, &length);
+    if (ret != 0)
+        return ret;
+#endif
+    sendSz = idx + length;
+
+    /* Check buffers are big enough and grow if needed. */
+    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
+        return ret;
+
+    /* Get position in output buffer to write new message to. */
+    output = ssl->buffers.outputBuffer.buffer +
+             ssl->buffers.outputBuffer.length;
+
+    /* Put the record and handshake headers on. */
+    AddTls13Headers(output, length, server_hello, ssl);
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
+    /* The negotiated protocol version. */
+    output[idx++] = TLS_DRAFT_MAJOR;
+    output[idx++] = TLS_DRAFT_MINOR;
+#else
+    /* The protocol version must be TLS v1.2 for middleboxes. */
+    output[idx++] = ssl->version.major;
+    output[idx++] = TLSv1_2_MINOR;
+#endif
+
+    if (extMsgType == server_hello) {
+    /* Generate server random. */
+    if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
+        return ret;
+    }
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    else {
+        /* HelloRetryRequest message has fixed value for random. */
+        XMEMCPY(output + idx, helloRetryRequestRandom, RAN_LEN);
+    }
+#endif
+    /* Store in SSL for debugging. */
+    XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
+    idx += RAN_LEN;
+
+#ifdef WOLFSSL_DEBUG_TLS
+    WOLFSSL_MSG("Server random");
+    WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
+#endif
+
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    output[idx++] = ssl->session.sessionIDSz;
+    if (ssl->session.sessionIDSz > 0) {
+        XMEMCPY(output + idx, ssl->session.sessionID, ssl->session.sessionIDSz);
+        idx += ssl->session.sessionIDSz;
+    }
+#endif
+
     /* Chosen cipher suite */
     output[idx++] = ssl->options.cipherSuite0;
     output[idx++] = ssl->options.cipherSuite;
-#endif
-
-    /* Add TLS extensions. */
-    TLSX_WriteResponse(ssl, output + idx, hello_retry_request);
-    idx += len;
-
-#ifdef WOLFSSL_CALLBACKS
-    if (ssl->hsInfoOn)
-        AddPacketName("HelloRetryRequest", &ssl->handShakeInfo);
-    if (ssl->toInfoOn) {
-        AddPacketInfo("HelloRetryRequest", &ssl->timeoutInfo, output, sendSz,
-                      ssl->heap);
-    }
-#endif
-
-    if ((ret = HashOutput(ssl, output, idx, 0)) != 0)
-        return ret;
-
-    ssl->buffers.outputBuffer.length += sendSz;
-
-    if (!ssl->options.groupMessages)
-        ret = SendBuffered(ssl);
-
-    WOLFSSL_LEAVE("SendTls13HelloRetryRequest", ret);
-
-    return ret;
-}
-
-/* Send TLS v1.3 ServerHello message to client.
- * Only a server will send this message.
- *
- * ssl  The SSL/TLS object.
- * returns 0 on success, otherwise failure.
- */
-static int SendTls13ServerHello(WOLFSSL* ssl)
-{
-    byte*  output;
-    word32 length;
-    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
-    int    sendSz;
-    int    ret;
-
-    WOLFSSL_ENTER("SendTls13ServerHello");
-
-    /* Protocol version, server random, cipher suite and extensions. */
-    length = VERSION_SZ + RAN_LEN + SUITE_LEN +
-             TLSX_GetResponseSize(ssl, server_hello);
-    sendSz = idx + length;
-
-    /* Check buffers are big enough and grow if needed. */
-    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
-        return ret;
-
-    /* Get position in output buffer to write new message to. */
-    output = ssl->buffers.outputBuffer.buffer +
-             ssl->buffers.outputBuffer.length;
-
-    /* Put the record and handshake headers on. */
-    AddTls13Headers(output, length, server_hello, ssl);
-
-    /* TODO: [TLS13] Replace existing code with code in comment.
-     * Use the TLS v1.3 draft version for now.
-     *
-     * Change to:
-     * output[idx++] = ssl->version.major;
-     * output[idx++] = ssl->version.minor;
-     */
-    /* The negotiated protocol version. */
-    output[idx++] = TLS_DRAFT_MAJOR;
-    output[idx++] = TLS_DRAFT_MINOR;
-
-    /* Generate server random. */
-    if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
-        return ret;
-    /* Store in SSL for debugging. */
-    XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
-    idx += RAN_LEN;
-
-#ifdef WOLFSSL_DEBUG_TLS
-    WOLFSSL_MSG("Server random");
-    WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
-#endif
-
-    /* Chosen cipher suite */
-    output[idx++] = ssl->options.cipherSuite0;
-    output[idx++] = ssl->options.cipherSuite;
+
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    /* Compression not supported in TLS v1.3. */
+    output[idx++] = 0;
+#endif
 
     /* Extensions */
-    TLSX_WriteResponse(ssl, output + idx, server_hello);
+    ret = TLSX_WriteResponse(ssl, output + idx, extMsgType, NULL);
+    if (ret != 0)
+        return ret;
 
     ssl->buffers.outputBuffer.length += sendSz;
@@ -3547,21 +4222,32 @@
     #ifdef WOLFSSL_CALLBACKS
     if (ssl->hsInfoOn)
-        AddPacketName("ServerHello", &ssl->handShakeInfo);
+        AddPacketName(ssl, "ServerHello");
     if (ssl->toInfoOn) {
-        AddPacketInfo("ServerHello", &ssl->timeoutInfo, output, sendSz,
-                      ssl->heap);
+        AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
+                      WRITE_PROTO, ssl->heap);
     }
     #endif
 
+#ifdef WOLFSSL_TLS13_DRAFT_18
     ssl->options.serverState = SERVER_HELLO_COMPLETE;
-
+#else
+    if (extMsgType == server_hello)
+    ssl->options.serverState = SERVER_HELLO_COMPLETE;
+#endif
+
+#ifdef WOLFSSL_TLS13_DRAFT_18
     if (!ssl->options.groupMessages)
+#else
+    if (!ssl->options.groupMessages || extMsgType != server_hello)
+#endif
         ret = SendBuffered(ssl);
 
     WOLFSSL_LEAVE("SendTls13ServerHello", ret);
+    WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
 
     return ret;
 }
 
+/* handle generation of TLS 1.3 encrypted_extensions (8) */
 /* Send the rest of the extensions encrypted under the handshake key.
  * This message is always encrypted in TLS v1.3.
@@ -3575,11 +4261,17 @@
     int    ret;
     byte*  output;
-    word32 length;
+    word16 length = 0;
     word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
     int    sendSz;
 
+    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
     WOLFSSL_ENTER("SendTls13EncryptedExtensions");
 
     ssl->keys.encryptionOn = 1;
+
+#ifndef WOLFSSL_NO_SERVER_GROUPS_EXT
+    if ((ret = TLSX_SupportedCurve_CheckPriority(ssl)) != 0)
+        return ret;
+#endif
 
     /* Derive the handshake secret now that we are at first message to be
@@ -3596,5 +4288,5 @@
     if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
         return ret;
-    if (ssl->earlyData != 2) {
+    if (ssl->earlyData != process_early_data) {
         if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
             return ret;
@@ -3605,5 +4297,8 @@
 #endif
 
-    length = TLSX_GetResponseSize(ssl, encrypted_extensions);
+    ret = TLSX_GetResponseSize(ssl, encrypted_extensions, &length);
+    if (ret != 0)
+        return ret;
+
     sendSz = idx + length;
     /* Encryption always on. */
@@ -3622,13 +4317,15 @@
     AddTls13Headers(output, length, encrypted_extensions, ssl);
 
-    TLSX_WriteResponse(ssl, output + idx, encrypted_extensions);
+    ret = TLSX_WriteResponse(ssl, output + idx, encrypted_extensions, NULL);
+    if (ret != 0)
+        return ret;
     idx += length;
 
 #ifdef WOLFSSL_CALLBACKS
     if (ssl->hsInfoOn)
-        AddPacketName("EncryptedExtensions", &ssl->handShakeInfo);
+        AddPacketName(ssl, "EncryptedExtensions");
     if (ssl->toInfoOn) {
-        AddPacketInfo("EncryptedExtensions", &ssl->timeoutInfo, output,
-                      sendSz, ssl->heap);
+        AddPacketInfo(ssl, "EncryptedExtensions", handshake, output,
+                      sendSz, WRITE_PROTO, ssl->heap);
     }
 #endif
@@ -3648,4 +4345,5 @@
 
     WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
+    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
 
     return ret;
@@ -3653,4 +4351,5 @@
 
 #ifndef NO_CERTS
+/* handle generation TLS v1.3 certificate_request (13) */
 /* Send the TLS v1.3 CertificateRequest message.
  * This message is always encrypted in TLS v1.3.
@@ -3669,9 +4368,10 @@
     int    sendSz;
     word32 i;
-    int    reqSz;
+    word16 reqSz;
 #ifndef WOLFSSL_TLS13_DRAFT_18
     TLSX*  ext;
 #endif
 
+    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
     WOLFSSL_ENTER("SendTls13CertificateRequest");
 
@@ -3727,6 +4427,8 @@
 
     i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
-    reqSz = OPAQUE8_LEN + reqCtxLen +
-        TLSX_GetRequestSize(ssl, certificate_request);
+    reqSz = (word16)(OPAQUE8_LEN + reqCtxLen);
+    ret = TLSX_GetRequestSize(ssl, certificate_request, &reqSz);
+    if (ret != 0)
+        return ret;
 
     sendSz = i + reqSz;
@@ -3746,5 +4448,5 @@
 
     /* Certificate request context. */
-    output[i++] = reqCtxLen;
+    output[i++] = (byte)reqCtxLen;
     if (reqCtxLen != 0) {
         XMEMCPY(output + i, reqCtx, reqCtxLen);
@@ -3753,5 +4455,9 @@
 
     /* Certificate extensions. */
-    i += TLSX_WriteRequest(ssl, output + i, certificate_request);
+    reqSz = 0;
+    ret = TLSX_WriteRequest(ssl, output + i, certificate_request, &reqSz);
+    if (ret != 0)
+        return ret;
+    i += reqSz;
 #endif
 
@@ -3764,8 +4470,8 @@
     #ifdef WOLFSSL_CALLBACKS
         if (ssl->hsInfoOn)
-            AddPacketName("CertificateRequest", &ssl->handShakeInfo);
+            AddPacketName(ssl, "CertificateRequest");
         if (ssl->toInfoOn) {
-            AddPacketInfo("CertificateRequest", &ssl->timeoutInfo, output,
-                          sendSz, ssl->heap);
+            AddPacketInfo(ssl, "CertificateRequest", handshake, output,
+                          sendSz, WRITE_PROTO, ssl->heap);
         }
     #endif
@@ -3776,4 +4482,5 @@
 
     WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
+    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
 
     return ret;
@@ -3790,5 +4497,5 @@
  * output    The buffer to encode into.
  */
-static INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
+static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
 {
     switch (hsType) {
@@ -3824,5 +4531,5 @@
  * hsType   The signature type.
  */
-static INLINE void DecodeSigAlg(byte* input, byte* hashAlgo, byte* hsType)
+static WC_INLINE void DecodeSigAlg(byte* input, byte* hashAlgo, byte* hsType)
 {
     switch (input[0]) {
@@ -3856,5 +4563,5 @@
  * returns the length of the hash.
  */
-static INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
+static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
 {
     int ret = 0;
@@ -3901,5 +4608,5 @@
 #define MAX_SIG_DATA_SZ            (SIGNING_DATA_PREFIX_SZ + \
                                     CERT_VFY_LABEL_SZ      + \
-                                    MAX_DIGEST_SIZE)
+                                    WC_MAX_DIGEST_SIZE)
 
 /* Create the signature data for TLS v1.3 certificate verification.
@@ -3935,5 +4642,5 @@
         return ret;
 
-    *sigDataSz = idx + ret;
+    *sigDataSz = (word16)(idx + ret);
     ret = 0;
 
@@ -4075,5 +4782,5 @@
  *
  * ssl       The SSL/TLS object.
- * hashAlgo  The signature algorithm used to generate signature.
+ * sigAlgo   The signature algorithm used to generate signature.
  * hashAlgo  The hash algorithm used to generate signature.
  * decSig    The decrypted signature.
@@ -4100,5 +4807,5 @@
             return ret;
 
-        /* PSS signature can be done in-pace */
+        /* PSS signature can be done in-place */
         ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
                                   sigAlgo, hashAlgo);
@@ -4147,6 +4854,8 @@
 /* Add certificate data and empty extension to output up to the fragment size.
  *
+ * ssl     SSL/TLS object.
  * cert    The certificate data to write out.
  * len     The length of the certificate data.
+ * extSz   Length of the extension data with the certificate.
  * idx     The start of the certificate data to write out.
  * fragSz  The maximum size of this fragment.
@@ -4154,6 +4863,6 @@
  * returns the number of bytes written.
  */
-static word32 AddCertExt(byte* cert, word32 len, word32 idx, word32 fragSz,
-                         byte* output)
+static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz,
+                         word32 idx, word32 fragSz, byte* output)
 {
     word32 i = 0;
@@ -4163,15 +4872,29 @@
         XMEMCPY(output, cert + idx, copySz);
         i = copySz;
-    }
-
-    if (copySz + OPAQUE16_LEN <= fragSz) {
+        if (copySz == fragSz)
+            return i;
+    }
+    copySz = len + extSz - idx - i;
+
+    if (extSz == OPAQUE16_LEN) {
+        if (copySz <= fragSz) {
         /* Empty extension */
         output[i++] = 0;
         output[i++] = 0;
     }
+    }
+    else {
+        byte* certExts = ssl->buffers.certExts->buffer + idx + i - len;
+        /* Put out as much of the extensions' data as will fit in fragment. */
+        if (copySz > fragSz - i)
+            copySz = fragSz - i;
+        XMEMCPY(output + i, certExts, copySz);
+        i += copySz;
+    }
 
     return i;
 }
 
+/* handle generation TLS v1.3 certificate (11) */
 /* Send the certificate for this end and any CAs that help with validation.
  * This message is always encrypted in TLS v1.3.
@@ -4184,4 +4907,5 @@
     int    ret = 0;
     word32 certSz, certChainSz, headerSz, listSz, payloadSz;
+    word16 extSz = 0;
     word32 length, maxFragment;
     word32 len = 0;
@@ -4192,4 +4916,5 @@
     byte*  certReqCtx = NULL;
 
+    WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
     WOLFSSL_ENTER("SendTls13Certificate");
 
@@ -4218,12 +4943,28 @@
         headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
                    CERT_HEADER_SZ;
-        /* Length of message data with one certificate and empty extensions. */
-        length = headerSz + certSz + OPAQUE16_LEN;
-        /* Length of list data with one certificate and empty extensions. */
-        listSz = CERT_HEADER_SZ + certSz + OPAQUE16_LEN;
+
+        ret = TLSX_GetResponseSize(ssl, certificate, &extSz);
+        if (ret < 0)
+            return ret;
+
+        /* Create extensions' data if none already present. */
+        if (extSz > OPAQUE16_LEN && ssl->buffers.certExts == NULL) {
+            ret = AllocDer(&ssl->buffers.certExts, extSz, CERT_TYPE, ssl->heap);
+            if (ret < 0)
+                return ret;
+
+            ret = TLSX_WriteResponse(ssl, ssl->buffers.certExts->buffer,
+                                                           certificate, &extSz);
+            if (ret < 0)
+                return ret;
+        }
+
+        /* Length of message data with one certificate and extensions. */
+        length = headerSz + certSz + extSz;
+        /* Length of list data with one certificate and extensions. */
+        listSz = CERT_HEADER_SZ + certSz + extSz;
 
         /* Send rest of chain if sending cert (chain has leading size/s). */
         if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
-            /* The pointer to the current spot in the cert chain buffer. */
             p = ssl->buffers.certChain->buffer;
             /* Chain length including extensions. */
@@ -4242,10 +4983,5 @@
         length -= (ssl->fragOffset + headerSz);
 
-    maxFragment = MAX_RECORD_SIZE;
-
-    #ifdef HAVE_MAX_FRAGMENT
-    if (ssl->max_fragment != 0 && maxFragment >= ssl->max_fragment)
-        maxFragment = ssl->max_fragment;
-    #endif /* HAVE_MAX_FRAGMENT */
+    maxFragment = wolfSSL_GetMaxRecordSize(ssl, MAX_RECORD_SIZE);
 
     while (length > 0 && ret == 0) {
@@ -4256,12 +4992,11 @@
 
         if (ssl->fragOffset == 0)  {
-            if (headerSz + certSz + OPAQUE16_LEN + certChainSz <=
+            if (headerSz + certSz + extSz + certChainSz <=
                 maxFragment - HANDSHAKE_HEADER_SZ) {
-
-                fragSz = headerSz + certSz + OPAQUE16_LEN + certChainSz;
-            }
-            else {
+                fragSz = headerSz + certSz + extSz + certChainSz;
+            }
+            else
                 fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
-            }
+
             sendSz += fragSz + HANDSHAKE_HEADER_SZ;
             i += HANDSHAKE_HEADER_SZ;
@@ -4309,13 +5044,14 @@
             AddTls13RecordHeader(output, fragSz, handshake, ssl);
 
-        if (certSz > 0 && ssl->fragOffset < certSz + OPAQUE16_LEN) {
-            /* Put in the leaf certificate and empty extension. */
-            word32 copySz = AddCertExt(ssl->buffers.certificate->buffer, certSz,
-                                       ssl->fragOffset, fragSz, output + i);
-
+        if (certSz > 0 && ssl->fragOffset < certSz + extSz) {
+            /* Put in the leaf certificate with extensions. */
+            word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer,
+                            certSz, extSz, ssl->fragOffset, fragSz, output + i);
             i += copySz;
             ssl->fragOffset += copySz;
             length -= copySz;
             fragSz -= copySz;
+            if (ssl->fragOffset == certSz + extSz)
+                FreeDer(&ssl->buffers.certExts);
         }
         if (certChainSz > 0 && fragSz > 0) {
@@ -4327,4 +5063,6 @@
                     /* Find next CA certificate to write out. */
                     offset = 0;
+                    /* Point to the start of current cert in chain buffer. */
+                    p = ssl->buffers.certChain->buffer + idx;
                     len = NextCert(ssl->buffers.certChain->buffer,
                                    ssl->buffers.certChain->length, &idx);
@@ -4334,5 +5072,6 @@
 
                 /* Write out certificate and empty extension. */
-                l = AddCertExt(p, len, offset, fragSz, output + i);
+                l = AddCertExt(ssl, p, len, OPAQUE16_LEN, offset, fragSz,
+                                                                    output + i);
                 i += l;
                 ssl->fragOffset += l;
@@ -4357,8 +5096,8 @@
         #ifdef WOLFSSL_CALLBACKS
             if (ssl->hsInfoOn)
-                AddPacketName("Certificate", &ssl->handShakeInfo);
+                AddPacketName(ssl, "Certificate");
             if (ssl->toInfoOn) {
-                AddPacketInfo("Certificate", &ssl->timeoutInfo, output, sendSz,
-                               ssl->heap);
+                AddPacketInfo(ssl, "Certificate", handshake, output,
+                        sendSz, WRITE_PROTO, ssl->heap);
             }
         #endif
@@ -4385,4 +5124,5 @@
 
     WOLFSSL_LEAVE("SendTls13Certificate", ret);
+    WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
 
     return ret;
@@ -4391,7 +5131,4 @@
 typedef struct Scv13Args {
     byte*  output; /* not allocated */
-#ifndef NO_RSA
-    byte*  verifySig;
-#endif
     byte*  verify; /* not allocated */
     word32 idx;
@@ -4411,10 +5148,4 @@
     (void)ssl;
 
-#ifndef NO_RSA
-    if (args->verifySig) {
-        XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
-        args->verifySig = NULL;
-    }
-#endif
     if (args->sigData) {
         XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
@@ -4423,4 +5154,5 @@
 }
 
+/* handle generation TLS v1.3 certificate_verify (15) */
 /* Send the TLS v1.3 CertificateVerify message.
  * A hash of all the message so far is used.
@@ -4444,4 +5176,5 @@
 #endif
 
+    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
     WOLFSSL_ENTER("SendTls13CertificateVerify");
 
@@ -4473,5 +5206,5 @@
             }
 
-            args->sendSz = MAX_CERT_VERIFY_SZ;
+            args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
             /* Always encrypted.  */
             args->sendSz += MAX_MSG_EXTRA;
@@ -4498,7 +5231,21 @@
                           &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
 
+            if (ssl->buffers.key == NULL) {
+            #ifdef HAVE_PK_CALLBACKS
+                if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
+                    args->length = GetPrivateKeySigSize(ssl);
+                else
+            #endif
+                    ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
+            }
+            else {
             ret = DecodePrivateKey(ssl, &args->length);
             if (ret != 0)
                 goto exit_scv;
+            }
+
+            if (args->length <= 0) {
+                ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
+            }
 
             /* Add signature algorithm. */
@@ -4513,11 +5260,20 @@
             EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo, args->verify);
 
-            /* Create the data to be signed. */
+            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
+                int sigLen = MAX_SIG_DATA_SZ;
+                if (args->length > MAX_SIG_DATA_SZ)
+                    sigLen = args->length;
+                args->sigData = (byte*)XMALLOC(sigLen, ssl->heap,
+                                                        DYNAMIC_TYPE_SIGNATURE);
+            }
+            else {
             args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
                                                     DYNAMIC_TYPE_SIGNATURE);
+            }
             if (args->sigData == NULL) {
                 ERROR_OUT(MEMORY_E, exit_scv);
             }
 
+            /* Create the data to be signed. */
             ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
             if (ret != 0)
@@ -4527,5 +5283,5 @@
             if (ssl->hsType == DYNAMIC_TYPE_RSA) {
                 /* build encoded signature buffer */
-                sig->length = MAX_ENCODED_SIG_SZ;
+                sig->length = WC_MAX_DIGEST_SIZE;
                 sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap,
                                                     DYNAMIC_TYPE_SIGNATURE);
@@ -4553,5 +5309,5 @@
                 if (ret < 0)
                     goto exit_scv;
-                args->sigDataSz = ret;
+                args->sigDataSz = (word16)ret;
                 ret = 0;
             }
@@ -4559,5 +5315,8 @@
         #ifdef HAVE_ED25519
             if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
-                /* Nothing to do */
+                ret = Ed25519CheckPubKey(ssl);
+                if (ret < 0) {
+                    ERROR_OUT(ret, exit_scv);
+                }
                 sig->length = ED25519_SIG_SIZE;
             }
@@ -4576,12 +5335,11 @@
                     args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
                     &sig->length, (ecc_key*)ssl->hsKey,
-            #if defined(HAVE_PK_CALLBACKS)
-                    ssl->buffers.key->buffer, ssl->buffers.key->length,
-                    ssl->EccSignCtx
+            #ifdef HAVE_PK_CALLBACKS
+                    ssl->buffers.key
             #else
-                    NULL, 0, NULL
+                    NULL
             #endif
                 );
-                args->length = sig->length;
+                args->length = (word16)sig->length;
             }
         #endif /* HAVE_ECC */
@@ -4591,9 +5349,8 @@
                     args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
                     &sig->length, (ed25519_key*)ssl->hsKey,
-            #if defined(HAVE_PK_CALLBACKS)
-                    ssl->buffers.key->buffer, ssl->buffers.key->length,
-                    ssl->Ed25519SignCtx
+            #ifdef HAVE_PK_CALLBACKS
+                    ssl->buffers.key
             #else
-                    NULL, 0, NULL
+                    NULL
             #endif
                 );
@@ -4608,12 +5365,13 @@
                     args->sigAlgo, ssl->suites->hashAlgo,
                     (RsaKey*)ssl->hsKey,
-                    ssl->buffers.key->buffer, ssl->buffers.key->length,
-                #ifdef HAVE_PK_CALLBACKS
-                    ssl->RsaSignCtx
-                #else
-                    NULL
-                #endif
+                    ssl->buffers.key
                 );
-                args->length = args->sigLen;
+                if (ret == 0) {
+                    args->length = (word16)args->sigLen;
+
+                    XMEMCPY(args->sigData,
+                        args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
+                        args->sigLen);
+                }
             }
         #endif /* !NO_RSA */
@@ -4636,19 +5394,10 @@
         #ifndef NO_RSA
             if (ssl->hsType == DYNAMIC_TYPE_RSA) {
-                if (args->verifySig == NULL) {
-                    args->verifySig = (byte*)XMALLOC(args->sigLen, ssl->heap,
-                                                   DYNAMIC_TYPE_SIGNATURE);
-                    if (args->verifySig == NULL) {
-                        ERROR_OUT(MEMORY_E, exit_scv);
-                    }
-                    XMEMCPY(args->verifySig,
-                        args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
-                        args->sigLen);
-                }
-
                 /* check for signature faults */
-                ret = VerifyRsaSign(ssl, args->verifySig, args->sigLen,
+                ret = VerifyRsaSign(ssl, args->sigData, args->sigLen,
                     sig->buffer, sig->length, args->sigAlgo,
-                    ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey);
+                    ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey,
+                    ssl->buffers.key
+                );
             }
         #endif /* !NO_RSA */
@@ -4697,8 +5446,8 @@
         #ifdef WOLFSSL_CALLBACKS
             if (ssl->hsInfoOn)
-                AddPacketName("CertificateVerify", &ssl->handShakeInfo);
+                AddPacketName(ssl, "CertificateVerify");
             if (ssl->toInfoOn) {
-                AddPacketInfo("CertificateVerify", &ssl->timeoutInfo,
-                              args->output, args->sendSz, ssl->heap);
+                AddPacketInfo(ssl, "CertificateVerify", handshake,
+                            args->output, args->sendSz, WRITE_PROTO, ssl->heap);
             }
         #endif
@@ -4717,4 +5466,5 @@
 
     WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
+    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
 
 #ifdef WOLFSSL_ASYNC_CRYPT
@@ -4732,5 +5482,5 @@
 }
 
-
+/* handle processing TLS v1.3 certificate (11) */
 /* Parse and handle a TLS v1.3 Certificate message.
  *
@@ -4747,10 +5497,15 @@
     int ret;
 
+    WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
     WOLFSSL_ENTER("DoTls13Certificate");
 
     ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
-
+    if (ret == 0) {
+#if !defined(NO_WOLFSSL_CLIENT)
+        if (ssl->options.side == WOLFSSL_CLIENT_END)
+            ssl->options.serverState = SERVER_CERT_COMPLETE;
+#endif
 #if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
-    if (ret == 0 && ssl->options.side == WOLFSSL_SERVER_END &&
+        if (ssl->options.side == WOLFSSL_SERVER_END &&
                                 ssl->options.handShakeState == HANDSHAKE_DONE) {
         /* reset handshake states */
@@ -4760,6 +5515,8 @@
     }
 #endif
+    }
 
     WOLFSSL_LEAVE("DoTls13Certificate", ret);
+    WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
 
     return ret;
@@ -4794,4 +5551,5 @@
 }
 
+/* handle processing TLS v1.3 certificate_verify (15) */
 /* Parse and handle a TLS v1.3 CertificateVerify message.
  *
@@ -4817,4 +5575,5 @@
 #endif
 
+    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
     WOLFSSL_ENTER("DoTls13CertificateVerify");
 
@@ -4847,6 +5606,5 @@
         {
         #ifdef WOLFSSL_CALLBACKS
-            if (ssl->hsInfoOn) AddPacketName("CertificateVerify",
-                                             &ssl->handShakeInfo);
+            if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateVerify");
             if (ssl->toInfoOn) AddLateName("CertificateVerify",
                                            &ssl->timeoutInfo);
@@ -4926,5 +5684,5 @@
                 if (ret < 0)
                     goto exit_dcv;
-                args->sigDataSz = ret;
+                args->sigDataSz = (word16)ret;
                 ret = 0;
             }
@@ -4953,6 +5711,5 @@
         {
         #ifndef NO_RSA
-            if (args->sigAlgo == rsa_sa_algo ||
-                                             args->sigAlgo == rsa_pss_sa_algo) {
+            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
                 WOLFSSL_MSG("Doing RSA peer cert verify");
 
@@ -4960,9 +5717,7 @@
                     args->sigAlgo, args->hashAlgo, ssl->peerRsaKey,
                 #ifdef HAVE_PK_CALLBACKS
-                    ssl->buffers.peerRsaKey.buffer,
-                    ssl->buffers.peerRsaKey.length,
-                    ssl->RsaVerifyCtx
+                    &ssl->buffers.peerRsaKey
                 #else
-                    NULL, 0, NULL
+                    NULL
                 #endif
                 );
@@ -4970,4 +5725,7 @@
                     args->sendSz = ret;
                     ret = 0;
+
+                    FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
+                    ssl->peerRsaKeyPresent = 0;
                 }
             }
@@ -4981,11 +5739,14 @@
                     ssl->peerEccDsaKey,
                 #ifdef HAVE_PK_CALLBACKS
-                    ssl->buffers.peerEccDsaKey.buffer,
-                    ssl->buffers.peerEccDsaKey.length,
-                    ssl->EccVerifyCtx
+                    &ssl->buffers.peerEccDsaKey
                 #else
-                    NULL, 0, NULL
+                    NULL
                 #endif
                 );
+
+                if (ret >= 0) {
+                    FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
+                    ssl->peerEccDsaKeyPresent = 0;
+                }
             }
         #endif /* HAVE_ECC */
@@ -4998,11 +5759,15 @@
                     ssl->peerEd25519Key,
                 #ifdef HAVE_PK_CALLBACKS
-                    ssl->buffers.peerEd25519Key.buffer,
-                    ssl->buffers.peerEd25519Key.length,
-                    ssl->Ed25519VerifyCtx
+                    &ssl->buffers.peerEd25519Key
                 #else
-                    NULL, 0, NULL
+                    NULL
                 #endif
                 );
+
+                if (ret >= 0) {
+                    FreeKey(ssl, DYNAMIC_TYPE_ED25519,
+                                                  (void**)&ssl->peerEd25519Key);
+                    ssl->peerEd25519KeyPresent = 0;
+                }
             }
         #endif
@@ -5060,14 +5825,18 @@
 
     WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
+    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
 
 #ifdef WOLFSSL_ASYNC_CRYPT
     /* Handle async operation */
     if (ret == WC_PENDING_E) {
-        /* Mark message as not recevied so it can process again */
+        /* Mark message as not received so it can process again */
         ssl->msgsReceived.got_certificate_verify = 0;
 
         return ret;
     }
+    else
 #endif /* WOLFSSL_ASYNC_CRYPT */
+    if (ret != 0)
+        SendAlert(ssl, alert_fatal, decrypt_error);
 
     /* Final cleanup */
@@ -5096,6 +5865,7 @@
     word32 finishedSz = 0;
     byte*  secret;
-    byte   mac[MAX_DIGEST_SIZE];
-
+    byte   mac[WC_MAX_DIGEST_SIZE];
+
+    WOLFSSL_START(WC_FUNC_FINISHED_DO);
     WOLFSSL_ENTER("DoTls13Finished");
 
@@ -5104,14 +5874,22 @@
         return BUFFER_E;
 
-    if (ssl->options.side == WOLFSSL_CLIENT_END) {
+    if (ssl->options.handShakeDone) {
+        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
+                                   ssl->keys.client_write_MAC_secret);
+        if (ret != 0)
+            return ret;
+
+        secret = ssl->keys.client_write_MAC_secret;
+    }
+    else if (ssl->options.side == WOLFSSL_CLIENT_END) {
         /* All the handshake messages have been received to calculate
          * client and server finished keys.
          */
-        ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret,
+        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
                                    ssl->keys.client_write_MAC_secret);
         if (ret != 0)
             return ret;
 
-        ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret,
+        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
                                    ssl->keys.server_write_MAC_secret);
         if (ret != 0)
@@ -5130,5 +5908,5 @@
 
     #ifdef WOLFSSL_CALLBACKS
-        if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo);
+        if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
         if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
     #endif
@@ -5138,4 +5916,5 @@
         if (XMEMCMP(input + *inOutIdx, mac, size) != 0){
             WOLFSSL_MSG("Verify finished error on hashes");
+            SendAlert(ssl, alert_fatal, decrypt_error);
             return VERIFY_FINISHED_ERROR;
         }
@@ -5148,5 +5927,5 @@
                                                   !ssl->options.handShakeDone) {
 #ifdef WOLFSSL_EARLY_DATA
-        if (ssl->earlyData) {
+        if (ssl->earlyData != no_early_data) {
             if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
                 return ret;
@@ -5171,4 +5950,5 @@
 
     WOLFSSL_LEAVE("DoTls13Finished", 0);
+    WOLFSSL_END(WC_FUNC_FINISHED_DO);
 
     return 0;
@@ -5192,7 +5972,8 @@
     byte* secret;
 
+    WOLFSSL_START(WC_FUNC_FINISHED_SEND);
     WOLFSSL_ENTER("SendTls13Finished");
 
-    outputSz = MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
+    outputSz = WC_MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
     /* Check buffers are big enough and grow if needed. */
     if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
@@ -5207,5 +5988,13 @@
 
     /* make finished hashes */
-    if (ssl->options.side == WOLFSSL_CLIENT_END)
+    if (ssl->options.handShakeDone) {
+        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
+                                   ssl->keys.client_write_MAC_secret);
+        if (ret != 0)
+            return ret;
+
+        secret = ssl->keys.client_write_MAC_secret;
+    }
+    else if (ssl->options.side == WOLFSSL_CLIENT_END)
         secret = ssl->keys.client_write_MAC_secret;
     else {
@@ -5213,10 +6002,10 @@
          * server finished keys.
          */
-        ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret,
+        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
                                    ssl->keys.client_write_MAC_secret);
         if (ret != 0)
             return ret;
 
-        ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret,
+        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
                                    ssl->keys.server_write_MAC_secret);
         if (ret != 0)
@@ -5235,5 +6024,5 @@
         return BUILD_MSG_ERROR;
 
-    if (!ssl->options.resuming) {
+    if (!ssl->options.resuming && ssl->options.side == WOLFSSL_SERVER_END) {
 #ifndef NO_SESSION_CACHE
         AddSession(ssl);    /* just try */
@@ -5242,15 +6031,12 @@
 
     #ifdef WOLFSSL_CALLBACKS
-        if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo);
+        if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
         if (ssl->toInfoOn) {
-            AddPacketInfo("Finished", &ssl->timeoutInfo, output, sendSz,
-                          ssl->heap);
+            AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
+                          WRITE_PROTO, ssl->heap);
         }
     #endif
 
     ssl->buffers.outputBuffer.length += sendSz;
-
-    if ((ret = SendBuffered(ssl)) != 0)
-        return ret;
 
     if (ssl->options.side == WOLFSSL_SERVER_END) {
@@ -5264,5 +6050,5 @@
         }
         if ((ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
-                                                       !ssl->earlyData)) != 0) {
+                                       ssl->earlyData == no_early_data)) != 0) {
             return ret;
         }
@@ -5280,5 +6066,5 @@
                                                   !ssl->options.handShakeDone) {
 #ifdef WOLFSSL_EARLY_DATA
-        if (ssl->earlyData) {
+        if (ssl->earlyData != no_early_data) {
             if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_AND_DECRYPT_SIDE,
                                                                      1)) != 0) {
@@ -5293,27 +6079,32 @@
 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
         ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret);
-#endif
-    }
-
-    if (ssl->options.resuming) {
-        if (ssl->options.side == WOLFSSL_CLIENT_END) {
+        if (ret != 0)
+            return ret;
+#endif
+    }
+
+#ifndef NO_WOLFSSL_CLIENT
+    if (ssl->options.side == WOLFSSL_CLIENT_END) {
+        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
             ssl->options.handShakeState = HANDSHAKE_DONE;
             ssl->options.handShakeDone  = 1;
         }
-    }
-#ifndef NO_WOLFSSL_CLIENT
-    if (ssl->options.side == WOLFSSL_CLIENT_END) {
-        if (!ssl->options.resuming) {
-            ssl->options.handShakeState = HANDSHAKE_DONE;
-            ssl->options.handShakeDone  = 1;
-        }
-    }
-#endif
+#endif
+#ifndef NO_WOLFSSL_SERVER
+    if (ssl->options.side == WOLFSSL_SERVER_END) {
+        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
+    }
+#endif
+
+    if ((ret = SendBuffered(ssl)) != 0)
+        return ret;
 
     WOLFSSL_LEAVE("SendTls13Finished", ret);
+    WOLFSSL_END(WC_FUNC_FINISHED_SEND);
 
     return ret;
 }
 
+/* handle generation TLS v1.3 key_update (24) */
 /* Send the TLS v1.3 KeyUpdate message.
  *
@@ -5331,4 +6122,5 @@
     word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
 
+    WOLFSSL_START(WC_FUNC_KEY_UPDATE_SEND);
     WOLFSSL_ENTER("SendTls13KeyUpdate");
 
@@ -5362,8 +6154,8 @@
 
     #ifdef WOLFSSL_CALLBACKS
-        if (ssl->hsInfoOn) AddPacketName("KeyUpdate", &ssl->handShakeInfo);
+        if (ssl->hsInfoOn) AddPacketName(ssl, "KeyUpdate");
         if (ssl->toInfoOn) {
-            AddPacketInfo("KeyUpdate", &ssl->timeoutInfo, output, sendSz,
-                          ssl->heap);
+            AddPacketInfo(ssl, "KeyUpdate", handshake, output, sendSz,
+                          WRITE_PROTO, ssl->heap);
         }
     #endif
@@ -5383,8 +6175,10 @@
 
     WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
+    WOLFSSL_END(WC_FUNC_KEY_UPDATE_SEND);
 
     return ret;
 }
 
+/* handle processing TLS v1.3 key_update (24) */
 /* Parse and handle a TLS v1.3 KeyUpdate message.
  *
@@ -5402,4 +6196,5 @@
     word32 i = *inOutIdx;
 
+    WOLFSSL_START(WC_FUNC_KEY_UPDATE_DO);
     WOLFSSL_ENTER("DoTls13KeyUpdate");
 
@@ -5440,4 +6235,5 @@
 
     WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
+    WOLFSSL_END(WC_FUNC_KEY_UPDATE_DO);
 
     return 0;
@@ -5461,4 +6257,5 @@
     word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
 
+    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_SEND);
     WOLFSSL_ENTER("SendTls13EndOfEarlyData");
 
@@ -5492,4 +6289,5 @@
 
     WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
+    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_SEND);
 
     return ret;
@@ -5498,4 +6296,5 @@
 
 #ifndef NO_WOLFSSL_SERVER
+/* handle processing of TLS 1.3 end_of_early_data (5) */
 /* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
  * no more early application data.
@@ -5513,4 +6312,5 @@
     (void)input;
 
+    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_DO);
     WOLFSSL_ENTER("DoTls13EndOfEarlyData");
 
@@ -5518,4 +6318,12 @@
         return BUFFER_ERROR;
 
+    if (ssl->earlyData == no_early_data) {
+        WOLFSSL_MSG("EndOfEarlyData recieved unexpectedly");
+        SendAlert(ssl, alert_fatal, unexpected_message);
+        return OUT_OF_ORDER_E;
+    }
+
+    ssl->earlyData = done_early_data;
+
     /* Always encrypted. */
     *inOutIdx += ssl->keys.padSz;
@@ -5523,5 +6331,6 @@
     ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
 
-    WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
+    WOLFSSL_LEAVE("DoTls13EndOfEarlyData", ret);
+    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_DO);
 
     return ret;
@@ -5551,5 +6360,10 @@
     word16 length;
     word32 now;
-
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    const byte*  nonce;
+    byte         nonceLength;
+#endif
+
+    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO);
     WOLFSSL_ENTER("DoTls13NewSessionTicket");
 
@@ -5567,4 +6381,20 @@
     ato32(input + *inOutIdx, &ageAdd);
     *inOutIdx += SESSION_ADD_SZ;
+
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    /* Ticket nonce. */
+    if ((*inOutIdx - begin) + 1 > size)
+        return BUFFER_ERROR;
+    nonceLength = input[*inOutIdx];
+    if (nonceLength > MAX_TICKET_NONCE_SZ) {
+        WOLFSSL_MSG("Nonce length not supported");
+        return INVALID_PARAMETER;
+    }
+    *inOutIdx += 1;
+    if ((*inOutIdx - begin) + nonceLength > size)
+        return BUFFER_ERROR;
+    nonce = input + *inOutIdx;
+    *inOutIdx += nonceLength;
+#endif
 
     /* Ticket length. */
@@ -5593,4 +6423,10 @@
     ssl->session.maxEarlyDataSz = ssl->options.maxEarlyDataSz;
     #endif
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    ssl->session.ticketNonce.len = nonceLength;
+    if (nonceLength > 0)
+        XMEMCPY(&ssl->session.ticketNonce.data, nonce, nonceLength);
+#endif
+    ssl->session.namedGroup     = ssl->namedGroup;
 
     if ((*inOutIdx - begin) + EXTS_SZ > size)
@@ -5626,4 +6462,5 @@
 
     WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
+    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_DO);
 
     return 0;
@@ -5648,5 +6485,5 @@
     int         ret;
     word32      finishedSz = 0;
-    byte        mac[MAX_DIGEST_SIZE];
+    byte        mac[WC_MAX_DIGEST_SIZE];
     Digest      digest;
     static byte header[] = { 0x14, 0x00, 0x00, 0x00 };
@@ -5684,5 +6521,5 @@
     header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
 #ifdef WOLFSSL_EARLY_DATA
-    if (ssl->earlyData) {
+    if (ssl->earlyData != no_early_data) {
         static byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
         ret = HashInputRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
@@ -5739,8 +6576,9 @@
     int    ret;
     int    sendSz;
-    word32 extSz;
+    word16 extSz;
     word32 length;
     word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
 
+    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND);
     WOLFSSL_ENTER("SendTls13NewSessionTicket");
 
@@ -5752,4 +6590,14 @@
 #endif
 
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    /* Start ticket nonce at 0 and go up to 255. */
+    if (ssl->session.ticketNonce.len == 0) {
+        ssl->session.ticketNonce.len = DEF_TICKET_NONCE_SZ;
+        ssl->session.ticketNonce.data[0] = 0;
+    }
+    else
+        ssl->session.ticketNonce.data[0]++;
+#endif
+
     if (!ssl->options.noTicketTls13) {
         if ((ret = CreateTicket(ssl)) != 0)
@@ -5761,5 +6609,8 @@
     if (ssl->session.maxEarlyDataSz > 0)
         TLSX_EarlyData_Use(ssl, ssl->session.maxEarlyDataSz);
-    extSz = TLSX_GetResponseSize(ssl, session_ticket);
+    extSz = 0;
+    ret = TLSX_GetResponseSize(ssl, session_ticket, &extSz);
+    if (ret != 0)
+        return ret;
 #else
     extSz = EXTS_SZ;
@@ -5769,4 +6620,8 @@
     length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ +
              ssl->session.ticketLen + extSz;
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    /* Nonce */
+    length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ;
+#endif
     sendSz = idx + length + MAX_MSG_EXTRA;
 
@@ -5789,4 +6644,9 @@
     idx += SESSION_ADD_SZ;
 
+#ifndef WOLFSSL_TLS13_DRAFT_18
+    output[idx++] = ssl->session.ticketNonce.len;
+    output[idx++] = ssl->session.ticketNonce.data[0];
+#endif
+
     /* length */
     c16toa(ssl->session.ticketLen, output + idx);
@@ -5797,5 +6657,9 @@
 
 #ifdef WOLFSSL_EARLY_DATA
-    idx += TLSX_WriteResponse(ssl, output + idx, session_ticket);
+    extSz = 0;
+    ret = TLSX_WriteResponse(ssl, output + idx, session_ticket, &extSz);
+    if (ret != 0)
+        return ret;
+    idx += extSz;
 #else
     /* No extension support - empty extensions. */
@@ -5822,4 +6686,5 @@
 
     WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
+    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_SEND);
 
     return ret;
@@ -5841,4 +6706,14 @@
 #ifndef NO_WOLFSSL_SERVER
         case client_hello:
+        #ifndef NO_WOLFSSL_CLIENT
+            if (ssl->options.side == WOLFSSL_CLIENT_END) {
+                WOLFSSL_MSG("ClientHello received by client");
+                return OUT_OF_ORDER_E;
+            }
+        #endif
+            if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE) {
+                WOLFSSL_MSG("ClientHello received out of order");
+                return OUT_OF_ORDER_E;
+            }
             if (ssl->msgsReceived.got_client_hello == 2) {
                 WOLFSSL_MSG("Too many ClientHello received");
@@ -5852,4 +6727,11 @@
 #ifndef NO_WOLFSSL_CLIENT
         case server_hello:
+        #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END) {
+                WOLFSSL_MSG("ServerHello received by server");
+                return OUT_OF_ORDER_E;
+            }
+        #endif
+        #ifdef WOLFSSL_TLS13_DRAFT_18
             if (ssl->msgsReceived.got_server_hello) {
                 WOLFSSL_MSG("Duplicate ServerHello received");
@@ -5857,4 +6739,11 @@
             }
             ssl->msgsReceived.got_server_hello = 1;
+        #else
+            if (ssl->msgsReceived.got_server_hello == 2) {
+                WOLFSSL_MSG("Duplicate ServerHello received");
+                return DUPLICATE_MSG_E;
+            }
+            ssl->msgsReceived.got_server_hello++;
+        #endif
 
             break;
@@ -5863,7 +6752,13 @@
 #ifndef NO_WOLFSSL_CLIENT
         case session_ticket:
-            if (ssl->msgsReceived.got_session_ticket) {
-                WOLFSSL_MSG("Duplicate SessionTicket received");
-                return DUPLICATE_MSG_E;
+        #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END) {
+                WOLFSSL_MSG("NewSessionTicket received by server");
+                return OUT_OF_ORDER_E;
+            }
+        #endif
+            if (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
+                WOLFSSL_MSG("NewSessionTicket received out of order");
+                return OUT_OF_ORDER_E;
             }
             ssl->msgsReceived.got_session_ticket = 1;
@@ -5875,4 +6770,18 @@
     #ifdef WOLFSSL_EARLY_DATA
         case end_of_early_data:
+        #ifndef NO_WOLFSSL_CLIENT
+            if (ssl->options.side == WOLFSSL_CLIENT_END) {
+                WOLFSSL_MSG("EndOfEarlyData received by client");
+                return OUT_OF_ORDER_E;
+            }
+        #endif
+            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
+                WOLFSSL_MSG("EndOfEarlyData received out of order");
+                return OUT_OF_ORDER_E;
+            }
+            if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE) {
+                WOLFSSL_MSG("EndOfEarlyData received out of order");
+                return OUT_OF_ORDER_E;
+            }
             if (ssl->msgsReceived.got_end_of_early_data == 1) {
                 WOLFSSL_MSG("Too many EndOfEarlyData received");
@@ -5885,6 +6794,17 @@
 #endif
 
+#ifdef WOLFSSL_TLS13_DRAFT_18
 #ifndef NO_WOLFSSL_CLIENT
         case hello_retry_request:
+        #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END) {
+                WOLFSSL_MSG("HelloRetryRequest received by server");
+                return OUT_OF_ORDER_E;
+            }
+        #endif
+            if (ssl->options.clientState > CLIENT_FINISHED_COMPLETE) {
+                WOLFSSL_MSG("HelloRetryRequest received out of order");
+                return OUT_OF_ORDER_E;
+            }
             if (ssl->msgsReceived.got_hello_retry_request) {
                 WOLFSSL_MSG("Duplicate HelloRetryRequest received");
@@ -5895,7 +6815,18 @@
             break;
 #endif
+#endif
 
 #ifndef NO_WOLFSSL_CLIENT
         case encrypted_extensions:
+        #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END) {
+                WOLFSSL_MSG("EncryptedExtensions received by server");
+                return OUT_OF_ORDER_E;
+            }
+        #endif
+            if (ssl->options.serverState != SERVER_HELLO_COMPLETE) {
+                WOLFSSL_MSG("EncryptedExtensions received out of order");
+                return OUT_OF_ORDER_E;
+            }
             if (ssl->msgsReceived.got_encrypted_extensions) {
                 WOLFSSL_MSG("Duplicate EncryptedExtensions received");
@@ -5908,4 +6839,28 @@
 
         case certificate:
+    #ifndef NO_WOLFSSL_CLIENT
+            if (ssl->options.side == WOLFSSL_CLIENT_END &&
+                ssl->options.serverState !=
+                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
+                WOLFSSL_MSG("Certificate received out of order - Client");
+                return OUT_OF_ORDER_E;
+            }
+        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+            /* Server's authenticating with PSK must not send this. */
+            if (ssl->options.side == WOLFSSL_CLIENT_END &&
+                             ssl->options.serverState == SERVER_CERT_COMPLETE &&
+                             ssl->arrays->psk_keySz != 0) {
+                WOLFSSL_MSG("Certificate received while using PSK");
+                return SANITY_MSG_E;
+            }
+        #endif
+    #endif
+    #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END &&
+                ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
+                WOLFSSL_MSG("Certificate received out of order - Server");
+                return OUT_OF_ORDER_E;
+            }
+    #endif
             if (ssl->msgsReceived.got_certificate) {
                 WOLFSSL_MSG("Duplicate Certificate received");
@@ -5914,33 +6869,44 @@
             ssl->msgsReceived.got_certificate = 1;
 
+            break;
+
 #ifndef NO_WOLFSSL_CLIENT
-            if (ssl->options.side == WOLFSSL_CLIENT_END) {
-                if ( ssl->msgsReceived.got_server_hello == 0) {
-                    WOLFSSL_MSG("No ServerHello before Cert");
+        case certificate_request:
+        #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END) {
+                WOLFSSL_MSG("CertificateRequest received by server");
                     return OUT_OF_ORDER_E;
                 }
-            }
-#endif
-#ifndef NO_WOLFSSL_SERVER
-            if (ssl->options.side == WOLFSSL_SERVER_END) {
-                if ( ssl->msgsReceived.got_client_hello == 0) {
-                    WOLFSSL_MSG("No ClientHello before Cert");
+#endif
+        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
+            if (ssl->options.serverState !=
+                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
+                WOLFSSL_MSG("CertificateRequest received out of order");
                     return OUT_OF_ORDER_E;
                 }
-            }
-#endif
-            break;
-
-#ifndef NO_WOLFSSL_CLIENT
-        case certificate_request:
-    #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
-            if (ssl->msgsReceived.got_finished)
-                ;
-            else
+        #else
+            if (ssl->options.serverState !=
+                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
+                       (ssl->options.serverState != SERVER_FINISHED_COMPLETE ||
+                        ssl->options.clientState != CLIENT_FINISHED_COMPLETE)) {
+                WOLFSSL_MSG("CertificateRequest received out of order");
+                return OUT_OF_ORDER_E;
+            }
+#endif
+        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+            /* Server's authenticating with PSK must not send this. */
+            if (ssl->options.serverState ==
+                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
+                                                  ssl->arrays->psk_keySz != 0) {
+                WOLFSSL_MSG("CertificateRequset received while using PSK");
+                return SANITY_MSG_E;
+            }
     #endif
+        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
             if (ssl->msgsReceived.got_certificate_request) {
                 WOLFSSL_MSG("Duplicate CertificateRequest received");
                 return DUPLICATE_MSG_E;
             }
+        #endif
             ssl->msgsReceived.got_certificate_request = 1;
 
@@ -5949,4 +6915,36 @@
 
         case certificate_verify:
+    #ifndef NO_WOLFSSL_CLIENT
+            if (ssl->options.side == WOLFSSL_CLIENT_END) {
+                if (ssl->options.serverState != SERVER_CERT_COMPLETE) {
+                    WOLFSSL_MSG("No Cert before CertVerify");
+                    return OUT_OF_ORDER_E;
+                }
+            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
+                /* Server's authenticating with PSK must not send this. */
+                if (ssl->options.serverState == SERVER_CERT_COMPLETE &&
+                                                  ssl->arrays->psk_keySz != 0) {
+                    WOLFSSL_MSG("CertificateVerify received while using PSK");
+                    return SANITY_MSG_E;
+                }
+            #endif
+            }
+    #endif
+    #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END) {
+                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
+                    WOLFSSL_MSG("CertificateVerify received out of order");
+                    return OUT_OF_ORDER_E;
+                }
+                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
+                    WOLFSSL_MSG("CertificateVerify before ClientHello done");
+                    return OUT_OF_ORDER_E;
+                }
+                if (!ssl->msgsReceived.got_certificate) {
+                    WOLFSSL_MSG("No Cert before CertificateVerify");
+                    return OUT_OF_ORDER_E;
+                }
+            }
+    #endif
             if (ssl->msgsReceived.got_certificate_verify) {
                 WOLFSSL_MSG("Duplicate CertificateVerify received");
@@ -5955,15 +6953,36 @@
             ssl->msgsReceived.got_certificate_verify = 1;
 
-            if (ssl->msgsReceived.got_certificate == 0) {
-                WOLFSSL_MSG("No Cert before CertVerify");
-                return OUT_OF_ORDER_E;
-            }
             break;
 
         case finished:
-    #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
-            if (1) {
-            }
-            else
+        #ifndef NO_WOLFSSL_CLIENT
+            if (ssl->options.side == WOLFSSL_CLIENT_END) {
+                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
+                    WOLFSSL_MSG("Finished received out of order");
+                    return OUT_OF_ORDER_E;
+                }
+                if (ssl->options.serverState <
+                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
+                    WOLFSSL_MSG("Finished received out of order");
+                    return OUT_OF_ORDER_E;
+                }
+            }
+        #endif
+        #ifndef NO_WOLFSSL_SERVER
+            if (ssl->options.side == WOLFSSL_SERVER_END) {
+                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
+                    WOLFSSL_MSG("Finished received out of order");
+                    return OUT_OF_ORDER_E;
+                }
+                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
+                    WOLFSSL_MSG("Finished received out of order");
+                    return OUT_OF_ORDER_E;
+                }
+            #ifdef WOLFSSL_EARLY_DATA
+                if (ssl->earlyData == process_early_data) {
+                    return OUT_OF_ORDER_E;
+                }
+            #endif
+            }
     #endif
             if (ssl->msgsReceived.got_finished) {
@@ -6004,6 +7023,7 @@
 {
     int ret = 0;
+    word32 inIdx = *inOutIdx;
+
     (void)totalSz;
-    word32 inIdx = *inOutIdx;
 
     WOLFSSL_ENTER("DoTls13HandShakeMsgType");
@@ -6016,4 +7036,5 @@
     if ( (ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
         WOLFSSL_MSG("Sanity Check on handshake message type received failed");
+        SendAlert(ssl, alert_fatal, unexpected_message);
         return ret;
     }
@@ -6023,6 +7044,6 @@
     if (ssl->toInfoOn) {
         int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
-        AddPacketInfo(0, &ssl->timeoutInfo, input + *inOutIdx - add,
-                      size + add, ssl->heap);
+        AddPacketInfo(ssl, 0, handshake, input + *inOutIdx - add,
+                      size + add, READ_PROTO, ssl->heap);
         AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
     }
@@ -6054,14 +7075,32 @@
     /* above checks handshake state */
     switch (type) {
-
 #ifndef NO_WOLFSSL_CLIENT
+    /* Messages only recieved by client. */
+    #ifdef WOLFSSL_TLS13_DRAFT_18
     case hello_retry_request:
         WOLFSSL_MSG("processing hello rety request");
         ret = DoTls13HelloRetryRequest(ssl, input, inOutIdx, size);
         break;
+    #endif
 
     case server_hello:
         WOLFSSL_MSG("processing server hello");
-        ret = DoTls13ServerHello(ssl, input, inOutIdx, size);
+        ret = DoTls13ServerHello(ssl, input, inOutIdx, size, &type);
+    #if !defined(WOLFSSL_NO_CLIENT_AUTH) && defined(HAVE_ED25519) && \
+                                                !defined(NO_ED25519_CLIENT_AUTH)
+        if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
+                                               IsAtLeastTLSv1_3(ssl->version)) {
+            ssl->options.cacheMessages = 0;
+            if (ssl->hsHashes->messages != NULL) {
+                XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
+                ssl->hsHashes->messages = NULL;
+            }
+        }
+    #endif
+        break;
+
+    case encrypted_extensions:
+        WOLFSSL_MSG("processing encrypted extensions");
+        ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
         break;
 
@@ -6077,11 +7116,22 @@
         ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
         break;
-
-    case encrypted_extensions:
-        WOLFSSL_MSG("processing encrypted extensions");
-        ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
+#endif /* !NO_WOLFSSL_CLIENT */
+
+#ifndef NO_WOLFSSL_SERVER
+    /* Messages only recieved by server. */
+    case client_hello:
+        WOLFSSL_MSG("processing client hello");
+        ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
         break;
-#endif /* !NO_WOLFSSL_CLIENT */
-
+
+    #ifdef WOLFSSL_EARLY_DATA
+    case end_of_early_data:
+        WOLFSSL_MSG("processing end of early data");
+        ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
+        break;
+    #endif
+#endif /* !NO_WOLFSSL_SERVER */
+
+    /* Messages recieved by both client and server. */
 #ifndef NO_CERTS
     case certificate:
@@ -6098,13 +7148,4 @@
 #endif /* !NO_RSA || HAVE_ECC */
 
-#ifdef WOLFSSL_EARLY_DATA
-    #ifndef NO_WOLFSSL_SERVER
-    case end_of_early_data:
-        WOLFSSL_MSG("processing end of early data");
-        ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
-        break;
-    #endif
-#endif
-
     case finished:
         WOLFSSL_MSG("processing finished");
@@ -6117,11 +7158,4 @@
         break;
 
-#ifndef NO_WOLFSSL_SERVER
-    case client_hello:
-        WOLFSSL_MSG("processing client hello");
-        ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
-        break;
-#endif /* !NO_WOLFSSL_SERVER */
-
     default:
         WOLFSSL_MSG("Unknown handshake message type");
@@ -6134,14 +7168,15 @@
         ssl->error = 0;
 
-
     if (ret == 0 && type != client_hello && type != session_ticket &&
-                             type != key_update && ssl->error != WC_PENDING_E) {
+                                                           type != key_update) {
         ret = HashInput(ssl, input + inIdx, size);
+    }
+    if (ret == 0 && ssl->buffers.inputBuffer.dynamicFlag) {
+        ShrinkInputBuffer(ssl, NO_FORCED_FREE);
     }
 
     if (ret == BUFFER_ERROR || ret == MISSING_HANDSHAKE_DATA)
         SendAlert(ssl, alert_fatal, decode_error);
-
-    if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
+    else if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
             ret == ECC_PEERKEY_ERROR || ret == BAD_KEY_SHARE_DATA ||
             ret == PSK_KEY_ERROR || ret == INVALID_PARAMETER) {
@@ -6150,5 +7185,8 @@
 
     if (ssl->options.tls1_3) {
-        if (type == server_hello && ssl->options.side == WOLFSSL_CLIENT_END) {
+        /* Need to hash input message before deriving secrets. */
+    #ifndef NO_WOLFSSL_CLIENT
+        if (ssl->options.side == WOLFSSL_CLIENT_END) {
+            if (type == server_hello) {
             if ((ret = DeriveEarlySecret(ssl)) != 0)
                 return ret;
@@ -6168,21 +7206,12 @@
 #endif
         }
-#ifdef WOLFSSL_EARLY_DATA
-        if (type == encrypted_extensions &&
-                                      ssl->options.side == WOLFSSL_CLIENT_END) {
-            if (!ssl->earlyData)
-            {
-                if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
-                    return ret;
-            }
-        }
-#endif
-
-        if (type == finished && ssl->options.side == WOLFSSL_CLIENT_END) {
+
+            if (type == finished) {
             if ((ret = DeriveMasterSecret(ssl)) != 0)
                 return ret;
 #ifdef WOLFSSL_EARLY_DATA
             if ((ret = DeriveTls13Keys(ssl, traffic_key,
-                             ENCRYPT_AND_DECRYPT_SIDE, !ssl->earlyData)) != 0) {
+                                       ENCRYPT_AND_DECRYPT_SIDE,
+                                       ssl->earlyData == no_early_data)) != 0) {
                 return ret;
             }
@@ -6194,7 +7223,22 @@
 #endif
         }
-
+        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
+            if (type == certificate_request &&
+                                ssl->options.handShakeState == HANDSHAKE_DONE) {
+                /* reset handshake states */
+                ssl->options.clientState = CLIENT_HELLO_COMPLETE;
+                ssl->options.connectState  = FIRST_REPLY_DONE;
+                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
+
+                if (wolfSSL_connect_TLSv13(ssl) != SSL_SUCCESS)
+                    ret = POST_HAND_AUTH_ERROR;
+            }
+        #endif
+        }
+    #endif /* NO_WOLFSSL_CLIENT */
+
+#ifndef NO_WOLFSSL_SERVER
 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
-        if (type == finished && ssl->options.side == WOLFSSL_SERVER_END) {
+        if (ssl->options.side == WOLFSSL_SERVER_END && type == finished) {
             ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret);
             if (ret != 0)
@@ -6202,4 +7246,5 @@
         }
 #endif
+#endif /* NO_WOLFSSL_SERVER */
     }
 
@@ -6286,7 +7331,7 @@
         if (inputLength + ssl->arrays->pendingMsgOffset >
                                                     ssl->arrays->pendingMsgSz) {
-            return BUFFER_ERROR;
+            inputLength = ssl->arrays->pendingMsgSz -
+                                                  ssl->arrays->pendingMsgOffset;
         }
-
         XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
                 input + *inOutIdx, inputLength);
@@ -6322,4 +7367,5 @@
 }
 
+#ifndef NO_WOLFSSL_CLIENT
 
 /* The client connecting to the server.
@@ -6336,6 +7382,4 @@
 int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
 {
-    int neededState;
-
     WOLFSSL_ENTER("wolfSSL_connect_TLSv13()");
 
@@ -6382,5 +7426,13 @@
             WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
     #ifdef WOLFSSL_EARLY_DATA
-            if (ssl->earlyData) {
+            if (ssl->earlyData != no_early_data) {
+        #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
+                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
+                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
+                    WOLFSSL_ERROR(ssl->error);
+                    return WOLFSSL_FATAL_ERROR;
+                }
+                ssl->options.sentChangeCipher = 1;
+        #endif
                 ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
                 return WOLFSSL_SUCCESS;
@@ -6390,17 +7442,11 @@
 
         case CLIENT_HELLO_SENT:
-            neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
-                                                  SERVER_HELLODONE_COMPLETE;
             /* Get the response/s from the server. */
-            while (ssl->options.serverState < neededState) {
+            while (ssl->options.serverState <
+                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
                 if ((ssl->error = ProcessReply(ssl)) < 0) {
                     WOLFSSL_ERROR(ssl->error);
                     return WOLFSSL_FATAL_ERROR;
                 }
-                /* if resumption failed, reset needed state. */
-                if (neededState == SERVER_FINISHED_COMPLETE &&
-                        !ssl->options.resuming) {
-                    neededState = SERVER_HELLODONE_COMPLETE;
-                }
             }
 
@@ -6414,6 +7460,8 @@
 
             if (!ssl->options.tls1_3) {
+    #ifndef WOLFSSL_NO_TLS12
                 if (ssl->options.downgrade)
                     return wolfSSL_connect(ssl);
+    #endif
 
                 WOLFSSL_MSG("Client using higher version, fatal error");
@@ -6421,6 +7469,16 @@
             }
 
-            if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
-                ssl->options.serverState = NULL_STATE;
+            if (ssl->options.serverState ==
+                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
+        #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
+                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
+                if (!ssl->options.sentChangeCipher) {
+                    if ((ssl->error = SendChangeCipher(ssl)) != 0) {
+                        WOLFSSL_ERROR(ssl->error);
+                        return WOLFSSL_FATAL_ERROR;
+                    }
+                    ssl->options.sentChangeCipher = 1;
+                }
+        #endif
                 /* Try again with different security parameters. */
                 if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
@@ -6435,21 +7493,10 @@
 
         case HELLO_AGAIN_REPLY:
-            if (ssl->options.serverState == NULL_STATE ||
-                                                ssl->error == WC_PENDING_E) {
-                neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
-                                                      SERVER_HELLODONE_COMPLETE;
-
                 /* Get the response/s from the server. */
-                while (ssl->options.serverState < neededState) {
+            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
                     if ((ssl->error = ProcessReply(ssl)) < 0) {
                             WOLFSSL_ERROR(ssl->error);
                             return WOLFSSL_FATAL_ERROR;
                     }
-                    /* if resumption failed, reset needed state */
-                    else if (neededState == SERVER_FINISHED_COMPLETE) {
-                        if (!ssl->options.resuming)
-                            neededState = SERVER_HELLODONE_COMPLETE;
-                    }
-                }
             }
 
@@ -6460,5 +7507,5 @@
         case FIRST_REPLY_DONE:
         #ifdef WOLFSSL_EARLY_DATA
-            if (ssl->earlyData) {
+            if (ssl->earlyData != no_early_data) {
                 if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
                     WOLFSSL_ERROR(ssl->error);
@@ -6474,4 +7521,20 @@
 
         case FIRST_REPLY_FIRST:
+        #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
+                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
+            if (!ssl->options.sentChangeCipher) {
+                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
+                    WOLFSSL_ERROR(ssl->error);
+                    return WOLFSSL_FATAL_ERROR;
+                }
+                ssl->options.sentChangeCipher = 1;
+            }
+        #endif
+
+            ssl->options.connectState = FIRST_REPLY_SECOND;
+            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
+            FALL_THROUGH;
+
+        case FIRST_REPLY_SECOND:
         #ifndef NO_CERTS
             if (!ssl->options.resuming && ssl->options.sendVerify) {
@@ -6485,10 +7548,9 @@
         #endif
 
-            ssl->options.connectState = FIRST_REPLY_SECOND;
-            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
+            ssl->options.connectState = FIRST_REPLY_THIRD;
+            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
             FALL_THROUGH;
 
-        case FIRST_REPLY_SECOND:
-
+        case FIRST_REPLY_THIRD:
         #ifndef NO_CERTS
             if (!ssl->options.resuming && ssl->options.sendVerify) {
@@ -6502,9 +7564,9 @@
         #endif
 
-            ssl->options.connectState = FIRST_REPLY_THIRD;
-            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
+            ssl->options.connectState = FIRST_REPLY_FOURTH;
+            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
             FALL_THROUGH;
 
-        case FIRST_REPLY_THIRD:
+        case FIRST_REPLY_FOURTH:
             if ((ssl->error = SendTls13Finished(ssl)) != 0) {
                 WOLFSSL_ERROR(ssl->error);
@@ -6529,4 +7591,8 @@
         #endif /* NO_HANDSHAKE_DONE_CB */
 
+            if (!ssl->options.keepResources) {
+                FreeHandshakeResources(ssl);
+            }
+
             WOLFSSL_LEAVE("wolfSSL_connect_TLSv13()", WOLFSSL_SUCCESS);
             return WOLFSSL_SUCCESS;
@@ -6537,6 +7603,7 @@
     }
 }
-
-#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
+#endif
+
+#if defined(WOLFSSL_SEND_HRR_COOKIE)
 /* Send a cookie with the HelloRetryRequest to avoid storing state.
  *
@@ -6556,4 +7623,5 @@
     if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
         return BAD_FUNC_ARG;
+ #ifndef NO_WOLFSSL_SERVER
     if (ssl->options.side == WOLFSSL_CLIENT_END)
         return SIDE_ERROR;
@@ -6602,5 +7670,13 @@
     ssl->options.sendCookie = 1;
 
-    return WOLFSSL_SUCCESS;
+    ret = WOLFSSL_SUCCESS;
+#else
+    (void)secret;
+    (void)secretSz;
+
+    ret = SIDE_ERROR;
+#endif
+
+    return ret;
 }
 #endif
@@ -6619,6 +7695,4 @@
     if (ssl == NULL)
         return BAD_FUNC_ARG;
-    if (ssl->options.side == WOLFSSL_SERVER_END)
-        return SIDE_ERROR;
 
     ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL);
@@ -6748,5 +7822,5 @@
  *
  * ctx  The SSL/TLS CTX object.
- * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
+ * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a client and
  * 0 on success.
  */
@@ -6767,5 +7841,5 @@
  * ssl  The SSL/TLS object.
  * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
- * SIDE_ERROR when not a server and 0 on success.
+ * SIDE_ERROR when not a client and 0 on success.
  */
 int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
@@ -6790,8 +7864,11 @@
 {
     int         ret;
+#ifndef NO_WOLFSSL_SERVER
     CertReqCtx* certReqCtx;
+#endif
 
     if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
         return BAD_FUNC_ARG;
+#ifndef NO_WOLFSSL_SERVER
     if (ssl->options.side == WOLFSSL_CLIENT_END)
         return SIDE_ERROR;
@@ -6812,4 +7889,8 @@
     ssl->certReqCtx = certReqCtx;
 
+    ssl->msgsReceived.got_certificate = 0;
+    ssl->msgsReceived.got_certificate_verify = 0;
+    ssl->msgsReceived.got_finished = 0;
+
     ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
     if (ret == WANT_WRITE)
@@ -6817,7 +7898,164 @@
     else if (ret == 0)
         ret = WOLFSSL_SUCCESS;
+#else
+    ret = SIDE_ERROR;
+#endif
+
     return ret;
 }
 #endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
+
+#if !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
+/* Get the preferred key exchange group.
+ *
+ * ssl  The SSL/TLS object.
+ * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3,
+ * SIDE_ERROR when not a client, NOT_READY_ERROR when handshake not complete
+ * and group number on success.
+ */
+int wolfSSL_preferred_group(WOLFSSL* ssl)
+{
+    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
+        return BAD_FUNC_ARG;
+#ifndef NO_WOLFSSL_CLIENT
+    if (ssl->options.side == WOLFSSL_SERVER_END)
+        return SIDE_ERROR;
+    if (ssl->options.handShakeState != HANDSHAKE_DONE)
+        return NOT_READY_ERROR;
+
+    /* Return supported groups only. */
+    return TLSX_SupportedCurve_Preferred(ssl, 1);
+#else
+    return SIDE_ERROR;
+#endif
+}
+#endif
+
+/* Sets the key exchange groups in rank order on a context.
+ *
+ * ctx     SSL/TLS context object.
+ * groups  Array of groups.
+ * count   Number of groups in array.
+ * returns BAD_FUNC_ARG when ctx or groups is NULL, not using TLS v1.3 or
+ * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
+ */
+int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, int count)
+{
+    int i;
+
+    if (ctx == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
+        return BAD_FUNC_ARG;
+    if (!IsAtLeastTLSv1_3(ctx->method->version))
+        return BAD_FUNC_ARG;
+
+    for (i = 0; i < count; i++)
+        ctx->group[i] = (word16)groups[i];
+    ctx->numGroups = (byte)count;
+
+    return WOLFSSL_SUCCESS;
+}
+
+/* Sets the key exchange groups in rank order.
+ *
+ * ssl     SSL/TLS object.
+ * groups  Array of groups.
+ * count   Number of groups in array.
+ * returns BAD_FUNC_ARG when ssl or groups is NULL, not using TLS v1.3 or
+ * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
+ */
+int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count)
+{
+    int i;
+
+    if (ssl == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
+        return BAD_FUNC_ARG;
+    if (!IsAtLeastTLSv1_3(ssl->version))
+        return BAD_FUNC_ARG;
+
+    for (i = 0; i < count; i++)
+        ssl->group[i] = (word16)groups[i];
+    ssl->numGroups = (byte)count;
+
+    return WOLFSSL_SUCCESS;
+}
+
+#ifndef NO_PSK
+void wolfSSL_CTX_set_psk_client_tls13_callback(WOLFSSL_CTX* ctx,
+                                               wc_psk_client_tls13_callback cb)
+{
+    WOLFSSL_ENTER("SSL_CTX_set_psk_client_tls13_callback");
+
+    if (ctx == NULL)
+        return;
+
+    ctx->havePSK = 1;
+    ctx->client_psk_tls13_cb = cb;
+}
+
+
+void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl,
+                                           wc_psk_client_tls13_callback cb)
+{
+    byte haveRSA = 1;
+    int  keySz   = 0;
+
+    WOLFSSL_ENTER("SSL_set_psk_client_tls13_callback");
+
+    if (ssl == NULL)
+        return;
+
+    ssl->options.havePSK = 1;
+    ssl->options.client_psk_tls13_cb = cb;
+
+    #ifdef NO_RSA
+        haveRSA = 0;
+    #endif
+    #ifndef NO_CERTS
+        keySz = ssl->buffers.keySz;
+    #endif
+    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
+               ssl->options.haveDH, ssl->options.haveNTRU,
+               ssl->options.haveECDSAsig, ssl->options.haveECC,
+               ssl->options.haveStaticECC, ssl->options.side);
+}
+
+
+void wolfSSL_CTX_set_psk_server_tls13_callback(WOLFSSL_CTX* ctx,
+                                               wc_psk_server_tls13_callback cb)
+{
+    WOLFSSL_ENTER("SSL_CTX_set_psk_server_tls13_callback");
+    if (ctx == NULL)
+        return;
+    ctx->havePSK = 1;
+    ctx->server_psk_tls13_cb = cb;
+}
+
+
+void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl,
+                                           wc_psk_server_tls13_callback cb)
+{
+    byte haveRSA = 1;
+    int  keySz   = 0;
+
+    WOLFSSL_ENTER("SSL_set_psk_server_tls13_callback");
+    if (ssl == NULL)
+        return;
+
+    ssl->options.havePSK = 1;
+    ssl->options.server_psk_tls13_cb = cb;
+
+    #ifdef NO_RSA
+        haveRSA = 0;
+    #endif
+    #ifndef NO_CERTS
+        keySz = ssl->buffers.keySz;
+    #endif
+    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
+               ssl->options.haveDH, ssl->options.haveNTRU,
+               ssl->options.haveECDSAsig, ssl->options.haveECC,
+               ssl->options.haveStaticECC, ssl->options.side);
+}
+#endif
+
 
 #ifndef NO_WOLFSSL_SERVER
@@ -6836,5 +8074,4 @@
 {
     word16 havePSK = 0;
-    word16 haveAnon = 0;
     WOLFSSL_ENTER("SSL_accept_TLSv13()");
 
@@ -6847,9 +8084,4 @@
 #endif
     (void)havePSK;
-
-#ifdef HAVE_ANON
-    haveAnon = ssl->options.haveAnon;
-#endif
-    (void)haveAnon;
 
     if (ssl->options.side != WOLFSSL_SERVER_END) {
@@ -6859,14 +8091,25 @@
 
 #ifndef NO_CERTS
-    /* in case used set_accept_state after init */
-    if (!havePSK && !haveAnon &&
-        (!ssl->buffers.certificate ||
-         !ssl->buffers.certificate->buffer ||
-         !ssl->buffers.key ||
-         !ssl->buffers.key->buffer)) {
-        WOLFSSL_MSG("accept error: don't have server cert and key");
-        ssl->error = NO_PRIVATE_KEY;
-        WOLFSSL_ERROR(ssl->error);
+    /* allow no private key if using PK callbacks and CB is set */
+    if (!havePSK) {
+        if (!ssl->buffers.certificate ||
+            !ssl->buffers.certificate->buffer) {
+
+            WOLFSSL_MSG("accept error: server cert required");
+            WOLFSSL_ERROR(ssl->error = NO_PRIVATE_KEY);
         return WOLFSSL_FATAL_ERROR;
+    }
+
+    #ifdef HAVE_PK_CALLBACKS
+        if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
+            WOLFSSL_MSG("Using PK for server private key");
+        }
+        else
+    #endif
+        if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
+            WOLFSSL_MSG("accept error: server key required");
+            WOLFSSL_ERROR(ssl->error = NO_PRIVATE_KEY);
+            return WOLFSSL_FATAL_ERROR;
+        }
     }
 #endif
@@ -6895,18 +8138,21 @@
     switch (ssl->options.acceptState) {
 
-        case ACCEPT_BEGIN :
-            /* get response */
-            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
+        case TLS13_ACCEPT_BEGIN :
+            /* get client_hello */
+            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
                 if ((ssl->error = ProcessReply(ssl)) < 0) {
                     WOLFSSL_ERROR(ssl->error);
                     return WOLFSSL_FATAL_ERROR;
                 }
-
-            ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
+            }
+
+            ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
             WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
             FALL_THROUGH;
 
-        case ACCEPT_CLIENT_HELLO_DONE :
-            if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
+        case TLS13_ACCEPT_CLIENT_HELLO_DONE :
+#ifdef WOLFSSL_TLS13_DRAFT_18
+            if (ssl->options.serverState ==
+                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
                 if ((ssl->error = SendTls13HelloRetryRequest(ssl)) != 0) {
                     WOLFSSL_ERROR(ssl->error);
@@ -6914,38 +8160,97 @@
                 }
             }
-            ssl->options.acceptState = ACCEPT_HELLO_RETRY_REQUEST_DONE;
-            WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
+
+            ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
+            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
             FALL_THROUGH;
 
-        case ACCEPT_HELLO_RETRY_REQUEST_DONE :
-            if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
-                if ( (ssl->error = ProcessReply(ssl)) < 0) {
+        case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
+#else
+            if (ssl->options.serverState ==
+                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
+                if ((ssl->error = SendTls13ServerHello(ssl,
+                                                   hello_retry_request)) != 0) {
                     WOLFSSL_ERROR(ssl->error);
                     return WOLFSSL_FATAL_ERROR;
                 }
             }
-            ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
+
+            ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
+            WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
+            FALL_THROUGH;
+
+        case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
+    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
+            if (ssl->options.serverState ==
+                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
+                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
+                    WOLFSSL_ERROR(ssl->error);
+                    return WOLFSSL_FATAL_ERROR;
+                }
+                ssl->options.sentChangeCipher = 1;
+            }
+    #endif
+            ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
             WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
             FALL_THROUGH;
-
-        case ACCEPT_FIRST_REPLY_DONE :
-            if ((ssl->error = SendTls13ServerHello(ssl)) != 0) {
+#endif
+
+        case TLS13_ACCEPT_FIRST_REPLY_DONE :
+            if (ssl->options.serverState ==
+                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
+                ssl->options.clientState = CLIENT_HELLO_RETRY;
+                while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
+                    if ((ssl->error = ProcessReply(ssl)) < 0) {
+                        WOLFSSL_ERROR(ssl->error);
+                        return WOLFSSL_FATAL_ERROR;
+                    }
+                }
+            }
+
+            ssl->options.acceptState = TLS13_ACCEPT_SECOND_REPLY_DONE;
+            WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
+            FALL_THROUGH;
+
+        case TLS13_ACCEPT_SECOND_REPLY_DONE :
+            if ((ssl->error = SendTls13ServerHello(ssl, server_hello)) != 0) {
                 WOLFSSL_ERROR(ssl->error);
                 return WOLFSSL_FATAL_ERROR;
             }
-            ssl->options.acceptState = SERVER_HELLO_SENT;
+            ssl->options.acceptState = TLS13_SERVER_HELLO_SENT;
             WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
             FALL_THROUGH;
 
-        case SERVER_HELLO_SENT :
+        case TLS13_SERVER_HELLO_SENT :
+    #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
+                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
+            if (!ssl->options.sentChangeCipher) {
+                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
+                    WOLFSSL_ERROR(ssl->error);
+                    return WOLFSSL_FATAL_ERROR;
+                }
+                ssl->options.sentChangeCipher = 1;
+            }
+    #endif
+
+            ssl->options.acceptState = TLS13_ACCEPT_THIRD_REPLY_DONE;
+            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
+            FALL_THROUGH;
+
+        case TLS13_ACCEPT_THIRD_REPLY_DONE :
+            if (!ssl->options.noPskDheKe) {
+                ssl->error = TLSX_KeyShare_DeriveSecret(ssl);
+                if (ssl->error != 0)
+                    return WOLFSSL_FATAL_ERROR;
+            }
+
             if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
                 WOLFSSL_ERROR(ssl->error);
                 return WOLFSSL_FATAL_ERROR;
             }
-            ssl->options.acceptState = SERVER_EXTENSIONS_SENT;
+            ssl->options.acceptState = TLS13_SERVER_EXTENSIONS_SENT;
             WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
             FALL_THROUGH;
 
-        case SERVER_EXTENSIONS_SENT :
+        case TLS13_SERVER_EXTENSIONS_SENT :
 #ifndef NO_CERTS
             if (!ssl->options.resuming) {
@@ -6959,10 +8264,9 @@
             }
 #endif
-            ssl->options.acceptState = CERT_REQ_SENT;
+            ssl->options.acceptState = TLS13_CERT_REQ_SENT;
             WOLFSSL_MSG("accept state CERT_REQ_SENT");
             FALL_THROUGH;
 
-        case CERT_REQ_SENT :
-            ssl->options.acceptState = KEY_EXCHANGE_SENT;
+        case TLS13_CERT_REQ_SENT :
 #ifndef NO_CERTS
             if (!ssl->options.resuming && ssl->options.sendVerify) {
@@ -6973,9 +8277,9 @@
             }
 #endif
-            ssl->options.acceptState = CERT_SENT;
+            ssl->options.acceptState = TLS13_CERT_SENT;
             WOLFSSL_MSG("accept state CERT_SENT");
             FALL_THROUGH;
 
-        case CERT_SENT :
+        case TLS13_CERT_SENT :
 #ifndef NO_CERTS
             if (!ssl->options.resuming && ssl->options.sendVerify) {
@@ -6986,9 +8290,9 @@
             }
 #endif
-            ssl->options.acceptState = CERT_STATUS_SENT;
-            WOLFSSL_MSG("accept state CERT_STATUS_SENT");
+            ssl->options.acceptState = TLS13_CERT_VERIFY_SENT;
+            WOLFSSL_MSG("accept state CERT_VERIFY_SENT");
             FALL_THROUGH;
 
-        case CERT_VERIFY_SENT :
+        case TLS13_CERT_VERIFY_SENT :
             if ((ssl->error = SendTls13Finished(ssl)) != 0) {
                 WOLFSSL_ERROR(ssl->error);
@@ -6996,8 +8300,8 @@
             }
 
-            ssl->options.acceptState = ACCEPT_FINISHED_DONE;
-            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
+            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_SENT;
+            WOLFSSL_MSG("accept state ACCEPT_FINISHED_SENT");
 #ifdef WOLFSSL_EARLY_DATA
-            if (ssl->earlyData) {
+            if (ssl->earlyData != no_early_data) {
                 ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
                 return WOLFSSL_SUCCESS;
@@ -7006,5 +8310,5 @@
             FALL_THROUGH;
 
-        case ACCEPT_FINISHED_DONE :
+        case TLS13_ACCEPT_FINISHED_SENT :
 #ifdef HAVE_SESSION_TICKET
     #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
@@ -7018,9 +8322,9 @@
     #endif
 #endif /* HAVE_SESSION_TICKET */
-            ssl->options.acceptState = TICKET_SENT;
+            ssl->options.acceptState = TLS13_PRE_TICKET_SENT;
             WOLFSSL_MSG("accept state  TICKET_SENT");
             FALL_THROUGH;
 
-        case TICKET_SENT:
+        case TLS13_PRE_TICKET_SENT :
             while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
                 if ( (ssl->error = ProcessReply(ssl)) < 0) {
@@ -7029,9 +8333,9 @@
                 }
 
-            ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
-            WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
+            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_DONE;
+            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
             FALL_THROUGH;
 
-        case ACCEPT_SECOND_REPLY_DONE :
+        case TLS13_ACCEPT_FINISHED_DONE :
 #ifdef HAVE_SESSION_TICKET
     #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
@@ -7048,9 +8352,9 @@
             }
 #endif /* HAVE_SESSION_TICKET */
-            ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
-            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
+            ssl->options.acceptState = TLS13_TICKET_SENT;
+            WOLFSSL_MSG("accept state TICKET_SENT");
             FALL_THROUGH;
 
-        case ACCEPT_THIRD_REPLY_DONE:
+        case TLS13_TICKET_SENT :
 #ifndef NO_HANDSHAKE_DONE_CB
             if (ssl->hsDoneCb) {
@@ -7064,4 +8368,8 @@
 #endif /* NO_HANDSHAKE_DONE_CB */
 
+            if (!ssl->options.keepResources) {
+                FreeHandshakeResources(ssl);
+            }
+
             WOLFSSL_LEAVE("SSL_accept()", WOLFSSL_SUCCESS);
             return WOLFSSL_SUCCESS;
@@ -7140,11 +8448,12 @@
         return BAD_FUNC_ARG;
 
+#ifndef NO_WOLFSSL_CLIENT
     if (ssl->options.side == WOLFSSL_SERVER_END)
         return SIDE_ERROR;
 
     if (ssl->options.handShakeState == NULL_STATE) {
-        ssl->earlyData = 1;
+        ssl->earlyData = expecting_early_data;
         ret = wolfSSL_connect_TLSv13(ssl);
-        if (ret <= 0)
+        if (ret != WOLFSSL_SUCCESS)
             return WOLFSSL_FATAL_ERROR;
     }
@@ -7154,4 +8463,7 @@
             *outSz = ret;
     }
+#else
+    return SIDE_ERROR;
+#endif
 
     WOLFSSL_LEAVE("SSL_write_early_data()", ret);
@@ -7174,5 +8486,5 @@
 int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
 {
-    int ret;
+    int ret = 0;
 
     WOLFSSL_ENTER("wolfSSL_read_early_data()");
@@ -7184,9 +8496,10 @@
         return BAD_FUNC_ARG;
 
+#ifndef NO_WOLFSSL_SERVER
     if (ssl->options.side == WOLFSSL_CLIENT_END)
         return SIDE_ERROR;
 
     if (ssl->options.handShakeState == NULL_STATE) {
-        ssl->earlyData = 1;
+        ssl->earlyData = expecting_early_data;
         ret = wolfSSL_accept_TLSv13(ssl);
         if (ret <= 0)
@@ -7202,4 +8515,7 @@
     else
         ret = 0;
+#else
+    return SIDE_ERROR;
+#endif
 
     WOLFSSL_LEAVE("wolfSSL_read_early_data()", ret);
